在android系统中,软件的安装和卸载都会发送广播,通过注册广播接收系统发送的广播就能对软件的安装和卸载进行监听
一 . 新建一个类继承BroadcastReceiver,复写onReceiver()
1 .继承BroadcastReceiver
public class BootReceiver extends BroadcastReceiver
2 .复写onReceiver()
@Override public void onReceive(Context context, Intent intent) { if(intent.getAction().equals("android.intent.action.PACKAGE_ADDED")){ String installPackageName = intent.getDataString().trim(); L.d("安装了应用",installPackageName); }else if(intent.getAction().equals("android.intent.action.PACKAGE_REMOVE")){ String uninstallPackageName = intent.getDataString().trim(); L.d("安装了应用",uninstallPackageName); } }
二 注册监听
在AndroidManifest.xml 配置文件的Application节点下注册,我一般选择在代码中注册,在
public IntentFilter getIntentFilter() { IntentFilter filter = new IntentFilter(); filter.addAction(Intent.ACTION_PACKAGE_REMOVED); filter.addAction(Intent.ACTION_PACKAGE_ADDED); filter.addDataScheme("package"); return filter; }
三 使用
一般在Activity的onStart()方法中注册监听,在onDestroy()方法中注销监听
// 注册应用广播 mReceiver = new BootReceiver(); IntentFilter filter = mReceiver.getIntentFilter(); mContext.registerReceiver(mReceiver,filter);
@Override public void onDestroy() { super.onDestroy(); // 注销广播 mContext.unregisterReceiver(mReceiver); }
逃逃
逃逃
逃逃