BroadcastReceiver 是系統全局廣播監聽類, 其主要方法是onReceive(),自定義的廣播類繼承于它并實現自己的onReceive()處理邏輯
BroadcastReceiver 使用前,需要進行注冊監聽(xml和代碼兩種方式),不使用時需要注銷監聽,其生命周期一般為整個應用的生命周期
1, 自定義廣播
自定義廣播MyInstalledReceiver繼承自BroadcastReceiver,實現其onReceive()方式,具體代碼如下:
if (intent.getAction().equals("android.intent.action.PACKAGE_ADDED")) { // install
String packageName = intent.getDataString();
Log.i("homer", "安裝了 :" + packageName);
}
if (intent.getAction().equals("android.intent.action.PACKAGE_REMOVED")) { // uninstall
String packageName = intent.getDataString();
Log.i("homer", "卸載了 :" + packageName);
}
}
}
2, 注冊監聽
1) xml 方式
在AndroidManifest.xml 配置文件的Application節點下,添加自定義的注冊監聽 MyInstalledReceiver
<application
android:icon="@drawable/ic_launcher"
android:label="@string/app_name" >
<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=".MyInstalledReceiver" >
<intent-filter>
<action android:name="android.intent.action.PACKAGE_ADDED" />
<action android:name="android.intent.action.PACKAGE_REMOVED" />
<data android:scheme="package" />
</intent-filter>
</receiver>
</application>
<uses-sdk android:minSdkVersion="3" />
</manifest>
在AndroidManifest.xml 添加的注冊監聽,其生命周期默認是整個應用的生命周期
2) 代碼方式
一般在Activity的onStart()方法中注冊監聽,在onDestroy()方法中注銷監聽(也可以在onStop()方法中注銷,其生命周期注銷時結束)
以上xml和代碼兩種注冊方式,使用時選擇其一即可;
如果同時使用兩種方式,則兩種方式都有效,即一次安裝或卸載均統計了兩次(重復統計)
3, 結果測試
新聞熱點
疑難解答
圖片精選