[android] 网络断开的监听
标签:
android网络监听杂谈 |
分类: Android |
[转自] http://blog.sina.com.cn/s/blog_5d5996d001012o07.html
其实手机在网络方面的的监听也比较重要,有时候我们必须实时监控这个程序的实时网络状态,android在网络断开与连接的时候都会发出广播,我们通过接收系统的广播就可以实现网络的监听,下面是代码---
onCreate的时候实例化
//监听器
private NetState receiver=new NetState();
private IntentFilter filter=new IntentFilter();
filter.addAction(ConnectivityManager.CONNECTIVITY_ACTION);
this.registerReceiver(receiver,
filter);
receiver.onReceive(this,
null);
一个广播接收类-
private class NetState extends BroadcastReceiver{
@Override
public void
onReceive(Context arg0, Intent arg1) {
ConnectivityManager
manager =
(ConnectivityManager)con.getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo gprs =
manager.getNetworkInfo(ConnectivityManager.TYPE_MOBILE);
NetworkInfo wifi =
manager.getNetworkInfo(ConnectivityManager.TYPE_WIFI);
if(!gprs.isConnected() && !wifi.isConnected())
{
AlertDialog.Builder ab=new
AlertDialog.Builder(con);
//设定标题
ab.setMessage("网络连接断开,请检查网络");
//设定退出按钮
//网络设置按钮
ab.setPositiveButton("确定", new
DialogInterface.OnClickListener() {
@Override
public
void onClick(DialogInterface dialog, int which) {
//
TODO Auto-generated method stub
dialog.dismiss();
ShakeActivity.this.finish();
}
}).show();
}
}
}