广播的基本使用,判断是否有可用网络,并弹出设置窗口

1、MainActivity

  1. package lpc.com.project521;
  2. import android.app.Activity;
  3. import android.content.BroadcastReceiver;
  4. import android.content.Context;
  5. import android.content.Intent;
  6. import android.content.IntentFilter;
  7. import android.net.ConnectivityManager;
  8. import android.net.NetworkInfo;
  9. import android.os.Bundle;
  10. import android.provider.Settings;
  11. import android.widget.Toast;
  12. public class MainActivity extends Activity {
  13. private IntentFilter intentFilter;
  14. private NetworkChangeReceiver networkChangeReceiver;
  15. @Override
  16. protected void onCreate(Bundle savedInstanceState) {
  17. super.onCreate(savedInstanceState);
  18. setContentView(R.layout.activity_main);
  19. intentFilter = new IntentFilter();
  20. intentFilter.addAction("android.net.conn.CONNECTIVITY_CHANGE");//android.net.conn.CONNECTIVITY_CHANGE是网络发生变化时的事件,将此事件和自定义的广播绑定之后,当发生网络状态改变的情况,就会调用自定义广播里的操作,此处是跳出设置窗口
  21. networkChangeReceiver = new NetworkChangeReceiver();
  22. registerReceiver(networkChangeReceiver,intentFilter);
  23. }
  24. private class NetworkChangeReceiver extends BroadcastReceiver{
  25. @Override
  26. public void onReceive(Context context, Intent intent) {
  27. ConnectivityManager connectivityManager = (ConnectivityManager)
  28. getSystemService(CONNECTIVITY_SERVICE);
  29. NetworkInfo networkInfo = connectivityManager.getActiveNetworkInfo();
  30. if (networkInfo !=null && networkInfo.isAvailable()){
  31. Toast.makeText(context,"网络可用",Toast.LENGTH_SHORT).show();
  32. }else {
  33. Toast.makeText(context,"网络不可用,请设置网络",Toast.LENGTH_SHORT).show();
  34. intent = new Intent(Settings.ACTION_SETTINGS);
  35. startActivity(intent);
  36. }
  37. }
  38. }
  39. @Override
  40. protected void onDestroy() {
  41. super.onDestroy();
  42. unregisterReceiver(networkChangeReceiver);
  43. }
  44. }

2、manifest文件

  1. <?xml version="1.0" encoding="utf-8"?>
  2. <manifest xmlns:android="http://schemas.android.com/apk/res/android"
  3. package="lpc.com.project521">
  4. <uses-permission android:name="android.permission.ACCESS_NETWORK_STATE"/>
  5. <application
  6. android:allowBackup="true"
  7. android:icon="@mipmap/ic_launcher"
  8. android:label="@string/app_name"
  9. android:supportsRtl="true"
  10. android:theme="@style/AppTheme">
  11. <activity android:name=".MainActivity">
  12. <intent-filter>
  13. <action android:name="android.intent.action.MAIN" />
  14. <category android:name="android.intent.category.LAUNCHER" />
  15. </intent-filter>
  16. </activity>
  17. </application>
  18. </manifest>

运行结果,当开启网络时,提示网络可用,当网络不可用(wifi和移动网络都不可用时,弹出网络不可用,并弹出设置 窗口)




posted @ 2015-12-22 16:33  liupengcheng  阅读(173)  评论(0编辑  收藏  举报