Android读取第三方应用列表并卸载

Android读取第三方应用列表并卸载_第1张图片

工具类功能如标题所示,实现效果如上图,具体实现见代码。

/**
 * 安装一个apk文件
 */
public static void install(Context context, File uriFile) {
    Intent intent = new Intent(Intent.ACTION_VIEW);
    intent.setDataAndType(Uri.fromFile(uriFile), "application/vnd.android.package-archive");
    intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
    context.startActivity(intent);
}
/**
 * 卸载一个app
 */
public static void uninstall(Context context, String packageName) {
    //通过程序的包名创建URI
    Uri packageURI = Uri.parse("package:" + packageName);
    //创建Intent意图
    Intent intent = new Intent(Intent.ACTION_DELETE, packageURI);
    //执行卸载程序
    context.startActivity(intent);
}

/**
 * 获取已安装非系统应用
 *
 * @return
 */
public static List scanInstallApp(Context mContext) {
    List appInfos = new ArrayList<>();
    PackageManager pm = mContext.getPackageManager(); // 获得PackageManager对象
    List listAppcations = pm
            .getInstalledApplications(PackageManager.GET_UNINSTALLED_PACKAGES);
    Collections.sort(listAppcations,
            new ApplicationInfo.DisplayNameComparator(pm));// 字典排序
    for (ApplicationInfo app : listAppcations) {
        if ((app.flags & ApplicationInfo.FLAG_SYSTEM) <= 0) {//非系统程序
            appInfos.add(getAppInfo(app, pm));
        }//本来是系统程序,被用户手动更新后,该系统程序也成为第三方应用程序了
        else if ((app.flags & ApplicationInfo.FLAG_UPDATED_SYSTEM_APP) != 0) {
            appInfos.add(getAppInfo(app, pm));
        }
    }
    return appInfos;
}

/**
 *  构造一个AppInfo对象 ,并赋值
 */
private static AppInfo getAppInfo(ApplicationInfo app, PackageManager pm) {
    AppInfo appInfo = new AppInfo();
    appInfo.setAppName(pm.getApplicationLabel(app).toString());//应用名称
    appInfo.setAppIcon(app.loadIcon(pm));//应用icon
    appInfo.setPkgName(app.packageName);//应用包名,用来卸载
    File file = new File(app.sourceDir);
    float size = file.length();
    DecimalFormat df = new DecimalFormat("#.00");
    appInfo.setAppSize(df.format(size / (1024 * 1024)) + "M");//应用大小,M单位,保留两位小数
    PackageInfo packageInfo = null;
    try {
        packageInfo = pm.getPackageInfo(app.packageName, 0);
        long lastUpdateTime = packageInfo.lastUpdateTime;//应用最近一次更新时间
        appInfo.setUpdateDate(TimeUtil.time2Ago(lastUpdateTime));//将毫秒时间对比当前时间转换为多久以前
    } catch (PackageManager.NameNotFoundException e) {
        e.printStackTrace();
    }
    return appInfo;
}

你可能感兴趣的:(Android编程)