接收系统广播监听网络变化

package com.example.broadcastdemo;

import android.app.Activity;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.net.ConnectivityManager;
import android.net.Network;
import android.net.NetworkInfo;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import android.widget.Toast;

public class MainActivity extends Activity {

	private IntentFilter filter  ;
	private NetwokChangeReceiver reciever ;
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_main);
		filter = new IntentFilter() ;
		filter.addAction("android.net.conn.CONNECTIVITY_CHANGE");
		reciever  = new NetwokChangeReceiver() ;
		registerReceiver(reciever, filter) ;
	}
	@Override
	protected void onDestroy() {
		// TODO Auto-generated method stub
		super.onDestroy();
		unregisterReceiver(reciever);
	}
	
	class NetwokChangeReceiver extends BroadcastReceiver {
		@Override
		public void onReceive(Context context, Intent intent) {
			// TODO Auto-generated method stub
			//Toast.makeText(context, "网络环境发生改变", Toast.LENGTH_LONG).show();
			ConnectivityManager connectionManager = (ConnectivityManager)getSystemService(Context.CONNECTIVITY_SERVICE) ;
			NetworkInfo info = connectionManager.getActiveNetworkInfo() ;
			if(info != null && info.isAvailable()) {
				Toast.makeText(context, "网络可用", Toast.LENGTH_LONG).show();
			} else {
				Toast.makeText(context, "网络不可用", Toast.LENGTH_LONG).show();
			}
			
		}
	}
}

别忘了在权限里声明     


你可能感兴趣的:(android)