自定义广播详解

静态注册:也就是在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);
    }

 

 

 

 

  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值