赞
踩
主页面:
public class MainActivity extends Activity {
public static final String CONNECTIVITY_CHANGE_ACTION = "android.net.conn.CONNECTIVITY_CHANGE";
MyReceiver mr = new MyReceiver();
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
registerDateTransReceiver();
if(Utils.getActiveNetwork(MainActivity.this)==null){
Toast.makeText(this, "没有网络!", Toast.LENGTH_LONG).show();
}else{
Toast.makeText(this, "网络良好!", Toast.LENGTH_LONG).show();
}
}
private void registerDateTransReceiver() {
Log.i("TAG", "register receiver " + CONNECTIVITY_CHANGE_ACTION);
IntentFilter filter = new IntentFilter();
filter.addAction(CONNECTIVITY_CHANGE_ACTION);
filter.setPriority(1000);
registerReceiver(mr, filter);
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
@Override
public void onBackPressed() {
// TODO Auto-generated method stub
super.onBackPressed();
unregisterReceiver(mr);
finish();
}
}
工具类:
public static final String CONNECTIVITY_CHANGE_ACTION = "android.net.conn.CONNECTIVITY_CHANGE";
MyReceiver mr = new MyReceiver();
public static NetworkInfo getActiveNetwork(Context context){
if (context == null)
return null;
ConnectivityManager mConnMgr = (ConnectivityManager) context
.getSystemService(Context.CONNECTIVITY_SERVICE);
if (mConnMgr == null)
return null;
NetworkInfo aActiveInfo = mConnMgr.getActiveNetworkInfo(); // 获取活动网络连接信息
return aActiveInfo;
}
MyRecevier:
public class MyReceiver extends BroadcastReceiver {
public static final String CONNECTIVITY_CHANGE_ACTION = "android.net.conn.CONNECTIVITY_CHANGE";
@Override
public void onReceive(Context context, Intent intent) {
String action = intent.getAction();
Log.i("TAG", "PfDataTransReceiver receive action " + action);
if(TextUtils.equals(action, CONNECTIVITY_CHANGE_ACTION)){//网络变化的时候会发送通知
Log.i("TAG", "网络变化了");
return;
}
}
}
最后在mainfaintext,xml文件中添加权限:<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE"/>
添加广播:
<receiver android:name="MyReceiver">
<intent-filter >
<action android:name="android.net.conn.CONNECTIVITY_CHANGE"/>
</intent-filter>
</receiver>
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。