关于静态广播和动态广播

1.J简单的看静态广播和动态广播的不同就是注册的场所的不同。

静态广播在清单文件里注册;动态广播在java文件中注册。废话少说看代码:

在mainActivity中:

实现一个广播类

//实现广播接收发送过来的信息
public class myReceiveBC extends BroadcastReceiver{

    @Override
    public void onReceive(Context context, Intent intent) {
       Log.d("=====",intent.getStringExtra("msg"));
    }
}

2.在mainActivity的onCreat()方法中注册广播(动态广播)

//注册广播
myReceiveBC receive=new myReceiveBC();
IntentFilter filter=new IntentFilter();
//添加频段时候可以设置多个,和面的发送频段只要有一个相同就可以。
filter.addAction("con.broadcoast.goinfo");
registerReceiver(receive,filter);

//注册完毕后,启动服务

Intent intent=new Intent(MainActivity.this, MyService.class);
startService(intent);//
//在服务中走onstartCommand方法,intent参数即是传送过来的参数值。
//    @Override
//    public int onStartCommand(Intent intent, int flags, int startId) {
//        return super.onStartCommand(intent, flags, startId);
//    }

3在一个服务

 MyService中

的onCreate()方法中发送广播。

Intent it=new Intent();
//注意频段相同
it.setAction("con.broadcoast.goinfo");
it.putExtra("msg","1");
sendBroadcast(it);
 
4.静态广播注册:
<receiver
    android:name=".broadcast.MyReceiver"
    android:enabled="true"
    android:exported="true">
    <intent-filter>
        <action android:name="android.intent.action.BOOT_COMPLETED" />
<!--频段设置(随便设必须和在注册时的频段相同)-->  
      />
    </intent-filter>
</receiver>

 

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值