标签:
(1)BroadcastReceiver的两种注册方式
当我们创建了一个继承于BroadcastReceiver的广播接收者类以后,要在程序中去注册,注册的第一种方式是xml方式,在Mainfest注册文件中去注册,注册的xml代码如下
<application android:allowBackup="true" android:icon="@drawable/ic_launcher" android:label="@string/app_name" android:theme="@style/AppTheme" > <activity android:name=".MainActivity" android:label="@string/app_name" > <intent-filter> <action android:name="android.intent.action.MAIN" /> <category android:name="android.intent.category.LAUNCHER" /> </intent-filter> </activity> <receiver android:name="MyReceiver"> <intent-filter> <action android:name="dengchaoqun.Reciever"/> </intent-filter> </receiver> </application>
然后再程序中发送广播
Intent intent=new Intent("dengchaoqun.Reciever");
sendBroadcast(intent);
(2)通过java代码动态注册
private Button btnStart; private Button btnStop; private BroadcastReceiver receiver; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); //动态方式注册BordCastrecever receiver=new MyReceiver(); IntentFilter filter=new IntentFilter("Myreceiver"); registerReceiver(receiver, filter); btnStart=(Button) findViewById(R.id.button1); btnStop=(Button)findViewById(R.id.button2); btnStart.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { //静态方式 /*Intent intent=new Intent("dengchaoqun.Reciever"); sendBroadcast(intent);*/ Intent intent=new Intent("Myreceiver"); sendBroadcast(intent); } }); btnStop.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { unregisterReceiver(receiver); } }); }
(3)接收者对象的销毁 unregisterReciever(receiver);
(4)在接收者对象中的
@Override
public void onReceive(Context context, Intent intent) {
Toast.makeText(context, "测试", 2000).show();
}
onReceiver中不能进行耗时操作,如果有耗时操作,必须开线程,或者通过intent启动services来完成
标签:
原文地址:http://www.cnblogs.com/deng-c-q/p/5198704.html