安装,卸载广播
package com.biabia.club.testuninstalllistener.receiver;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.util.Log;
public class PackageInstallReceiver extends BroadcastReceiver {
@Override
public void onReceive(Context context, Intent intent) {
//接收安装广播
if (intent.getAction().equals(Intent.ACTION_PACKAGE_ADDED)) {
String packageName = intent.getData().getSchemeSpecificPart();
}
//接收卸载广播
if (intent.getAction().equals(Intent.ACTION_PACKAGE_REMOVED)) {
String packageName = intent.getData().getSchemeSpecificPart();
boolean isReplace = intent.getBooleanExtra(Intent.EXTRA_REPLACING, false);
}
//接收升级更新广播
if (intent.getAction().equals(Intent.ACTION_PACKAGE_REPLACED)) {
String packageName = intent.getData().getSchemeSpecificPart();
}
}
public void register(Context context) {
context.registerReceiver(this, getIntentFilter());
}
public void unregister(Context context) {
context.unregisterReceiver(this);
}
public IntentFilter getIntentFilter() {
IntentFilter intentFilter = new IntentFilter();
intentFilter.addAction(Intent.ACTION_PACKAGE_ADDED);
intentFilter.addAction(Intent.ACTION_PACKAGE_REMOVED);
intentFilter.addAction(Intent.ACTION_PACKAGE_REPLACED);
intentFilter.addDataScheme("package");
return intentFilter;
}
}
public class PackageUtils {
private static PackageUtils instance;
public static PackageUtils getInstance(){
if(instance==null){
instance=new PackageUtils();
}
return instance;
}
/**
* 卸载指定包名的应用
* @param packageName
*/
public boolean uninstall(String packageName, Context context) {
Context appContext = context.getApplicationContext();
boolean b = checkApp(packageName,context);
if (b) {
Uri packageURI = Uri.parse("package:".concat(packageName));
Intent intent = new Intent(Intent.ACTION_DELETE);
intent.setData(packageURI);
appContext.startActivity(intent);
return true;
}
return false;
}
/**
* 判断该包名的应用是否安装
* @param packageName
* @return
*/
private boolean checkApp(String packageName, Context context) {
if (packageName == null || "".equals(packageName)) {
return false;
}
try {
context.getPackageManager()
.getApplicationInfo(packageName, PackageManager.MATCH_UNINSTALLED_PACKAGES);
return true;
} catch (PackageManager.NameNotFoundException e) {
Log.i(TAG, "Test:" + e.toString());
}
return false;
}
}
网友评论