Android中BroadcastReceiver使用分為動態註冊BroastcastReceiver ,靜態註冊BroastcastReceiver
1、動態註冊BroastcastReceiver。
定義BroadcastReceiver:
private BroadcastReceiver bcr1 = new BroadcastReceiver() { @Overridepublic void onReceive(Context context, Intent intent) {// TODO Auto-generated method stub String action = intent.getAction(); Toast.makeText(context, "動態:"+action, 1000).show(); } };
註冊registerReceiver(bcr1, new IntentFilter(ACTION_1));代碼如下。關鍵代碼是註冊代碼registerReceiver(bcr1, new IntentFilter(ACTION_1)),其他是一些簡單的按鈕, 及綁定的Click事件。
Button btn1,btn2,btn3; static final String ACTION_1 = "com.example.broadcastreceiverdemo.ACTION_1"; static final String ACTION_2 = "com.example.broadcastreceiverdemo.ACTION_2"; static final String ACTION_3 = "com.example.broadcastreceiverdemo.ACTION_3"; @Overrideprotected void onCreate(Bundle savedInstanceState) {super.onCreate(savedInstanceState);setContentView(R.layout.activity_main);btn1 = (Button)this.findViewById(R.id.button1);btn1.setOnClickListener(new ClickEvent());btn2 = (Button)this.findViewById(R.id.button2);btn2.setOnClickListener(new ClickEvent());btn3 = (Button)this.findViewById(R.id.button3);btn3.setOnClickListener(new ClickEvent());registerReceiver(bcr1, new IntentFilter(ACTION_1));}
發送廣播
class ClickEvent implements OnClickListener { @Override public void onClick(View v) { // TODO Auto-generated method stub if(v == btn1) { Intent intent = new Intent(ACTION_1); sendBroadcast(intent); } if(v == btn2) { Intent intent = new Intent(ACTION_2); sendBroadcast(intent); } if(v == btn3) { IntentFilter filter = new IntentFilter(); filter.addAction(Intent.ACTION_BATTERY_LOW); filter.addAction(ACTION_3); registerReceiver(bcr2, new IntentFilter(ACTION_3)); Intent intent = new Intent(ACTION_3); intent.putExtra("Conuntry", "China"); intent.putExtra("City", "ShangHai"); sendBroadcast(intent); } }
其中 v == btn1為發送至內部動態註冊的BroadcastReceiver;
v == btn2為發送至內部靜態註冊的BroadcastReceiver;
v == btn3為發送至系統級內部動態註冊BroadcastReceiver(bt1和bt3基本一樣,只是稍微加了addAction以及Intent的putExtra);
2 靜態註冊BroastcastReceiver。靜態註冊更要煩些,要在Androidmanifest.xml中註冊。
<application android:allowBackup="true" android:icon="@drawable/ic_launcher" android:label="@string/app_name" android:theme="@style/AppTheme" > <receiver android:name="cls2"> <intent-filter> <action android:name="com.example.broadcastreceiverdemo.ACTION_2"></action> </intent-filter> </receiver> <activity android:name="com.example.broadcastreceiverdemo.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> </application>
並且要實現一個類繼承BroadcastReceiver
public class cls2 extends BroadcastReceiver{@Overridepublic void onReceive(Context context, Intent intent) {// TODO Auto-generated method stubString action = intent.getAction(); Toast.makeText(context, "靜態:"+action, 1000).show(); }}