import android.content.BroadcastReceiver; import android.content.Context; import android.content.Intent; import android.content.pm.PackageManager; import android.text.TextUtils; import android.widget.Toast; import com.stone.mobilesafe.util.LogUtils; public class AppReceiver extends BroadcastReceiver { private final String TAG = this.getClass().getSimpleName(); @Override public void onReceive(Context context, Intent intent) { PackageManager pm = context.getPackageManager(); if (TextUtils.equals(intent.getAction(), Intent.ACTION_PACKAGE_ADDED)) { String packageName = intent.getData().getSchemeSpecificPart(); LogUtils.printInfo(TAG, "--------安装成功" + packageName); Toast.makeText(context, "安装成功" + packageName, Toast.LENGTH_LONG).show(); } else if (TextUtils.equals(intent.getAction(), Intent.ACTION_PACKAGE_REPLACED)) { String packageName = intent.getData().getSchemeSpecificPart(); LogUtils.printInfo(TAG, "--------替换成功" + packageName); Toast.makeText(context, "替换成功" + packageName, Toast.LENGTH_LONG).show(); } else if (TextUtils.equals(intent.getAction(), Intent.ACTION_PACKAGE_REMOVED)) { String packageName = intent.getData().getSchemeSpecificPart(); LogUtils.printInfo(TAG, "--------卸载成功" + packageName); Toast.makeText(context, "卸载成功" + packageName, Toast.LENGTH_LONG).show(); } } }
manifest.xml中的配置
<receiver android:name=".receiver.AppReceiver" > <intent-filter> <!-- 一个新应用包已经安装在设备上,数据包括包名(监听所在的app,新安装时,不能接收到这个广播) --> <action android:name="android.intent.action.PACKAGE_ADDED" /> <!-- 一个新版本的应用安装到设备,替换之前已经存在的版本 替换时会先收到卸载的再收到替换的, 替换自身也能收到--> <action android:name="android.intent.action.PACKAGE_REPLACED" /> <!-- 一个已存在的应用程序包已经从设备上移除,包括包名(卸载监听所在的app,则无法接收到) --> <action android:name="android.intent.action.PACKAGE_REMOVED" /> <data android:scheme="package" /> </intent-filter> </receiver>
原创文章,作者:ItWorker,如若转载,请注明出处:https://blog.ytso.com/tech/pnotes/10708.html