在android系統中,安裝和卸載都會發送廣播,當應用安裝完成後系統會發android.intent.action.PACKAGE_ADDED廣播。可以通過intent.getDataString()獲得所安裝的包名。當卸載程序時系統發android.intent.action.PACKAGE_REMOVED廣播。同樣intent.getDataString()獲得所卸載的包名。
應用程序無法監聽自己的安裝與卸載,但覆蓋安裝可以監聽到自己的android.intent.action.PACKAGE_REMOVED廣播。
- public class PackageReceiver extends BroadcastReceiver{
- @Override
- public void onReceive(Context context, Intent intent) {
- if (intent.getAction().equals("android.intent.action.PACKAGE_ADDED")) {
- String packageName = intent.getDataString();
- Log.i("Test","---------------" + packageName);
- }
-
- if (intent.getAction().equals("android.intent.action.PACKAGE_REMOVED")) {
- String packageName = intent.getDataString();
- Log.i("Test","---------------" + "PACKAGE_REMOVED" + packageName);
- }
- }
- }
- <?XML version="1.0" encoding="utf-8"?>
- <manifest
- XMLns:android="http://schemas.android.com/apk/res/android"
- package="com.test"
- android:versionCode="1"
- android:versionName="1.0">
- <application
- android:icon="@drawable/icon"
- android:label="測試">
- <receiver android:name=".PackageReceiver"
- android:label="@string/app_name">
- <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="7" />
- <uses-permission android:name="android.permission.INTERNET" />
- <uses-permission android:name="android.permission.RESTART_PACKAGES"/>
- <uses-permission android:name="android.permission.RECEIVE_BOOT_COMPLETED"/>
- </manifest>