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();
}
}

}


}


本文标题:Android网络状态监听

文章作者:Kebin.Wang

发布时间:2018年06月02日 - 00:06

原始链接:https://yyping.top/android_02/

许可协议: 署名-非商业性使用-禁止演绎 转载请保留原文链接及作者。

坚持原创技术分享,您的支持将鼓励我继续创作!

分享到: