动态注册:不打开程序无法接受广播
![](https://i-blog.csdnimg.cn/blog_migrate/8f900a89c6347c561fdf2122f13be562.gif)
![](https://i-blog.csdnimg.cn/blog_migrate/961ddebeb323a10fe0623af514929fc1.gif)
1 public class MyBRReceiver extends BroadcastReceiver{ 2 @Override 3 public void onReceive(Context context, Intent intent) { 4 Toast.makeText(context,"网络状态发生改变",Toast.LENGTH_SHORT).show(); 5 } 6 } 7 MainActivity.java中动态注册广播: 8 public class MainActivity extends AppCompatActivity { 9 10 MyBRReceiver myReceiver; 11 12 @Override 13 protected void onCreate(Bundle savedInstanceState) { 14 super.onCreate(savedInstanceState); 15 setContentView(R.layout.activity_main); 16 //核心部分代码: 17 myReceiver = new MyBRReceiver(); 18 IntentFilter itFilter = new IntentFilter(); 19 itFilter.addAction("android.net.conn.CONNECTIVITY_CHANGE"); 20 registerReceiver(myReceiver, itFilter); 21 } 22 23 //别忘了将广播取消掉哦~ 24 @Override 25 protected void onDestroy() { 26 super.onDestroy(); 27 unregisterReceiver(myReceiver); 28 } 29 }
静态注册:Android 4.3以上的版本,是允许将程序安装到SD卡上的,就会收不到开机广播
![](https://i-blog.csdnimg.cn/blog_migrate/8f900a89c6347c561fdf2122f13be562.gif)
![](https://i-blog.csdnimg.cn/blog_migrate/961ddebeb323a10fe0623af514929fc1.gif)
1 public class MyBroadCastReceiver extends BroadcastReceiver { 2 3 @Override 4 public void onReceive(Context context, Intent intent) { 5 // TODO Auto-generated method stub 6 if("android.intent.action.BOOT_COMPLETED".equals(intent.getAction())) 7 { 8 Toast.makeText(context, "开机完成",Toast.LENGTH_LONG); 9 } 10 } 11 12 }
![](https://i-blog.csdnimg.cn/blog_migrate/8f900a89c6347c561fdf2122f13be562.gif)
![](https://i-blog.csdnimg.cn/blog_migrate/961ddebeb323a10fe0623af514929fc1.gif)
1 <receiver android:name=".BootCompleteReceiver"> 2 <intent-filter> 3 <action android:name = "android.intent.cation.BOOT_COMPLETED"/> 4 </intent-filter> 5 </receiver> 6 7 <!-- 权限 --> 8 <uses-permission android:name="android.permission.RECEIVE_BOOT_COMPLETED"/>