Android网络状态监听

本教程实现Android网络状态实时监听

MainActivity中

public class FirstActivity extends Activity implements OnClickListener {
	private IntentFilter intentFilter;
	private NetworkChangReceiver networkChangeReceiver;
	@Override
	protected void onCreate(Bundle arg0) {
		super.onCreate(arg0);
		setContentView(R.layout.activity_first);

		// 实现网络状态监听
		intentFilter = new IntentFilter();
		intentFilter.addAction("android.net.conn.CONNECTIVITY_CHANGE");
		networkChangeReceiver = new NetworkChangReceiver();
		registerReceiver(networkChangeReceiver, intentFilter);

	}



	protected void onDestroy() {
		// TODO Auto-generated method stub
		super.onDestroy();
		unregisterReceiver(networkChangeReceiver);
	}

	class NetworkChangReceiver extends BroadcastReceiver {
		@Override
		public void onReceive(Context context, Intent intent) {
			ConnectivityManager connectivityManager = (ConnectivityManager) getSystemService(
					Context.CONNECTIVITY_SERVICE);
			NetworkInfo networkInfo = connectivityManager.getActiveNetworkInfo();
			if (networkInfo != null && networkInfo.isAvailable()) {
				 Toast.makeText(getApplicationContext(),
				 "有网",Toast.LENGTH_SHORT).show();
				
			} else {
				 Toast.makeText(getApplicationContext(),
				 "没网",Toast.LENGTH_SHORT).show();
			}
		}

	}


}
更多教程 关注 Kebin.Wang

你可能感兴趣的:(Android网络状态监听)