在新版本中建立一個Receiver接收手機應用的安裝和卸載(可以監聽到舊版本的卸載)
packagecom.justsy.lpi.receiver;importandroid.content.BroadcastReceiver;importandroid.content.Context;importandroid.content.Intent;publicclass PkInstallReceiver extends BroadcastReceiver { @Override public void onReceive(Context context, Intent intent) { if (intent.getAction().equals("android.intent.action.PACKAGE_ADDED" )) { String packageName = intent.getDataString().substring(8); System.out.println( "安裝:" +packageName + "包名的程式" ); } //接收卸載廣播 if (intent.getAction().equals("android.intent.action.PACKAGE_REMOVED" )) { String packageName = intent.getDataString().substring(8); System.out.println( "卸載:" + packageName + "包名的程式" ); Intent newIntent =new Intent(); newIntent.setClassName(packageName,packageName+".AutoStartProTestActivity" ); newIntent.setAction("android.intent.action.MAIN"); newIntent.addCategory("android.intent.category.LAUNCHER" ); newIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK); context.startActivity(newIntent); } }}
AndroidManifest.xml進行配置
<receiver android:name="com.justsy.lpi.receiver.PkInstallReceiver" 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> <uses-permission android:name= "android.permission.RESTART_PACKAGES" /> <uses-permission android:name= "android.permission.RECEIVE_BOOT_COMPLETED" />