广播监听手机中应用程序是否安装并卸载
private static final int PACKAGE_NAME_INDEX = 8;
@Override
public void onReceive(Context context, Intent intent) {
if (intent != null) {
/**安装程序的ACTION为Intent.ACTION_PACKAGE_ADDED*/
if (intent.getAction().equals(Intent.ACTION_PACKAGE_ADDED)) {
String data = intent.getDataString();
if (data == null || data.length() <= PACKAGE_NAME_INDEX) { return; }
String packageName = data.substring(PACKAGE_NAME_INDEX);
if (isAvilible(context, packageName)) {
/**说明安装了应用包*/
Uri uri = Uri.fromParts("package", packageName, null);
/**监听应用卸载的ACTION*/
intent = new Intent(Intent.ACTION_DELETE, uri);
intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
context.startActivity(intent);
}
else {
Toast.makeText(context, "手机并没有安装该应用!", Toast.LENGTH_SHORT).show();
}
}
}
}
/**检测是否安装了微信的客户端*/
public static boolean isAvilible(Context context, String packageName) {
/**包管理器PackageManager*/
final PackageManager packageManager = context.getPackageManager();
/**所有已安装程序的包信息*/
List<PackageInfo> pinfo = packageManager.getInstalledPackages(0);
/**存储所有已安装程序的包名*/
List<String> pName = new ArrayList<String>();
if (pinfo != null) {
for (int i = 0; i < pinfo.size(); i++) {
String pn = pinfo.get(i).packageName;
pName.add(pn);
}
}
return pName.contains(packageName);
}
}
-----------AndroidManifest.xml中注册广播---------------------------
<receiver android:name=".PackageReceiver">
<intent-filter>
<action android:name="android.intent.action.PACKAGE_ADDED" />
<data android:scheme="package" />
</intent-filter>
</receiver>
郑重声明:本站内容如果来自互联网及其他传播媒体,其版权均属原媒体及文章作者所有。转载目的在于传递更多信息及用于网络分享,并不代表本站赞同其观点和对其真实性负责,也不构成任何其他建议。