可以在代碼文件中聲明一個receiver,也可以在manifest中聲明一個,前者中的receiver只有在該activity launch起來以后才會監聽其所感興趣的事件,
而如果在androidManifext.xml中聲明的話,就不受限制,隨時可以監聽感興趣的事件。
首先談談在androidManifext.xml中注冊一個receiver, 例如我們想監聽相機按鈕按下事件的發生,並且發生后調用我們的camera程序
<receiver android:name="CameraButtonIntentReceiver"> <intent-filter> <action android:name="android.intent.action.CAMERA_BUTTON"/> </intent-filter> </receiver>
另外,當程序需要使用手機相關的服務, 如電話、短信、因特網等功能時,就得在Manifest中添加對於的user-permission。
在這個配置文件中聲明了一個receiver用來監聽相機的按鍵事件,所以還需要在代碼文件定義與配置文件中同名的receiver:
public class CameraButtonIntentReceiver extends BroadcastReceiver { public void onReceive(Context context, Intent intent) { Intent i = new Intent(Intent.ACTION_MAIN); i.setClass(context, Camera.class); i.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK); context.startActivity(i); } }
關於另外一種,在代碼中注冊一個receiver,例如我們想在代碼文件中監聽電池電量的變化,就可以按照如下方法
private final BroadcastReceiver mBatteryReceiver = new BroadcastReceiver() { @Override public void onReceive(Context context, Intent intent) { String action = intent.getAction(); if (action.equals(Intent.ACTION_BATTERY_CHANGED)) { … } } }
這種方法需要在onCreate 或者onStart中注冊該receiver所感興趣的intent,如:
registerReceiver(mBatteryReceiver, Intent.ACTION_BATTERY_CHANGED);
在onStop及onDestroy中注銷監聽
unregisterReceiver(mBatteryReceiver, Intent.ACTION_BATTERY_CHANGED);
系統廣播可以捕捉系統發出的行為有:
1. “android.provider.Telephony.SMS_RECEIVED” 收到短信
2. Intent.ACTION_BATTERY_CHANGED 剩余的手機電池量
3. Intent.ACTION_MEDIA_MOUNTED SD卡成功掛載
4. Intent.ACTION_MEDIA_UNMOUNTED SD卡未掛載
5. Intent.ACTION_NEW_OUTGOING_CALL撥打電話
6. Intent.ACTION_PACKAGE_ADDED執行安裝
7. Intent.ACTION_PACKAGE_REMOVED 執行卸載