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>