version:1.1

fix:
add:应用使用数据统计
This commit is contained in:
2021-12-25 16:54:44 +08:00
parent 88f65afb48
commit 71e5516ab8
159 changed files with 1671 additions and 3312 deletions

View File

@@ -0,0 +1,890 @@
package com.uiui.sn.utils;
import android.annotation.SuppressLint;
import android.app.Activity;
import android.app.ActivityManager;
import android.app.PendingIntent;
import android.app.usage.UsageStats;
import android.app.usage.UsageStatsManager;
import android.content.Context;
import android.content.Intent;
import android.content.pm.ApplicationInfo;
import android.content.pm.PackageInfo;
import android.content.pm.PackageInstaller;
import android.content.pm.PackageManager;
import android.content.pm.ResolveInfo;
import android.net.Uri;
import android.os.Binder;
import android.os.Build;
import android.provider.Settings;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import androidx.annotation.RequiresApi;
import androidx.core.content.FileProvider;
import com.uiui.sn.BuildConfig;
import com.uiui.sn.R;
import com.uiui.sn.receiver.InstallResultReceiver;
import java.io.BufferedReader;
import java.io.DataOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Enumeration;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.SortedMap;
import java.util.TreeMap;
import java.util.function.Predicate;
import java.util.zip.ZipEntry;
import java.util.zip.ZipFile;
public class ApkUtils {
private static String TAG = ApkUtils.class.getSimpleName();
/**
* 获取第三方应用
* @param context
* @return
*/
public static List<String> queryFilterAppList(Context context) {
PackageManager pm = context.getPackageManager();
// 查询所有已经安装的应用程序
List<ApplicationInfo> appInfos = pm.getInstalledApplications(PackageManager.GET_UNINSTALLED_PACKAGES);// GET_UNINSTALLED_PACKAGES代表已删除但还有安装目录的
List<String> applicationInfos = new ArrayList<>();
for (ApplicationInfo app : appInfos) {
// Log.e("queryFilterAppInfo", String.valueOf(app.flags));
// Log.e("queryFilterAppInfo", String.valueOf((app.flags & mask)));
if ((app.flags & ApplicationInfo.FLAG_SYSTEM) == 1) {
//通过flag排除系统应用会将电话、短信也排除掉
} else {
applicationInfos.add(app.packageName);
Log.e("queryFilterAppInfo", app.packageName);
}
}
return applicationInfos;
}
public static synchronized boolean getRootAhth() {
Process process = null;
DataOutputStream os = null;
try {
process = Runtime.getRuntime().exec("su");
os = new DataOutputStream(process.getOutputStream());
os.writeBytes("exit\n");
os.flush();
int exitValue = process.waitFor();
if (exitValue == 0) {
return true;
} else {
return false;
}
} catch (Exception e) {
Log.e("*** DEBUG ***", "Unexpected error - Here is what I know: "
+ e.getMessage());
return false;
} finally {
try {
if (os != null) {
os.close();
}
process.destroy();
} catch (Exception e) {
e.printStackTrace();
}
}
}
public static void openApp(Context context, View view) {
try {
Intent intent = context.getPackageManager().getLaunchIntentForPackage((String) view.getTag(R.string.download_btn_had));
context.startActivity(intent);
} catch (Exception e) {
ToastUtil.show(String.valueOf(R.string.open_app_fail));
}
return;
}
public static void openApp(Context context, String packageName) {
Intent intent = context.getPackageManager().getLaunchIntentForPackage(packageName);
if (intent != null) {
// intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
context.startActivity(intent);
}
}
/**
* 安装一个apk文件
*/
public static void install(Context context, File uriFile) {
Intent intent = new Intent(Intent.ACTION_VIEW);
// 由于没有在Activity环境下启动Activity,设置下面的标签
intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
if (Build.VERSION.SDK_INT >= 24) { //判读版本是否在7.0以上
//参数1 上下文, 参数2 Provider主机地址 和配置文件中保持一致 参数3 共享的文件
Uri apkUri =
FileProvider.getUriForFile(context, "com.uiui.sn.fileprovider", uriFile);
//添加这一句表示对目标应用临时授权该Uri所代表的文件
intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
intent.setDataAndType(apkUri, "application/vnd.android.package-archive");
} else {
intent.setDataAndType(Uri.fromFile(uriFile),
"application/vnd.android.package-archive");
}
context.startActivity(intent);
}
/**
* 根据包名卸载应用
*
* @param packageName 包名
*/
@RequiresApi(api = Build.VERSION_CODES.LOLLIPOP)
public static void uninstall(Context context, String packageName) {
Intent broadcastIntent = new Intent(context, InstallResultReceiver.class);
PendingIntent pendingIntent = PendingIntent.getBroadcast(context, 1,
broadcastIntent, PendingIntent.FLAG_UPDATE_CURRENT);
PackageInstaller packageInstaller = context.getPackageManager().getPackageInstaller();
packageInstaller.uninstall(packageName, pendingIntent.getIntentSender());
}
/**
* 检查手机上是否安装了指定的软件
*/
public static boolean isAvailable(Context context, String packageName) {
// 获取packagemanager
final PackageManager packageManager = context.getPackageManager();
// 获取所有已安装程序的包信息
List<PackageInfo> packageInfos = packageManager.getInstalledPackages(0);
// 用于存储所有已安装程序的包名
List<String> packageNames = new ArrayList<>();
// 从pinfo中将包名字逐一取出压入pName list中
if (packageInfos != null) {
for (int i = 0; i < packageInfos.size(); i++) {
String packName = packageInfos.get(i).packageName;
packageNames.add(packName);
}
}
// 判断packageNames中是否有目标程序的包名有TRUE没有FALSE
return packageNames.contains(packageName);
}
/**
* 检查手机上是否安装了指定的软件
*/
public static boolean isAvailable(Context context, File file) {
return isAvailable(context, getPackageName(context, file.getAbsolutePath()));
}
/**
* 根据文件路径获取包名
*/
public static String getPackageName(Context context, String filePath) {
PackageManager packageManager = context.getPackageManager();
PackageInfo info = packageManager.getPackageArchiveInfo(filePath, PackageManager.GET_ACTIVITIES);
if (info != null) {
ApplicationInfo appInfo = info.applicationInfo;
return appInfo.packageName; //得到安装包名称
}
return null;
}
/**
* 从apk中获取版本信息
*/
public static String getChannelFromApk(Context context, String channelPrefix) {
//从apk包中获取
ApplicationInfo appinfo = context.getApplicationInfo();
String sourceDir = appinfo.sourceDir;
//默认放在meta-inf/里, 所以需要再拼接一下
String key = "META-INF/" + channelPrefix;
String ret = "";
ZipFile zipfile = null;
try {
zipfile = new ZipFile(sourceDir);
Enumeration<?> entries = zipfile.entries();
while (entries.hasMoreElements()) {
ZipEntry entry = ((ZipEntry) entries.nextElement());
String entryName = entry.getName();
if (entryName.startsWith(key)) {
ret = entryName;
break;
}
}
} catch (IOException e) {
e.printStackTrace();
} finally {
if (zipfile != null) {
try {
zipfile.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
String[] split = ret.split(channelPrefix);
String channel = "";
if (split.length >= 2) {
channel = ret.substring(key.length());
}
return channel;
}
// public static void installRx(final Context context, final String packageName, final String filePath) {
//
// Observable.create(new Observable.OnSubscribe<Integer>() {
// @Override
// public void call(Subscriber<? super Integer> subscriber) {
// File file = new File(filePath);
// if (filePath == null || filePath.length() == 0 || file == null) {
// Log.e("fanhuitong", "errormesg=========" + " 空啊 ");
// subscriber.onNext(0);
// return;
// }
// // String[] args = { "pm", "install", "-r", filePath };
// String[] args = {"pm", "install", "-i", "com.colorflykids", "--user", "0", filePath};
// // String argss = "pm install -i " + "com.colorflykids" + " --user 0 " + filePath;
// Log.e("fanhuitong", "argss====" + args);
// ProcessBuilder processBuilder = new ProcessBuilder(args);
// Process process = null;
// BufferedReader successResult = null;
// BufferedReader errorResult = null;
// StringBuilder successMsg = new StringBuilder();
// StringBuilder errorMsg = new StringBuilder();
// try {
// process = processBuilder.start();
// successResult = new BufferedReader(new InputStreamReader(process.getInputStream()));
// errorResult = new BufferedReader(new InputStreamReader(process.getErrorStream()));
// String s;
// while ((s = successResult.readLine()) != null) {
// Log.e("mjhseng", "successResult----------" + s);
// successMsg.append(s);
// }
// while ((s = errorResult.readLine()) != null) {
// Log.e("mjhseng", "errorResult----------" + s);
// errorMsg.append(s);
// }
// } catch (IOException e1) {
// Log.e("fanhuitong", "IOException e1)----------" + e1.toString());
// e1.printStackTrace();
// } finally {
// try {
// if (successResult != null) {
// successResult.close();
// }
// if (errorResult != null) {
// errorResult.close();
// }
// } catch (IOException e1) {
// Log.e("fanhuitong", "IOException e11)---------" + e1.toString());
// e1.printStackTrace();
// }
// if (process != null) {
// process.destroy();
// }
// }
// if (successMsg.toString().contains("Success") || successMsg.toString().contains("success")) {
// subscriber.onNext(2);
// } else {
// Log.e("fanhuitong", "errormesg=========" + errorMsg.toString());
// subscriber.onNext(1);
// }
// }
// }).subscribeOn(Schedulers.newThread())
// .observeOn(AndroidSchedulers.mainThread())
// .subscribe(new Observer<Integer>() {
//
// @Override
// public void onNext(Integer value) {
// if (value == 2) {
// //安装成功
// ToastUtil.show("安装成功");
// Log.e("fanhuitong", "-----------安装成功-----------");
// } else {
// //安装错误
// Log.e("fanhuitong", "------------安装错误-----------");
// ToastUtil.show("安装失败");
// }
// }
//
// @Override
// public void onCompleted() {
//
// }
//
// @Override
// public void onError(Throwable e) {
// //安装错误
// }
// });
// }
// public static void installApp(final String path, final String packageNames){
// File apkFile = new File(path);
// try {
// Class<?> clazz = Class.forName("android.os.ServiceManager");
// Method method_getService = clazz.getMethod("getService", String.class);
// IBinder bind = (IBinder) method_getService.invoke(null, "package");
// IPackageManager iPm = IPackageManager.Stub.asInterface(bind);
// iPm.installPackage(Uri.fromFile(apkFile),null, 2, apkFile.getName());
// Log.e("fanhuitong", "安装成功");
// } catch (Exception e) {
// e.printStackTrace();
// Log.e("fanhuitong", "安装失败");
// }
// }
//使用系统签名
public static void installApkInSilence(String installPath, String packageName) {
ToastUtil.show("正在安装应用...");
Class<?> pmService;
Class<?> activityTherad;
Method method;
try {
activityTherad = Class.forName("android.app.ActivityThread");
Class<?> paramTypes[] = getParamTypes(activityTherad, "getPackageManager");
method = activityTherad.getMethod("getPackageManager", paramTypes);
Object PackageManagerService = method.invoke(activityTherad);
pmService = PackageManagerService.getClass();
Class<?> paramTypes1[] = getParamTypes(pmService, "installPackageAsUser");
method = pmService.getMethod("installPackageAsUser", paramTypes1);
method.invoke(PackageManagerService, installPath, null, 0x00000040, packageName, getUserId(Binder.getCallingUid()));//getUserId
} catch (ClassNotFoundException e) {
e.printStackTrace();
} catch (NoSuchMethodException e) {
e.printStackTrace();
} catch (IllegalAccessException e) {
e.printStackTrace();
} catch (InvocationTargetException e) {
e.printStackTrace();
}
}
/**
* 通过路径安装APK兼容Android 9以上
*
* @param context 上下文
* @param filePath apk文件路径
*/
public static void installApp(Context context, String filePath) {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.P) {
installAppatPie(context, filePath);
} else {
installApps(filePath);
}
}
public static boolean installApps(String apkPath) {
ToastUtil.show("正在安装应用");
Process process = null;
BufferedReader successResult = null;
BufferedReader errorResult = null;
StringBuilder successMsg = new StringBuilder();
StringBuilder errorMsg = new StringBuilder();
try {
process = new ProcessBuilder("pm", "install", "-i", BuildConfig.APPLICATION_ID, "--user", "0", apkPath).start();
successResult = new BufferedReader(new InputStreamReader(process.getInputStream()));
errorResult = new BufferedReader(new InputStreamReader(process.getErrorStream()));
String s;
while ((s = successResult.readLine()) != null) {
successMsg.append(s);
}
while ((s = errorResult.readLine()) != null) {
errorMsg.append(s);
}
} catch (Exception e) {
Log.e("installApps1", e.getMessage());
} finally {
try {
if (successResult != null) {
successResult.close();
}
if (errorResult != null) {
errorResult.close();
}
} catch (Exception e) {
Log.e("installApps2", e.getMessage());
}
if (process != null) {
process.destroy();
}
}
Log.e("result", "" + errorMsg.toString());
//如果含有“success”认为安装成功
Log.e("installApp", successMsg.toString());
// if (!successMsg.toString().equalsIgnoreCase("success")) {
// install(context, new File(apkPath));
// }
return successMsg.toString().equalsIgnoreCase("success");
}
@RequiresApi(api = Build.VERSION_CODES.LOLLIPOP)
public static void installAppatPie(Context context, String apkFilePath) {
File file = new File(apkFilePath);
PackageInstaller packageInstaller = context.getPackageManager().getPackageInstaller();
PackageInstaller.SessionParams sessionParams = new PackageInstaller.SessionParams(PackageInstaller
.SessionParams.MODE_FULL_INSTALL);
sessionParams.setSize(file.length());
int sessionId = createSession(packageInstaller, sessionParams);
if (sessionId != -1) {
boolean copySuccess = copyApkFile(packageInstaller, sessionId, apkFilePath);
if (copySuccess) {
install(packageInstaller, sessionId, context);
}
}
}
@RequiresApi(api = Build.VERSION_CODES.LOLLIPOP)
private static boolean copyApkFile(PackageInstaller pi, int sessionId, String apkFilePath) {
boolean success = false;
File apkFile = new File(apkFilePath);
PackageInstaller.Session session = null;
try {
session = pi.openSession(sessionId);
OutputStream out = session.openWrite("app.apk", 0, apkFile.length());
FileInputStream input = new FileInputStream(apkFile);
int read = 0;
byte[] buffer = new byte[65536];
// while (read != -1) {
// read = input.read(buffer);
// out.write(buffer, 0, read);
// }
while (true) {
read = input.read(buffer);
if (read == -1) {
session.fsync(out);
success = true;
out.close();
input.close();
break;
}
out.write(buffer, 0, read);
}
} catch (IOException e) {
e.printStackTrace();
Log.e("fht", "copyApkFile" + e.getMessage());
}
return success;
}
@RequiresApi(api = Build.VERSION_CODES.LOLLIPOP)
private static void install(PackageInstaller packageInstaller, int sessionId, Context context) {
try {
PackageInstaller.Session session = packageInstaller.openSession(sessionId);
Intent intent = new Intent(context, InstallResultReceiver.class);
PendingIntent pendingIntent = PendingIntent.getBroadcast(
context,
1, intent,
PendingIntent.FLAG_UPDATE_CURRENT
);
session.commit(pendingIntent.getIntentSender());
} catch (IOException e) {
e.printStackTrace();
}
}
@RequiresApi(api = Build.VERSION_CODES.LOLLIPOP)
private static int createSession(PackageInstaller packageInstaller, PackageInstaller.SessionParams sessionParams) {
int sessionId = -1;
try {
sessionId = packageInstaller.createSession(sessionParams);
} catch (IOException e) {
e.printStackTrace();
}
return sessionId;
}
public static void uninstallApp(Context context, String packageName) {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
uninstall(context, packageName);
} else {
deleteApkInSilence(packageName);
}
}
public static void deleteApkInSilence(String packageName) {
Class<?> pmService;
Class<?> activityTherad;
Method method;
try {
activityTherad = Class.forName("android.app.ActivityThread");
Class<?> paramTypes[] = getParamTypes(activityTherad, "getPackageManager");
method = activityTherad.getMethod("getPackageManager", paramTypes);
Object PackageManagerService = method.invoke(activityTherad);
pmService = PackageManagerService.getClass();
Class<?> paramTypes1[] = getParamTypes(pmService, "deletePackageAsUser");
method = pmService.getMethod("deletePackageAsUser", paramTypes1);
//getUserId
method.invoke(PackageManagerService, packageName, null, getUserId(Binder.getCallingUid()), 0x00000040);
} catch (ClassNotFoundException e) {
e.printStackTrace();
} catch (NoSuchMethodException e) {
e.printStackTrace();
} catch (IllegalAccessException e) {
e.printStackTrace();
} catch (InvocationTargetException e) {
e.printStackTrace();
}
}
private static Class<?>[] getParamTypes(Class<?> cls, String mName) {
Class<?> cs[] = null;
Method[] mtd = cls.getMethods();
for (int i = 0; i < mtd.length; i++) {
if (!mtd[i].getName().equals(mName)) {
continue;
}
cs = mtd[i].getParameterTypes();
}
return cs;
}
public static final int PER_USER_RANGE = 100000;
public static int getUserId(int uid) {
return uid / PER_USER_RANGE;
}
public static boolean checkIsUpdate(Context context, String packageName, int versionCode) {
PackageManager packageManager = context.getPackageManager();
boolean update = false;
PackageInfo packageInfo = null;
try {
packageInfo = packageManager.getPackageInfo(packageName, PackageManager.GET_ACTIVITIES);
int code = packageInfo.versionCode;
update = versionCode > code;
} catch (PackageManager.NameNotFoundException e) {
e.printStackTrace();
// Log.e("NameNotFoundException", e.getMessage());
update = false;
}
return update;
}
synchronized public static PackageInfo getPackageInfo(Context context, String packageName) {
PackageManager pm = context.getPackageManager();
PackageInfo packageInfo = null;
try {
packageInfo = pm.getPackageInfo(packageName, 0);
} catch (PackageManager.NameNotFoundException e) {
e.printStackTrace();
Log.e("getPackageInfo", packageName + ":" + e.getMessage());
}
return packageInfo;
}
synchronized public static String getApplicationName(Context context, String packageName) {
PackageManager pm = context.getPackageManager();
PackageInfo packageInfo = null;
String name = "";
try {
packageInfo = pm.getPackageInfo(packageName, 0);
name = pm.getApplicationLabel(packageInfo.applicationInfo).toString();
} catch (PackageManager.NameNotFoundException e) {
e.printStackTrace();
Log.e("getPackageInfo", packageName + ":" + e.getMessage());
}
return name;
}
public static void installApk(Activity activity, File newApkFile) {
Intent intent = new Intent(Intent.ACTION_VIEW);
intent.addCategory(Intent.CATEGORY_DEFAULT);
intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
String type = "application/vnd.android.package-archive";
Uri uri;
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
uri = FileProvider.getUriForFile(activity, "com.uiui.sn.fileprovider", newApkFile);
intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
} else {
uri = Uri.fromFile(newApkFile);
}
intent.setDataAndType(uri, type);
activity.startActivity(intent);
}
public static void installApk(Context context, File newApkFile) {
Intent intent = new Intent(Intent.ACTION_VIEW);
intent.addCategory(Intent.CATEGORY_DEFAULT);
intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
String type = "application/vnd.android.package-archive";
Uri uri;
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
uri = FileProvider.getUriForFile(context, "com.uiui.sn.fileprovider", newApkFile);
intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
} else {
uri = Uri.fromFile(newApkFile);
}
intent.setDataAndType(uri, type);
context.startActivity(intent);
}
public static void hideSystemSettingAPP(Context context, String pkage) {
int hide = 0;
//后台0显示1隐藏
try {
if ("com.mediatek.camera".equalsIgnoreCase(pkage)) {
if (JGYUtils.getInt(context.getContentResolver(), "qch_app_camera") == 1) {
hide = 1;
}
} else if ("com.android.deskclock".equalsIgnoreCase(pkage)) {
if (JGYUtils.getInt(context.getContentResolver(), "qch_app_deskclock") == 1) {
hide = 1;
}
} else if ("com.android.soundrecorder".equalsIgnoreCase(pkage)) {
if (JGYUtils.getInt(context.getContentResolver(), "qch_app_soundrecorder") == 1) {
hide = 1;
}
} else if ("com.android.music".equalsIgnoreCase(pkage)) {
if (JGYUtils.getInt(context.getContentResolver(), "qch_app_music") == 1) {
hide = 1;
}
} else if ("com.android.gallery3d".equalsIgnoreCase(pkage)) {
if (JGYUtils.getInt(context.getContentResolver(), "qch_app_gallery") == 1) {
hide = 1;
}
} else if ("com.android.documentsui".equalsIgnoreCase(pkage)
|| "com.mediatek.filemanager".equalsIgnoreCase(pkage)) {
if (JGYUtils.getInt(context.getContentResolver(), "qch_app_filemanager") == 1) {
hide = 1;
}
}
} catch (Settings.SettingNotFoundException e) {
e.printStackTrace();
}
// PackageManager pm = context.getPackageManager();
// if (hide == 0) {
// pm.setApplicationEnabledSetting(pkage, PackageManager.COMPONENT_ENABLED_STATE_DEFAULT, 0);
// } else {
// pm.setApplicationEnabledSetting(pkage, PackageManager.COMPONENT_ENABLED_STATE_DISABLED, 0);
// }
}
public static int getAppVersionCode(Context context, String packageName) {
PackageManager pm = context.getPackageManager();
PackageInfo info = null;
try {
info = pm.getPackageInfo(packageName, 0);
} catch (PackageManager.NameNotFoundException e) {
e.printStackTrace();
}
if (null != info) {
long appVersionCode;
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.P) {
appVersionCode = info.getLongVersionCode();
} else {
appVersionCode = info.versionCode;
}
return (int) appVersionCode;
} else {
return 0;
}
}
public static void addShortcut(Context context) {
String packageList = Settings.System.getString(context.getContentResolver(), "only_jgy_shortcut_list");
if (TextUtils.isEmpty(packageList)) {
JGYUtils.putString(context.getContentResolver(), "qch_launcher_icon_app", "");
return;
}
Log.e("addShortcut", "addShortcut: " + packageList);
String[] stringList = packageList.split(",");
HashSet<String> packages = new HashSet<>(Arrays.asList(stringList));
String romapps = JGYUtils.getString(context.getContentResolver(), "jgy_customromapp");
Log.e(TAG, "addShortcut: romapps: " + romapps);
HashSet<String> appSet = new HashSet<>();
if (!TextUtils.isEmpty(romapps)) {
appSet = new HashSet<>(Arrays.asList(romapps.split(",")));
packages.addAll(appSet);
}
packages.removeIf(new Predicate<String>() {
@Override
public boolean test(String s) {
return TextUtils.isEmpty(s);
}
});
StringBuilder installedListBuilder = new StringBuilder();
for (String s : packages) {
if ("com.jiaoguanyi.store".equals(s) || "com.jiaoguanyi.appstore".equals(s)) {
continue;
}
if (isSystemApp(context, s)) {
if (!appSet.contains(s)) {
continue;
}
}
if (!isAvailable(context, s)) {
continue;
}
// getStartActivityName(context, s);
if (installedListBuilder.length() > 0) {
installedListBuilder.append(",");
}
installedListBuilder.append(s);
Log.e("addShortcut", "packages: " + s);
}
String installedList = installedListBuilder.toString();
boolean qch_force_app = JGYUtils.putString(context.getContentResolver(), "qch_launcher_icon_app", installedList);
// String old = JGYUtils.getString(context.getContentResolver(), "qch_launcher_icon_app");
// Log.e("addShortcut", old);
Log.e("addShortcut", "installedList:" + installedList);
Log.e("addShortcut", "putstring:" + qch_force_app);
}
@SuppressLint("NewApi")
public static void writeAppPackageList(Context context, String result) {
addShortcut(context);//开机之后添加图标到桌面
HashSet<String> factoryAppList = new HashSet<String>() {{
this.add("com.jiaoguanyi.appstore");
this.add("com.jiaoguanyi.store");
this.add("com.uiui.sn");
this.add("com.appstore.uiui");
this.add("com.uiui.appstore");
this.add("com.android.uiuios");
this.add("com.uiuios.jgy1");
this.add("com.uiuios.jgy2");
this.add("com.tt.ttutils");
this.add("com.info.chat");
this.add("com.info.learning");
this.add("com.uiui.browser");
this.add("com.uiui.os");
this.add("com.alarmclock.uiui");
}};
HashSet<String> factoryAppSet = new HashSet<>(factoryAppList);
if (!TextUtils.isEmpty(result)) {
HashSet<String> writeAppSet = new HashSet<>(Arrays.asList(result.split(",")));
writeAppSet.addAll(factoryAppSet);
String pkgString = String.join(",", writeAppSet);
Log.e("fht", "qch_app_forbid :" + pkgString);
boolean qch_app_forbid = JGYUtils.putString(context.getContentResolver(), "qch_app_forbid", pkgString);
} else {
JGYUtils.putString(context.getContentResolver(), "qch_app_forbid", String.join(",", factoryAppSet));
Log.e("fht", "writeAppPackageList is null:");
}
Utils.writeDisableUpdateList(context);
}
/**
* 判断是否为系统应用
*
* @param context 上下文
* @param pkgName 包名
* @return
*/
public static boolean isSystemApp(Context context, String pkgName) {
boolean isSystemApp = false;
PackageInfo pi = null;
try {
PackageManager pm = context.getPackageManager();
pi = pm.getPackageInfo(pkgName, 0);
} catch (PackageManager.NameNotFoundException e) {
Log.e("isSystemApp: NameNotFoundException:", e.getMessage());
}
// 是系统中已安装的应用
if (pi != null) {
boolean isSysApp = (pi.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) == 1;
boolean isSysUpd = (pi.applicationInfo.flags & ApplicationInfo.FLAG_UPDATED_SYSTEM_APP) == 1;
isSystemApp = isSysApp || isSysUpd;
}
return isSystemApp;
}
//通过包名获取版本号
public static String getAPPVersionName(Context context, String packageName) {
String versionName = "0";
if (TextUtils.isEmpty(packageName)) {
return versionName;
}
PackageManager pm = context.getPackageManager();
try {
PackageInfo packageInfo = pm.getPackageInfo(packageName, 0);
versionName = packageInfo.versionName;
} catch (PackageManager.NameNotFoundException e) {
e.printStackTrace();
}
return versionName;
}
public static String getTaskPackname(Context context) {
String currentApp = "CurrentNULL";
if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.LOLLIPOP) {
@SuppressLint("WrongConstant") UsageStatsManager usm = (UsageStatsManager) context.getSystemService("usagestats");
long time = System.currentTimeMillis();
List<UsageStats> appList = usm.queryUsageStats(UsageStatsManager.INTERVAL_DAILY, time - 1000 * 1000, time);
if (appList != null && appList.size() > 0) {
SortedMap<Long, UsageStats> mySortedMap = new TreeMap<Long, UsageStats>();
for (UsageStats usageStats : appList) {
mySortedMap.put(usageStats.getLastTimeUsed(), usageStats);
}
if (mySortedMap != null && !mySortedMap.isEmpty()) {
currentApp = mySortedMap.get(mySortedMap.lastKey()).getPackageName();
}
}
} else {
ActivityManager am = (ActivityManager) context.getSystemService(Context.ACTIVITY_SERVICE);
List<ActivityManager.RunningAppProcessInfo> tasks = am.getRunningAppProcesses();
currentApp = tasks.get(0).processName;
}
// Log.e("TAG", "Current App in foreground is: " + currentApp);
return currentApp;
}
public static boolean getIsCanStart(Context context, String pkg) {
Intent intent = new Intent(Intent.ACTION_MAIN, null);
intent.addCategory(Intent.CATEGORY_LAUNCHER);
// 通过查询获得所有ResolveInfo对象.
List<ResolveInfo> infos = context.getPackageManager().queryIntentActivities(intent, 0);
HashMap<String, ResolveInfo> hashMap = new HashMap<>();
for (ResolveInfo info : infos) {
hashMap.put(info.activityInfo.packageName, info);
}
if (hashMap.get(pkg) == null) {
return false;
} else {
return true;
}
}
/**
* 获取第三方应用
*
* @param context
* @return
*/
public static List<String> queryFilterAppInfo(Context context) {
PackageManager pm = context.getPackageManager();
// 查询所有已经安装的应用程序
List<ApplicationInfo> appInfos = pm.getInstalledApplications(PackageManager.GET_UNINSTALLED_PACKAGES);// GET_UNINSTALLED_PACKAGES代表已删除但还有安装目录的
List<String> applicationInfos = new ArrayList<>();
for (ApplicationInfo app : appInfos) {
// Logutils.e("queryFilterAppInfo", String.valueOf(app.flags));
// Logutils.e("queryFilterAppInfo", String.valueOf((app.flags & mask)));
if ((app.flags & ApplicationInfo.FLAG_SYSTEM) == 1) {
//通过flag排除系统应用会将电话、短信也排除掉
} else {
applicationInfos.add(app.packageName);
Log.e("queryFilterAppInfo", app.packageName);
}
}
return applicationInfos;
}
}