标签:
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE"/>
<uses-permission android:name="android.permission.ACCESS_WIFI_STATE"/>
<uses-permission android:name="android.permission.INTERNET"/>
- 在界面中,存在一个按钮,单击按钮的情况下,判断当前的网络连接状态,分别在连接网络状态和未连接网络状态下,提示相关信息。代码如下:
public class MainActivity extends Activity {
private Button button;//对应的按钮
private ConnectivityManager connetivityManager;//
private NotificationManager notificationManager;// 通知用户网络状况
private BroadcastReceiver broadcastReceiver = new BroadcastReceiver() {@Override
public void onReceive(Context contex, Intent intent) {
// TODO Auto-generated method stub
// 网络状况
NetworkInfo mobileInfo = connetivityManager
.getNetworkInfo(ConnectivityManager.TYPE_MOBILE);
NetworkInfo wifiInfo = connetivityManager
.getNetworkInfo(ConnectivityManager.TYPE_WIFI);Notification.Builder builder = new Notification.Builder(
MainActivity.this);
builder.setContentTitle("提示信息");
builder.setSmallIcon(R.drawable.ic_launcher);
if (!mobileInfo.isConnected() && !wifiInfo.isConnected()) {
builder.setContentText("网络状态有异常");
} else {
builder.setContentText("网络正常");
}
notificationManager.notify(1001, builder.build());
}
};@Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.mainactivity);
button = (Button) findViewById(R.id.button1);
button.setOnClickListener(new OnClickListener() {@Override
public void onClick(View arg0) {
// TODO Auto-generated method stub
IntentFilter intentFilter = new IntentFilter();
intentFilter.addAction(ConnectivityManager.CONNECTIVITY_ACTION);
registerReceiver(broadcastReceiver, intentFilter);
connetivityManager = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
notificationManager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
}
});
}// 卸载广播
@Override
protected void onPause() {
// TODO Auto-generated method stub
super.onPause();
if (broadcastReceiver != null) {
unregisterReceiver(broadcastReceiver);
}
}
}
标签:
原文地址:http://www.cnblogs.com/Yellow0-0River/p/4237616.html