静态注册:也就是在AndroidManifest进行注册。这种注册只要应用程序运行起来之后,那么广播接收器就一直存在。
1,首先需要在AndroidMainfiest里面注册广播:
<application
android:allowBackup="true"
android:icon="@mipmap/ic_launcher"
android:label="@string/app_name"
android:roundIcon="@mipmap/ic_launcher_round"
android:supportsRtl="true"
android:theme="@style/AppTheme">
<activity android:name=".MainActivity">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<receiver android:name="com.example.myactivity.MyReceiver">
<intent-filter>
<action android:name="hello.test"/>
</intent-filter>
</receiver>
</application>
2,新建一个MyReceiver类继承自BroadcastReceiver并实现onReceiver()方法,在这个方法里面实现接受广播之后所要处理的事情:
public class MyReceiver extends BroadcastReceiver {
@Override
public void onReceive(Context context, Intent intent) {
Toast.makeText(context,"接收到了广播",Toast.LENGTH_SHORT).show();
}
}
3,在MainActivity里面实现点击按钮发送一个广播:
button.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Intent intent=new Intent("hello.test");
sendBroadcast(intent);
}
});
其中Intent表示所要广播到那个活动,然后去AndroidMainfest里面查查找注册了这个活动的广播接收器。
有一点需要注意:在onReceive()方法里面不能处理过于耗时的代码,规定不能超过十秒。超过十秒的话就会报ANR这种异常。因为程序认为这是没有响应。如果确定BroadcastReceiver要实现比较耗时的处理,那么就考虑使用启动服务来处理。
动态注册:希望在用的时候才注册,不使用的时候不去注册
button_send=findViewById(R.id.send_brocast);
myReceiver=new MyReceiver();
IntentFilter intentFilter=new IntentFilter("hello.test");
registerReceiver(myReceiver,intentFilter);
动态广播不需要再AndroidMainfest里面进行声明,只需要再MainActivity的onCreate()方法里面加上上面几句话就行了。
当不需要使用到这个广播的时候需要再onDestroy()里面把广播取消掉。
@Override
protected void onDestroy() {
super.onDestroy();
unregisterReceiver(myReceiver);
}
扫描二维码关注公众号,回复:
4868073 查看本文章