- 實作事件接收 public class MyEventsReceiver extends BroadcastReceiver
- 設定 AndroidManifest.xml 監聽的事件,部分事件是需要額外權限的,安裝軟體時會顯示給使用者
BroadcastReceiver:
package org.changyy.study;
public class MyEventsReceiver extends BroadcastReceiver {
Intent MyService;
@Override
public void onReceive(Context context, Intent intent) {
// TODO Auto-generated method stub
String action = intent.getAction();
if( action.compareTo("android.intent.action.BOOT_COMPLETED") == 0 ) {
MyService = new Intent(context, MyService.class);
context.startService(MyService);
}
}
}
AndroidManifest.xml:
<uses-permission android:name="android.permission.RECEIVE_BOOT_COMPLETED"/>
<application
android:icon="@drawable/ic_launcher"
android:label="@string/app_name"
android:theme="@style/AppTheme" >
<service
android:name="org.changyy.study.MyService"
android:process=":MyService">
</service>
<receiver android:name="org.changyy.study.MyEventsReceiver">
<intent-filter>
<action android:name="android.intent.action.BOOT_COMPLETED"></action>
<action android:name="android.intent.action.MEDIA_MOUNTED"/>
<action android:name="android.intent.action.MEDIA_UNMOUNTED"/>
<action android:name="android.intent.action.MEDIA_BAD_REMOVAL"/>
</intent-filter>
</receiver>
</application>
此例除了開機事件(android.intent.action.BOOT_COMPLETED)外,順便監聽了外部儲存媒體的插拔。簡單的說,如果要監聽一排的事件,就只要在 AndroidManifest.xml 填寫完後,在 MyEventsReceiver 裡的 onReceive 判斷,若每個事件都要做一樣的事則不用判斷去執行指定項目即可,若需要判斷可透過 intent.getAction() 處理。
沒有留言:
張貼留言