Files
CubeAoleyunSN/app/src/main/java/com/aoleyun/sn/utils/JGYUtils.java

2999 lines
123 KiB
Java
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
package com.aoleyun.sn.utils;
import android.annotation.SuppressLint;
import android.app.ActivityManager;
import android.app.ActivityManagerNative;
import android.app.ActivityTaskManager;
import android.app.role.RoleManager;
import android.content.ComponentName;
import android.content.ContentResolver;
import android.content.Context;
import android.content.ContextWrapper;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.ServiceConnection;
import android.content.pm.ApplicationInfo;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.content.pm.ResolveInfo;
import android.content.pm.UserInfo;
import android.graphics.Bitmap;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.net.Uri;
import android.os.BatteryManager;
import android.os.Build;
import android.os.Environment;
import android.os.IBinder;
import android.os.PowerManager;
import android.os.Process;
import android.os.RemoteException;
import android.os.SystemProperties;
import android.os.UserHandle;
import android.provider.Settings;
import android.text.TextUtils;
import android.util.Log;
import androidx.annotation.Nullable;
import androidx.annotation.RequiresApi;
import androidx.core.content.ContextCompat;
import com.aoleyun.sn.BuildConfig;
import com.aoleyun.sn.bean.AdminAppInfo;
import com.aoleyun.sn.bean.AppListInfo;
import com.aoleyun.sn.bean.Appground;
import com.aoleyun.sn.bean.BaseResponse;
import com.aoleyun.sn.bean.ForceDownloadData;
import com.aoleyun.sn.bean.NetAndLaunchBean;
import com.aoleyun.sn.bean.NetAndLaunchData;
import com.aoleyun.sn.bean.TTAppground;
import com.aoleyun.sn.comm.CommonConfig;
import com.aoleyun.sn.comm.JGYActions;
import com.aoleyun.sn.comm.PackageNames;
import com.aoleyun.sn.disklrucache.CacheHelper;
import com.aoleyun.sn.gson.GsonUtils;
import com.aoleyun.sn.network.NetInterfaceManager;
import com.aoleyun.sn.network.UrlAddress;
import com.aoleyun.sn.receiver.BootReceiver;
import com.aoleyun.sn.service.GuardService;
import com.aoleyun.sn.service.LogcatService;
import com.aoleyun.sn.service.StepService;
import com.aoleyun.sn.service.main.MainService;
import com.blankj.utilcode.util.FileUtils;
import com.google.gson.Gson;
import com.google.gson.JsonObject;
import com.google.gson.reflect.TypeToken;
import com.google.zxing.BarcodeFormat;
import com.google.zxing.EncodeHintType;
import com.google.zxing.WriterException;
import com.google.zxing.common.BitMatrix;
import com.google.zxing.qrcode.QRCodeWriter;
import com.google.zxing.qrcode.decoder.ErrorCorrectionLevel;
import com.kte.interfacesettings.aidl.ITools;
import com.tencent.mmkv.MMKV;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.lang.reflect.Constructor;
import java.lang.reflect.Field;
import java.lang.reflect.Method;
import java.lang.reflect.Type;
import java.net.Inet4Address;
import java.net.InetAddress;
import java.net.NetworkInterface;
import java.net.SocketException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Enumeration;
import java.util.HashMap;
import java.util.HashSet;
import java.util.LinkedHashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.concurrent.Executor;
import java.util.function.BiConsumer;
import java.util.function.Consumer;
import java.util.function.Predicate;
import java.util.stream.Collectors;
import io.reactivex.rxjava3.annotations.NonNull;
import io.reactivex.rxjava3.core.Observable;
import io.reactivex.rxjava3.core.ObservableEmitter;
import io.reactivex.rxjava3.core.ObservableOnSubscribe;
import io.reactivex.rxjava3.core.Observer;
import io.reactivex.rxjava3.disposables.Disposable;
import static android.app.ActivityManager.RECENT_IGNORE_UNAVAILABLE;
public class JGYUtils {
private static final String TAG = JGYUtils.class.getSimpleName();
@SuppressLint("StaticFieldLeak")
private static JGYUtils sInstance;
private MMKV mMMKV = MMKV.mmkvWithID(CommonConfig.MMKV_ID, MMKV.MULTI_PROCESS_MODE);
private Context mContext;
private ContentResolver crv;
public static final int UnknowPlatform = 0;
public static final int MTKPlatform = 1;
public static final int CubePlatform = 2;
public static final int ZhanruiPlatform = 3;
public static final int MTK11Platform = 5;
public static final int TeclastP20sPlatform = 6;
public static final int AH6016Platform = 9;
public static final int ZR6016Platform = 10;
public static final int HRAD13Platform = 11;
public static final int G10PPlatform = 12;
public static final int C2Platform = 13;
public static final String Other = "其他";
public static final String MTKTag = "MTK";
public static final String CubeTag = "展锐cube";
public static final String ZhanruiTag = "展锐";
public static final String MTK11Tag = "MTK11";
public static final String TeclastP20sTag = "P20S";
public static final String AH6016Tag = "AH6016";
public static final String ZR6016Tag = "ZR6016";
public static final String HRAD13Tag = "HRAD13";
public static final String G10PTag = "G10P";
public static final String C2Tag = "MTK8183";
private CacheHelper cacheHelper;
static {
System.loadLibrary("jgy");
}
private JGYUtils(Context context) {
if (context == null) {
throw new RuntimeException("Context is NULL");
}
this.mContext = context;
this.crv = context.getContentResolver();
this.cacheHelper = new CacheHelper(context);
initConnectedTimeCache();
if (C2Tag.equals(BuildConfig.platform)) {
Log.e(TAG, "JGYUtils: c2");
mServiceConnection = new ServiceConnection() {
@Override
public void onServiceConnected(ComponentName componentName, IBinder iBinder) {
Log.e(TAG, "onServiceConnected: " + componentName);
try {
mITools = ITools.Stub.asInterface(iBinder);
} catch (Exception e) {
e.printStackTrace();
}
}
@Override
public void onServiceDisconnected(ComponentName componentName) {
Log.e(TAG, "onServiceDisconnected: " + componentName);
mITools = null;
bindEbaifenService();
}
};
bindEbaifenService();
}
}
public static void init(Context context) {
if (sInstance == null) {
Log.e(TAG, "init: ");
sInstance = new JGYUtils(context);
}
}
public static JGYUtils getInstance() {
if (sInstance == null) {
throw new IllegalStateException("You must be init JGYUtils first");
}
return sInstance;
}
public static native String getAuthorization();
private static final String EBAIFEN_PACKAGE = "com.kte.interfacesettings";
private static final String EBAIFEN_CLASS_NAME = "com.kte.interfacesettings.ToolsImplService";
private static final String EBAIFEN_ACTION = "com.kte.interfacesettings.aidl";
private ITools mITools;
private ServiceConnection mServiceConnection;
private void bindEbaifenService() {
Intent intent = new Intent(EBAIFEN_ACTION);
intent.setPackage(EBAIFEN_PACKAGE);
// intent.setComponent(new ComponentName(EBAIFEN_PACKAGE, EBAIFEN_CLASS_NAME));
mContext.bindService(intent, mServiceConnection, Context.BIND_AUTO_CREATE);
}
public int checkSNPlatform(String sn) {
if (TextUtils.isEmpty(sn)) return UnknowPlatform;
String secondChars = sn.substring(1, 2);
if ("N".equalsIgnoreCase(secondChars)) {//MTK平台
return MTKPlatform;
} else if ("R".equalsIgnoreCase(secondChars)) {//展锐平台
return ZhanruiPlatform;
} else {
Log.e(TAG, "checkSNPlatform: " + "sn: " + sn + "没有对应平台");
return UnknowPlatform;
}
}
public int checkAppPlatform() {
String platform = BuildConfig.platform;
if ("MTK".equalsIgnoreCase(platform)) {
Log.i(TAG, "checkAppPlatform: " + "MTK平台");
return MTKPlatform;
} else if ("ZhanRui".equalsIgnoreCase(platform)) {
Log.i(TAG, "checkAppPlatform: " + "展锐平台");
return ZhanruiPlatform;
} else if ("ZhanRuiCube".equalsIgnoreCase(platform)) {
Log.i(TAG, "checkAppPlatform: " + "ZhanRuiCube");
return CubePlatform;
} else if (MTK11Tag.equalsIgnoreCase(platform)) {
Log.i(TAG, "checkAppPlatform: " + "MTK11");
return MTK11Platform;
} else if (TeclastP20sTag.equalsIgnoreCase(platform)) {
Log.i(TAG, "checkAppPlatform: " + "P20S");
return TeclastP20sPlatform;
} else if (AH6016Tag.equalsIgnoreCase(platform)) {
Log.i(TAG, "checkAppPlatform: " + "AH6016");
return AH6016Platform;
} else if (ZR6016Tag.equalsIgnoreCase(platform)) {
Log.i(TAG, "checkAppPlatform: " + "ZR6016");
return ZR6016Platform;
} else if (HRAD13Tag.equalsIgnoreCase(platform)) {
Log.i(TAG, "checkAppPlatform: " + "HRAD13");
return HRAD13Platform;
} else if (G10PTag.equalsIgnoreCase(platform)) {
Log.i(TAG, "checkAppPlatform: " + "G10P");
return G10PPlatform;
} else if (C2Tag.equalsIgnoreCase(platform)) {
Log.i(TAG, "checkAppPlatform: " + "C2");
return C2Platform;
} else {
Log.i(TAG, "checkAppPlatform: " + "没有数据");
return UnknowPlatform;
}
}
public boolean isSamePlatform(String platform) {
String AppPlatform = BuildConfig.platform;
if ("ZhanRui".equals(AppPlatform)) {
return ZhanruiTag.equals(platform);
} else {
return AppPlatform.equals(platform);
}
}
public interface GetAppPlatformCallback {
void AppPlatform(int platform);
}
public void getAppPlatform(GetAppPlatformCallback getAppPlatformCallback) {
String platform = BuildConfig.platform;
if ("MTK".equalsIgnoreCase(platform)) {
getAppPlatformCallback.AppPlatform(MTKPlatform);
} else if ("ZhanRui".equalsIgnoreCase(platform)) {
getAppPlatformCallback.AppPlatform(ZhanruiPlatform);
} else if ("ZhanRuiCube".equalsIgnoreCase(platform)) {
getAppPlatformCallback.AppPlatform(CubePlatform);
} else if ("MTK11".equalsIgnoreCase(platform)) {
getAppPlatformCallback.AppPlatform(MTK11Platform);
} else if (TeclastP20sTag.equalsIgnoreCase(platform)) {
getAppPlatformCallback.AppPlatform(TeclastP20sPlatform);
} else if (AH6016Tag.equalsIgnoreCase(platform)) {
getAppPlatformCallback.AppPlatform(AH6016Platform);
} else if (ZR6016Tag.equalsIgnoreCase(platform)) {
getAppPlatformCallback.AppPlatform(ZR6016Platform);
} else if (HRAD13Tag.equalsIgnoreCase(platform)) {
getAppPlatformCallback.AppPlatform(HRAD13Platform);
} else if (G10PTag.equalsIgnoreCase(platform)) {
getAppPlatformCallback.AppPlatform(G10PPlatform);
} else if (C2Tag.equalsIgnoreCase(platform)) {
getAppPlatformCallback.AppPlatform(C2Platform);
} else {
getAppPlatformCallback.AppPlatform(UnknowPlatform);
}
}
public String getAppPlatform() {
String platform = BuildConfig.platform;
if ("MTK".equalsIgnoreCase(platform)) {
return MTKTag;
} else if ("ZhanRui".equalsIgnoreCase(platform)) {
return ZhanruiTag;
} else if (CubeTag.equalsIgnoreCase(platform)) {
return CubeTag;
} else if (MTK11Tag.equalsIgnoreCase(platform)) {
return MTK11Tag;
} else if (TeclastP20sTag.equalsIgnoreCase(platform)) {
return TeclastP20sTag;
} else if (AH6016Tag.equalsIgnoreCase(platform)) {
return AH6016Tag;
} else if (ZR6016Tag.equalsIgnoreCase(platform)) {
return ZR6016Tag;
} else if (HRAD13Tag.equalsIgnoreCase(platform)) {
return HRAD13Tag;
} else if (G10PTag.equalsIgnoreCase(platform)) {
return G10PTag;
} else if (C2Tag.equalsIgnoreCase(platform)) {
return C2Tag;
} else {
return Other;
}
}
public static boolean isOfficialVersion() {
String channelValue = JGYUtils.getInstance().getStringMetaData();
return "official".equals(channelValue);
}
public static boolean isOfficialVersion(Context context) {
Log.e(TAG, "isOfficialVersion: " + ProcessUtil.getCurrentProcessName(context));
String channelValue = JGYUtils.getInstance().getStringMetaData();
return "official".equals(channelValue);
}
public static boolean isNewlyVersion() {
String channelValue = JGYUtils.getInstance().getStringMetaData();
return "beta".equals(channelValue);
}
public static boolean isBetaVersion() {
String channelValue = JGYUtils.getInstance().getStringMetaData();
return "beta".equals(channelValue);
}
public static String getCHANNEL_VALUE() {
return JGYUtils.getInstance().getStringMetaData();
}
public void resetDevice() {
boolean isReset = MySQLData.GetBooleanData(mContext, CommonConfig.IS_RESET);
int batteryLevel = getBatteryLevel();
Log.e(TAG, "batteryLevel:" + batteryLevel + " isReset" + isReset);
if (isReset && batteryLevel >= CommonConfig.MIN_POWER) {
Utils.doMasterClear(mContext);
}
}
public String getDownLoadPath() {
String path = ContextCompat.getExternalFilesDirs(mContext, Environment.DIRECTORY_DOWNLOADS)[0].getAbsolutePath();
return path + File.separator;
}
public boolean getDeviceIsLocked() {
int locked = Settings.System.getInt(crv, JGYActions.ACTION_QCH_UNLOCK_IPAD, JGYActions.FRAME_CODE_LOCKED);
return locked == JGYActions.FRAME_CODE_LOCKED;
}
public boolean tagEmpty() {
String tag = mMMKV.decodeString(CommonConfig.DEVICES_TAG, "");
return TextUtils.isEmpty(tag);
}
public int getBatteryLevel() {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
BatteryManager batteryManager = (BatteryManager) mContext.getSystemService(Context.BATTERY_SERVICE);
return batteryManager.getIntProperty(BatteryManager.BATTERY_PROPERTY_CAPACITY);
} else {
Intent intent = new ContextWrapper(mContext).registerReceiver(null, new IntentFilter(Intent.ACTION_BATTERY_CHANGED));
return (intent.getIntExtra(BatteryManager.EXTRA_LEVEL, -1) * 100) /
intent.getIntExtra(BatteryManager.EXTRA_SCALE, -1);
}
}
private PowerManager.WakeLock wakeLock = null;
private static final String mWakeLockName = "BackupService";
/**
* 获取电源锁保持该服务在屏幕熄灭时仍然获取CPU时保持运行
*/
@SuppressLint("InvalidWakeLockTag")
private synchronized void acquireWakeLock() {
if (null == wakeLock) {
PowerManager pm = (PowerManager) mContext.getSystemService(Context.POWER_SERVICE);
wakeLock = pm.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK
| PowerManager.ON_AFTER_RELEASE, mWakeLockName);
if (null != wakeLock) {
Log.e("fht", "acquireWakeLock!");
wakeLock.acquire();
}
}
}
/**
* 释放设备电源锁
*/
private synchronized void releaseWakeLock() {
if (null != wakeLock) {
Log.e("fht", "releaseWakeLock!");
wakeLock.release();
wakeLock = null;
}
}
/**
* 忽略电池优化
*/
private void ignoreBatteryOptimization(Context context) {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
PowerManager powerManager = (PowerManager) mContext.getSystemService(Context.POWER_SERVICE);
boolean hasIgnored = powerManager.isIgnoringBatteryOptimizations(context.getPackageName());
// 判断当前APP是否有加入电池优化的白名单如果没有弹出加入电池优化的白名单的设置对话框。
if (!hasIgnored) {
Intent intent = new Intent(Settings.ACTION_REQUEST_IGNORE_BATTERY_OPTIMIZATIONS);
intent.setData(Uri.parse("package:" + context.getPackageName()));
intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
mContext.startActivity(intent);
}
}
}
public static boolean getScreenStatus(Context context) {
PowerManager powerManager = (PowerManager) context.getSystemService(Context.POWER_SERVICE);
//true为打开false为关闭
return powerManager.isScreenOn();
}
/**
* 点亮屏幕
*
* @param timeout The timeout after which to release the wake lock, in milliseconds.
*/
@Nullable
public static PowerManager.WakeLock acquireWakeLock(@NonNull Context context, long timeout) {
PowerManager pm = (PowerManager) context.getSystemService(Context.POWER_SERVICE);
if (pm == null)
return null;
PowerManager.WakeLock wakeLock = pm.newWakeLock(PowerManager.ACQUIRE_CAUSES_WAKEUP |
PowerManager.FULL_WAKE_LOCK |
PowerManager.ON_AFTER_RELEASE,
context.getClass().getName());
wakeLock.acquire(timeout);
return wakeLock;
}
public static void release(@Nullable PowerManager.WakeLock wakeLock) {
if (wakeLock != null && wakeLock.isHeld()) {
wakeLock.release();
}
}
/**
* 应用自启升级和网络权限管理
*
* @param netAndLaunchBean
*/
@SuppressLint("NewApi")
synchronized public void setNetAndlaunch(NetAndLaunchBean netAndLaunchBean, List<AppListInfo> appListInfos) {
Log.e(TAG, "setNetAndlaunch: " + "应用联网管控: " + netAndLaunchBean.getData().toString());
Log.e(TAG, "setNetAndlaunch: ");
HashSet<String> autoLaunchApp = new HashSet<>();//开机自启app
HashSet<String> allowNetApp = new HashSet<>();//允许联网
HashSet<String> disallowNetApp = new HashSet<>();//禁止联网
HashSet<String> allowUpgrade = new HashSet<>();//允许升级
HashSet<String> disallowUpgrade = new HashSet<>();//禁止升级
HashSet<String> allowSlide = new HashSet<>();//允许滑动
HashSet<String> disallowSlide = new HashSet<>();//禁止滑动
List<NetAndLaunchData> data = netAndLaunchBean.getData();
for (NetAndLaunchData netAndLaunchData : data) {
String app_package = netAndLaunchData.getApp_package();
int is_auto = netAndLaunchData.getIs_auto();
int is_network = netAndLaunchData.getIs_network();
int is_upgrade = netAndLaunchData.getIs_upgrade();
int is_slide = netAndLaunchData.getIs_slide();
if (is_auto == 1) {
autoLaunchApp.add(app_package);
}
if (is_network == 1) {
allowNetApp.add(app_package);
} else {
disallowNetApp.add(app_package);
}
if (is_upgrade == 1) {
allowUpgrade.add(app_package);
} else {
disallowUpgrade.add(app_package);
}
if (is_slide == 1) {
allowSlide.add(app_package);
} else {
disallowSlide.add(app_package);
}
}
if (disallowSlide.size() != 0) {
String slide_not = String.join(",", disallowSlide);
boolean writeSucceed = Settings.System.putString(crv, CommonConfig.AOLE_ACTION_DISABLE_SLIDE, slide_not);
Log.e("fht", "aole_disable_slide=" + writeSucceed + ":" + slide_not);
} else {
String slide_ok = String.join(",", allowSlide);
boolean writeSucceed = Settings.System.putString(crv, CommonConfig.AOLE_ACTION_DISABLE_SLIDE, "Invalid");
Log.e("fht", "aole_disable_slide ok=" + writeSucceed + ":" + slide_ok);
}
String[] upgrade_ok = new String[allowUpgrade.size()];
allowUpgrade.toArray(upgrade_ok);
checkPackageAndVersion(disallowUpgrade, appListInfos);
String[] upgrade_not = new String[disallowUpgrade.size()];
disallowUpgrade.toArray(upgrade_not);
Utils.writeDisableUpdateList(mContext, upgrade_not, upgrade_ok);
String aole_app_power_on = String.join(",", autoLaunchApp);
Log.e(TAG, "setNetAndlaunch: aole_app_power_on: " + aole_app_power_on);
if (TextUtils.isEmpty(aole_app_power_on)) {
//当 aole_app_power_on 的值为空时,会造成系统所有应用断网
Settings.System.putString(crv, CommonConfig.AOLE_ACTION_APP_POWER_ON, "Invalid");
Log.e(TAG, "setNetAndlaunch: aole_app_power_on: " + "Invalid");
} else {
Settings.System.putString(crv, CommonConfig.AOLE_ACTION_APP_POWER_ON, aole_app_power_on);
Log.e(TAG, "setNetAndlaunch: aole_app_power_on: " + aole_app_power_on);
}
// if (BuildConfig.DEBUG) {
// TODO: 2021/7/2 测试写入为空是否断网
// boolean w = Settings.System.putString(crv, "aole_app_power_on", "");
// Log.e(TAG, "setNetAndlaunch: 测试写入: " + w);
// }
setAppNetwork(mContext, disallowNetApp, allowNetApp);
}
public void onBootOpenApp() {
String qch_app_power_on = Settings.System.getString(mContext.getContentResolver(), CommonConfig.AOLE_ACTION_APP_POWER_ON);
if (TextUtils.isEmpty(qch_app_power_on)) {
return;
}
List<String> appList = new ArrayList<>(Arrays.asList(qch_app_power_on.split(",")));
for (String s : appList) {
if (TextUtils.isEmpty(s)) continue;
Log.e(TAG, "onBootOpenApp: " + s);
ApkUtils.openApp(mContext, s);
}
}
private void checkPackageAndVersion(HashSet<String> disallowUpgrade, List<AppListInfo> appListInfos) {
if (appListInfos == null || appListInfos.size() == 0) {
return;
}
Log.e(TAG, "checkPackageAndVersion: " + disallowUpgrade);
PackageManager pm = mContext.getPackageManager();
HashMap<String, AppListInfo> listInfoHashMap = new HashMap<>();
for (AppListInfo appListInfo : appListInfos) {
listInfoHashMap.put(appListInfo.getApp_package(), appListInfo);
}
for (String pkg : disallowUpgrade) {
AppListInfo info = listInfoHashMap.get(pkg);
if (info != null) {
PackageInfo packageInfo = null;
try {
packageInfo = pm.getPackageInfo(pkg, 0);
long appVersionCode;
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.P) {
appVersionCode = packageInfo.getLongVersionCode();
} else {
appVersionCode = packageInfo.versionCode;
}
if (appVersionCode > info.getApp_version_code() && info.getApp_version_code() != 0) {
Log.e(TAG, "checkPackageAndVersion: appVersionCode: " + appVersionCode + " getApp_version_code: " + info.getApp_version_code());
Log.e(TAG, "checkPackageAndVersion: " + pkg + " 卸载");
ApkUtils.UninstallAPP(mContext, pkg);
JsonObject packageObj = new JsonObject();
packageObj.addProperty("app_name", info.getApp_name());
packageObj.addProperty("app_package", info.getApp_package());
packageObj.addProperty("app_id", info.getApp_id());
packageObj.addProperty("MD5", info.getApp_md5());
Utils.ariaDownload(mContext, info.getApp_url(), packageObj);
} else {
Log.e(TAG, "checkPackageAndVersion: " + pkg + " 版本正常");
}
} catch (PackageManager.NameNotFoundException e) {
e.printStackTrace();
}
}
}
}
@SuppressLint("NewApi")
synchronized public void setNetAndlaunch(NetAndLaunchBean netAndLaunchBean) {
Log.e(TAG, "setNetAndlaunch: " + "应用联网管控: " + netAndLaunchBean.getData().toString());
Log.e(TAG, "setNetAndlaunch: ");
HashSet<String> autoLaunchApp = new HashSet<>();//开机自启app
HashSet<String> allowNetApp = new HashSet<>();//允许联网
HashSet<String> disallowNetApp = new HashSet<>();//禁止联网
HashSet<String> allowUpgrade = new HashSet<>();//允许升级
HashSet<String> disallowUpgrade = new HashSet<>();//禁止升级
HashSet<String> allowSlide = new HashSet<>();//允许滑动
HashSet<String> disallowSlide = new HashSet<>();//禁止滑动
List<NetAndLaunchData> data = netAndLaunchBean.getData();
for (NetAndLaunchData netAndLaunchData : data) {
String app_package = netAndLaunchData.getApp_package();
int is_auto = netAndLaunchData.getIs_auto();
int is_network = netAndLaunchData.getIs_network();
int is_upgrade = netAndLaunchData.getIs_upgrade();
int is_slide = netAndLaunchData.getIs_slide();
if (is_auto == 1) {
autoLaunchApp.add(app_package);
}
if (is_network == 1) {
allowNetApp.add(app_package);
} else {
disallowNetApp.add(app_package);
}
if (is_upgrade == 1) {
allowUpgrade.add(app_package);
} else {
disallowUpgrade.add(app_package);
}
if (is_slide == 1) {
allowSlide.add(app_package);
} else {
disallowSlide.add(app_package);
}
}
if (disallowSlide.size() != 0) {
String slide_not = String.join(",", disallowSlide);
boolean writeSucceed = Settings.System.putString(crv, CommonConfig.AOLE_ACTION_DISABLE_SLIDE, slide_not);
Log.e("fht", "aole_disable_slide=" + writeSucceed + ":" + slide_not);
} else {
String slide_ok = String.join(",", allowSlide);
boolean writeSucceed = Settings.System.putString(crv, CommonConfig.AOLE_ACTION_DISABLE_SLIDE, "Invalid");
Log.e("fht", "aole_disable_slide ok=" + writeSucceed + ":" + slide_ok);
}
String[] upgrade_ok = new String[allowUpgrade.size()];
allowUpgrade.toArray(upgrade_ok);
String[] upgrade_not = new String[disallowUpgrade.size()];
disallowUpgrade.toArray(upgrade_not);
Utils.writeDisableUpdateList(mContext, upgrade_not, upgrade_ok);
String aole_app_power_on = String.join(",", autoLaunchApp);
Log.e(TAG, "setNetAndlaunch: aole_app_power_on: " + aole_app_power_on);
if (TextUtils.isEmpty(aole_app_power_on)) {
//当 qch_app_power_on 的值为空时,会造成系统所有应用断网
Settings.System.putString(crv, CommonConfig.AOLE_ACTION_APP_POWER_ON, "Invalid");
Log.e(TAG, "setNetAndlaunch: aole_app_power_on: " + "Invalid");
} else {
Settings.System.putString(crv, CommonConfig.AOLE_ACTION_APP_POWER_ON, aole_app_power_on);
Log.e(TAG, "setNetAndlaunch: aole_app_power_on: " + aole_app_power_on);
}
// if (BuildConfig.DEBUG) {
// TODO: 2021/7/2 测试写入为空是否断网
// boolean w = Settings.System.putString(crv, "aole_app_power_on", "");
// Log.e(TAG, "setNetAndlaunch: 测试写入: " + w);
// }
setAppNetwork(mContext, disallowNetApp, allowNetApp);
}
@SuppressLint("NewApi")
synchronized public static void setAppNetwork(Context context, HashSet<String> blackList, HashSet<String> whiteList) {
ContentResolver contentResolver = context.getContentResolver();
Log.e(TAG, "setAppNetwork: " + "设置应用联网管控" + blackList);
if (!MTK11Tag.equals(JGYUtils.getInstance().getAppPlatform())) {
if (blackList == null || blackList.size() == 0) {
SPUtils.put(context, CommonConfig.AOLE_ACTION_NETWORK_DISALLOW, "");
Settings.System.putString(contentResolver, CommonConfig.AOLE_ACTION_NETWORK_DISALLOW, "");
} else {
String net_not = String.join(",", blackList);
SPUtils.put(context, CommonConfig.AOLE_ACTION_NETWORK_DISALLOW, net_not);
Settings.System.putString(contentResolver, CommonConfig.AOLE_ACTION_NETWORK_DISALLOW, net_not);
Log.e(TAG, "setAppNetwork: " + net_not);
}
}
if (whiteList == null || whiteList.size() == 0) {
SPUtils.put(context, CommonConfig.AOLE_ACTION_NETWORK_ALLOW, "");
// Settings.System.putString(contentResolver, CommonConfig.AOLE_ACTION_NETWORK_ALLOW, "");
} else {
String net_not = String.join(",", whiteList);
SPUtils.put(context, CommonConfig.AOLE_ACTION_NETWORK_ALLOW, net_not);
Log.e(TAG, "setAppNetwork: net_not = " + net_not);
List<String> filterList = whiteList.stream().filter(s -> !ApkUtils.isAvailable(context, s)).collect(Collectors.toList());
if (filterList.size() == 0) {
// Settings.System.putString(contentResolver, CommonConfig.AOLE_ACTION_NETWORK_ALLOW, "");
} else {
// Settings.System.putString(contentResolver, CommonConfig.AOLE_ACTION_NETWORK_ALLOW, String.join(",", filterList));
}
Log.e(TAG, "setAppNetwork: filterList = " + filterList);
}
//Intent netControlIntent = new Intent(CommonDatas.ACTION_HrReceiver_JGY_DIS);
//netControlIntent.putExtra("package_name", net_not);
//sendBroadcast(netControlIntent);
//Intent netControlNotIntent = new Intent(CommonDatas.ACTION_HrReceiver_JGY);
//netControlNotIntent.putExtra("package_name", net_ok);
//sendBroadcast(netControlNotIntent);
}
public void updateNetworkWhiteList() {
String whiteString = (String) SPUtils.get(mContext, CommonConfig.AOLE_ACTION_NETWORK_ALLOW, "");
if (TextUtils.isEmpty(whiteString)) {
Log.e(TAG, "updateNetworkWhiteList: allow content is empty");
return;
}
List<String> whiteList = new ArrayList<>(Arrays.asList(whiteString.split(",")));
List<String> filterList = whiteList.stream().filter(s -> !ApkUtils.isAvailable(mContext, s)).collect(Collectors.toList());
if (filterList.size() == 0) {
// Settings.System.putString(crv, CommonConfig.AOLE_ACTION_NETWORK_ALLOW, "");
} else {
// Settings.System.putString(crv, CommonConfig.AOLE_ACTION_NETWORK_ALLOW, String.join(",", filterList));
}
Log.e(TAG, "updateNetworkWhiteList: " + filterList);
}
@SuppressLint("NewApi")
synchronized public void onBootSendNetwork() {
if (!MTK11Tag.equals(JGYUtils.getInstance().getAppPlatform())) {
String oldBlackListString = (String) SPUtils.get(mContext, CommonConfig.AOLE_ACTION_NETWORK_DISALLOW, "");
HashSet<String> oldBlackListSet = new HashSet<>(Arrays.asList(oldBlackListString.split(",")));
Log.e(TAG, "setAppNetwork: oldBlackListSet: " + oldBlackListSet);
oldBlackListSet.removeIf(new Predicate<String>() {
@Override
public boolean test(String s) {
return TextUtils.isEmpty(s.trim());
}
});
for (String pkg : oldBlackListSet) {
if (TextUtils.isEmpty(pkg)) continue;
if (!ApkUtils.isAvailable(mContext, pkg)) {
Log.e(TAG, "setAppNetwork: skip: " + pkg);
continue;
}
Intent netControlNotIntent = new Intent(CommonConfig.AOLE_ACTION_NETWORK_DISALLOW);
netControlNotIntent.putExtra("package_name", pkg);
netControlNotIntent.setPackage("com.android.settings");
mContext.sendBroadcast(netControlNotIntent);
}
}
}
/**
* @param ids 需要管控的ID
* @param packages 应用程序包名
*/
public void writeDeselectIDtoSystem(String ids, String packages) {
if (!TextUtils.isEmpty(ids) && !TextUtils.isEmpty(packages)) {
ArrayList<String> idArrayList = new ArrayList<>(Arrays.asList(ids.split(",")));
ArrayList<String> packageArrayList = new ArrayList<>(Arrays.asList(packages.split(",")));
LinkedHashSet<String> idHashSet = new LinkedHashSet<>(idArrayList);
LinkedHashSet<String> packageHashSet = new LinkedHashSet<>(packageArrayList);
ArrayList<String> idList = new ArrayList<>(idHashSet);
ArrayList<String> packageList = new ArrayList<>(packageHashSet);
StringBuilder idStringBuilder = new StringBuilder();
for (String id : idList) {
if (idStringBuilder.length() > 0) {
idStringBuilder.append(",");
}
idStringBuilder.append(id);
}
StringBuilder packageStringBuilder = new StringBuilder();
for (String pkg : packageList) {
if (packageStringBuilder.length() > 0) {
packageStringBuilder.append(",");
}
packageStringBuilder.append(pkg);
}
String olddeselectViewArray = Settings.System.getString(crv, CommonConfig.AOLE_ACTION_APP_FORBID_ID);
Log.e("writeDeselectIDtoSystem", "olddeselectViewArray: " + olddeselectViewArray);
Settings.System.putString(crv, CommonConfig.AOLE_ACTION_APP_FORBID_ID, packageStringBuilder.toString());
Settings.System.putString(crv, "DeselectViewArray", idStringBuilder.toString());
Log.e("writeDeselectIDtoSystem", "aole_app_forbid_id: " + packageStringBuilder.toString());
Log.e("writeDeselectIDtoSystem", "deselectViewArray: " + idStringBuilder.toString());
} else {
Log.e("writeDeselectIDtoSystem", "writeDeselectIDtoSystem is null:");
Settings.System.putString(crv, CommonConfig.AOLE_ACTION_APP_FORBID_ID, "");
Settings.System.putString(crv, "DeselectViewArray", "");
}
}
synchronized public void setAppinsideWeb(BaseResponse<List<Appground>> response) {
if (response.code == 200) {
List<Appground> appgrounds = response.data;
if (appgrounds != null && appgrounds.size() > 0) {
StringBuilder strings = new StringBuilder();
StringBuilder packageList = new StringBuilder();//单条管控名单
for (Appground appground : appgrounds) {
if (TextUtils.isEmpty(appground.getAddress())) {
if (packageList.length() > 0) {
packageList.append(",");
}
packageList.append(appground.getPackages());
} else {
if (strings.length() > 0) {
strings.append(";");
}
strings.append(appground.toString());
}
}
if (packageList.length() > 0) {
//app内所有的网页禁止
Log.e("setAppinsideWeb ", "packageList:" + packageList.toString());
Intent qch_app_website = new Intent("qch_app_website")
.setPackage("com.android.settings");
qch_app_website.putExtra("package_name", packageList.toString());
mContext.sendBroadcast(qch_app_website);
} else {
sendAllweb(mContext);
}
if (strings.length() > 0) {
//app内单个网页地址禁止打开
Log.e("setAppinsideWeb ", "strings:" + strings.toString());
Intent intent = new Intent("qch_app_inside_website")
.setPackage("com.android.settings");
intent.putExtra("websitelist", strings.toString());
mContext.sendBroadcast(intent);
} else {
sendwebUrl(mContext);
}
}
} else if (response.code == 400) {
//列表为空的情况
sendAllweb(mContext);
sendwebUrl(mContext);
//ToastUtil.show(msg);
Log.e("setAppinsideWeb", "setAppinsideWeb: " + response.msg);
}
}
/**
* @param response 黑白名单都可以管控
*/
synchronized public void setNewAppinsideWeb(BaseResponse response) {
Log.e(TAG, "setNewAppinsideWeb: " + "应用内部联网管控: " + response);
if (response.code == 200) {
String jsonString = GsonUtils.toJSONString(response.data);
Gson gson = new Gson();
Type type = new TypeToken<List<TTAppground>>() {
}.getType();
List<TTAppground> appgrounds = gson.fromJson(jsonString, type);
List<TTAppground> whiteApp = new ArrayList<>();
List<TTAppground> blackApp = new ArrayList<>();
if (appgrounds != null && appgrounds.size() > 0) {
for (TTAppground appground : appgrounds) {
if (appground.getType() == 1) {
whiteApp.add(appground);
} else {
blackApp.add(appground);
}
}
Log.e(TAG, "setAppinsideWeb: whiteApp: " + whiteApp);
Log.e(TAG, "setAppinsideWeb: blackApp: " + blackApp);
setWhiteApp(whiteApp);
setBlackApp(blackApp);
}
} else if (response.code == 400) {
//列表为空的情况
List<TTAppground> whiteApp = new ArrayList<>();
setWhiteApp(whiteApp);
sendAllweb(mContext);
sendwebUrl(mContext);
//ToastUtil.show(msg);
Log.e("setAppinsideWeb", "setAppinsideWeb: " + response.msg);
}
}
public static final String JGY_APPINSIDE_WHITELIST = "JGY_APPINSIDE_WHITELIST";
// public static final String JGY_APPINSIDE_FIRST_WRITE = "JGY_APPINSIDE_FIRST_WRITE";
@SuppressLint("NewApi")
synchronized private void setWhiteApp(List<TTAppground> appgrounds) {
//去重
List<TTAppground> ttAppgrounds = appgrounds.stream().distinct().collect(Collectors.toList());
List<TTAppground> old = getOldWhitelist();
comparedAppground(old, ttAppgrounds);
setWhiteList(ttAppgrounds);
}
synchronized private void comparedAppground(List<TTAppground> oldAppgrounds, List<TTAppground> newAppgrounds) {
List<TTAppground> addAppgrounds = new ArrayList<>();
List<TTAppground> deleteAppgrounds = new ArrayList<>();
List<TTAppground> changedAppgrounds = new ArrayList<>();
HashMap<String, TTAppground> oldAppgroundsMap = new HashMap<>();
HashMap<String, TTAppground> newAppgroundsMap = new HashMap<>();
for (TTAppground appground : oldAppgrounds) {
oldAppgroundsMap.put(appground.getPackages(), appground);
}
for (TTAppground appground : newAppgrounds) {
newAppgroundsMap.put(appground.getPackages(), appground);
}
for (TTAppground appground : oldAppgrounds) {
String packageName = appground.getPackages();
TTAppground mapground = newAppgroundsMap.get(packageName);
if (mapground == null) {
deleteAppgrounds.add(appground);
} else {
if (!appground.equals(mapground)) {
changedAppgrounds.add(mapground);
}
}
newAppgroundsMap.remove(packageName);
}
for (Map.Entry<String, TTAppground> entry : newAppgroundsMap.entrySet()) {
addAppgrounds.add(entry.getValue());
}
Log.e(TAG, "comparedAppground: addAppgrounds.size():" + addAppgrounds.size());
Log.e(TAG, "comparedAppground: deleteAppgrounds.size():" + deleteAppgrounds.size());
Log.e(TAG, "comparedAppground: changedAppgrounds.size():" + changedAppgrounds.size());
addAppground(addAppgrounds);
deleteAppground(deleteAppgrounds);
changeAppground(oldAppgroundsMap, changedAppgrounds);
Log.e(TAG, "comparedAppground: complete");
}
private void addAppground(List<TTAppground> appgroundList) {
for (TTAppground appground : appgroundList) {
addPackage(appground.getPackages());
//删除空的,旧版本使用这个清除
deleteWhitelistUrl(appground.getPackages(), "Invalid");
addToWhitelist(appground.getPackages(), appground.getAddress());
Log.e("comparedAppground", "addAppground: " + appground.getAddress());
}
}
private void deleteAppground(List<TTAppground> appgroundList) {
for (TTAppground appground : appgroundList) {
deleteWhitelistUrl(appground.getPackages(), appground.getAddress());
deleteOtherAppWhitelist(appground.getPackages());
Log.e("comparedAppground", "deleteAppground: " + appground.getAddress());
}
}
private void changeAppground(HashMap<String, TTAppground> oldAppgroundsMap, List<TTAppground> appgroundList) {
for (TTAppground appground : appgroundList) {
HashSet<String> newURL = new HashSet<>(Arrays.asList(appground.getAddress().split(",")));
TTAppground oldAppground = oldAppgroundsMap.get(appground.getPackages());
HashSet<String> oldURL = new HashSet<>(Arrays.asList(oldAppground.getAddress().split(",")));
for (String url : newURL) {
if (oldURL.contains(url)) {
oldURL.remove(url);
} else {
addToWhitelist(appground.getPackages(), url);
Log.e("comparedAppground", "addToWhitelist: " + url);
}
}
for (String url : oldURL) {
deleteWhitelistUrl(appground.getPackages(), url);
Log.e("comparedAppground", "deleteWhitelistUrl: " + url);
}
}
}
private List<TTAppground> getOldWhitelist() {
String whiteListString = (String) SPUtils.get(mContext, JGY_APPINSIDE_WHITELIST, "");
Log.e(TAG, "getOldWhitelist: " + whiteListString);
Gson gson = new Gson();
Type listType = new TypeToken<List<TTAppground>>() {
}.getType();
List<TTAppground> whiteList = gson.fromJson(whiteListString, listType);
if (whiteList == null) {
whiteList = new ArrayList<>();
}
//去重
whiteList.removeIf(new Predicate<TTAppground>() {
@Override
public boolean test(TTAppground ttAppground) {
return !ApkUtils.isAvailable(mContext, ttAppground.getPackages());
}
});
List<TTAppground> ttAppgrounds = whiteList.stream().distinct().collect(Collectors.toList());
return ttAppgrounds;
}
/**
* @param appgrounds 写入缓存
*/
private void setWhiteList(List<TTAppground> appgrounds) {
appgrounds.removeIf(new Predicate<TTAppground>() {
@Override
public boolean test(TTAppground ttAppground) {
return !ApkUtils.isAvailable(mContext, ttAppground.getPackages());
}
});
String data = new Gson().toJson(appgrounds);
SPUtils.put(mContext, JGY_APPINSIDE_WHITELIST, data);
}
public void onBootSetAppInsideWeb() {
List<TTAppground> old = getOldWhitelist();
Log.e(TAG, "onBootSetAppInsideWeb: " + old);
for (TTAppground appground : old) {
if (TextUtils.isEmpty(appground.getAddress())) {
Log.e(TAG, "setWhiteApp: " + "skip: " + appground.getAddress());
} else {
addPackage(appground.getPackages());
//删除空的,旧版本使用这个清除
addToWhitelist(appground.getPackages(), appground.getAddress());
deleteWhitelistUrl(appground.getPackages(), "Invalid");
}
}
}
/**
* @param pkg 开启app白名单
*/
synchronized private void addPackage(String pkg) {
Log.e(TAG, "addPackage: " + pkg);
Intent intent26 = new Intent();
intent26.setAction("qch_app_inside_website");
intent26.putExtra("WEBURLforbidapp", pkg);
intent26.setPackage("com.android.settings");
mContext.sendBroadcast(intent26);
}
/**
* @param pkg
* @param urls 添加app白名单
*/
synchronized private void addToWhitelist(String pkg, String urls) {
if (TextUtils.isEmpty(urls)) {
Log.e(TAG, "addToWhitelist: " + "urls is NULL");
return;
}
HashSet<String> urlSet = new HashSet<>(Arrays.asList(urls.trim().split(",")));
for (String url : urlSet) {
if (TextUtils.isEmpty(url)) {
continue;
}
deleteOtherAppWhitelist(pkg);
Log.e(TAG, "addToWhitelist: pkg:" + pkg + " url: " + url);
Intent intent25 = new Intent();
intent25.setAction("qch_app_setAddAppWhitWebUid");
intent25.putExtra("AddAppWhitWebUidPackage", pkg);
intent25.putExtra("AddAppWhitWebUid", url);
intent25.setPackage("com.android.settings");
mContext.sendBroadcast(intent25);
}
}
/**
* @param pkg
* @param urls 删除某个app 内某个白名单
*/
synchronized private void deleteWhitelistUrl(String pkg, String urls) {
if (TextUtils.isEmpty(urls)) {
Log.e(TAG, "addToWhitelist: " + "urls is NULL");
return;
}
HashSet<String> urlSet = new HashSet<>(Arrays.asList(urls.trim().split(",")));
for (String url : urlSet) {
if (TextUtils.isEmpty(url)) {
continue;
}
Log.e(TAG, "deleteWhitelistUrl: qch_app_setDelAppWhitWebUid" + "pkg: " + pkg + " url: " + url);
Intent intent25 = new Intent();
intent25.setAction("qch_app_setDelAppWhitWebUid");
intent25.putExtra("DelAppWhitWebUidPackage", pkg);
intent25.putExtra("DelAppWhitWebUid", url);
intent25.setPackage("com.android.settings");
mContext.sendBroadcast(intent25);
}
}
/**
* @param pkg 开启和关闭白名单管控都需要发送
*/
synchronized private void deleteOtherAppWhitelist(String pkg) {
Log.e(TAG, "disableAppWhitelist: " + pkg);
Intent intent24 = new Intent();
intent24.setAction("qch_app_setDelAppWhitUid");
intent24.putExtra("DelAppWhitUidPackage", pkg);
intent24.setPackage("com.android.settings");
mContext.sendBroadcast(intent24);
}
/**
* @param appgrounds 设置黑名单管控
*/
synchronized private void setBlackApp(List<TTAppground> appgrounds) {
Log.e(TAG, "setBlackApp: " + appgrounds);
StringBuilder blackList = new StringBuilder();
StringBuilder packageList = new StringBuilder();//单条管控名单
for (TTAppground appground : appgrounds) {
if (TextUtils.isEmpty(appground.getAddress())) {
if (packageList.length() > 0) {
packageList.append(",");
}
packageList.append(appground.getPackages());
} else {
if (blackList.length() > 0) {
blackList.append(";");
}
blackList.append(appground.toString());
}
}
//old
if (packageList.length() > 0) {
//app内所有的网页禁止
Log.e("setAppinsideWeb ", "packageList:" + packageList.toString());
Intent qch_app_website = new Intent("qch_app_website")
.setPackage("com.android.settings");
qch_app_website.putExtra("package_name", packageList.toString());
mContext.sendBroadcast(qch_app_website);
} else {
// sendAllweb(mContext);
}
if (blackList.length() > 0) {
//app内单个网页地址禁止打开
Log.e("setAppinsideWeb ", "blackList:" + blackList.toString());
Intent intent = new Intent("qch_app_inside_website")
.setPackage("com.android.settings");
intent.putExtra("websitelist", blackList.toString());
mContext.sendBroadcast(intent);
} else {
// sendwebUrl(mContext);
}
}
synchronized private static void sendAllweb(Context context) {
Log.e(TAG, "sendAllweb: ");
Intent intent = new Intent("qch_app_website")
.setPackage("com.android.settings");
intent.putExtra("package_name", "Invalid");
context.sendBroadcast(intent);
}
synchronized private static void sendwebUrl(Context context) {
Log.e(TAG, "sendwebUrl: ");
Intent intent = new Intent("qch_app_inside_website")
.setPackage("com.android.settings");
intent.putExtra("websitelist", "Invalid");
context.sendBroadcast(intent);
}
synchronized public void SettingSysData(String data) {
SPUtils.put(mContext, "SystemSettingData", data);
if (TextUtils.isEmpty(data)) {
Log.e(TAG, "SettingSysData: " + "data is empty");
SysSettingUtils.setDisableSetting(mContext);
SPUtils.put(mContext, JGYActions.ACTION_STATUSBAR_STATUS, "");
} else {
SysSettingUtils.setSystemSetting(mContext, data);
}
}
HashSet<String> defaultPackages = new HashSet<String>() {{
this.add(BuildConfig.APPLICATION_ID);
this.add(PackageNames.OLD_DEVICE_INFO);//设备信息
this.add(PackageNames.OLD_APPSTORE);//教管壹
this.add(PackageNames.DEVICE_INFO);
this.add(PackageNames.APPSTORE);
this.add("com.info.sn");
this.add("com.uiuios.jgy1");
this.add("com.uiuios.jgy2");
this.add("com.tt.ttutils");
this.add("com.aoleyun.browser");
this.add("com.uiui.browser");
this.add("com.android.uiuios");
this.add("com.aoleyun.os");
this.add("com.aoleyunos.dop1");
this.add("com.aoleyunos.dop2");
this.add("com.aoleyunos.dop3");
this.add("com.aoleyun.info");
this.add("com.calculator.uiui");
this.add("com.notepad.uiui");
this.add("com.calendar.uiui");
this.add("com.alarmclock.uiui");
this.add("com.uiui.videoplayer");
this.add("com.ygyb.yischool");
}};
@SuppressLint("NewApi")
public void writeAppPackageList(Context context, String packageList) {
ApkUtils.addShortcut(context);
HashSet<String> pkgSet = new HashSet<>(Arrays.asList(packageList.split(",")));
pkgSet.addAll(defaultPackages);
pkgSet.addAll(ApkUtils.desktopAPP);
pkgSet.addAll(ApkUtils.aoleyunAPP);
pkgSet.addAll(ApkUtils.aihuaApp);
pkgSet.addAll(ApkUtils.jxwApp);
pkgSet.removeIf(TextUtils::isEmpty);
if (JGYUtils.C2Tag.equalsIgnoreCase(JGYUtils.getInstance().getAppPlatform())) {
pkgSet.remove("com.tencent.mm");
}
String aole_app_forbid = String.join(",", pkgSet);
Log.e(TAG, "writeAppPackageList: " + aole_app_forbid);
boolean b = Settings.System.putString(crv, CommonConfig.AOLE_ACTION_APP_FORBID, aole_app_forbid);
setAppRestriction(2);
addAppInstallWhiteList(new ArrayList<>(pkgSet));
Log.e("writeAppPackageList: ", "aole_app_forbid: " + b + " " + Settings.System.getString(crv, CommonConfig.AOLE_ACTION_APP_FORBID));
}
public void writeAppPackageList() {
HashSet<String> pkgSet = new HashSet<>(defaultPackages);
pkgSet.addAll(ApkUtils.desktopAPP);
pkgSet.addAll(ApkUtils.aoleyunAPP);
pkgSet.addAll(ApkUtils.aihuaApp);
pkgSet.addAll(ApkUtils.jxwApp);
if (JGYUtils.C2Tag.equalsIgnoreCase(JGYUtils.getInstance().getAppPlatform())) {
pkgSet.remove("com.tencent.mm");
}
String aole_app_forbid = String.join(",", pkgSet);
Log.e(TAG, "writeAppPackageList: " + aole_app_forbid);
Settings.System.putString(crv, CommonConfig.AOLE_ACTION_APP_FORBID, aole_app_forbid);
}
public void checkForceDownload() {
String jsonString = cacheHelper.getAsString(UrlAddress.GET_FORCE_INSTALL_LIST);
//为 "" 是已经请求成功的
if (jsonString == null) {
NetInterfaceManager.getInstance().getForceDownload();
} else {
Gson gson = new Gson();
Type listType = new TypeToken<List<ForceDownloadData>>() {
}.getType();
List<ForceDownloadData> forceDownloadData = gson.fromJson(jsonString, listType);
if (forceDownloadData != null) {
JGYUtils.getInstance().forceDownload(forceDownloadData);
}
}
}
public void forceDownload(List<ForceDownloadData> data) {
if (data == null || data.size() <= 0) {
return;
}
List<String> list = new ArrayList<>();
for (int i = 0; i < data.size(); i++) {
ForceDownloadData forceDownloadData = data.get(i);
String app_name = forceDownloadData.getApp_name();
String app_package = forceDownloadData.getApp_package();
String app_url = forceDownloadData.getApp_url();
String app_id = forceDownloadData.getApp_id();
String app_md5 = forceDownloadData.getApp_md5();
JsonObject jsonObject = new JsonObject();
jsonObject.addProperty("app_name", app_name);
jsonObject.addProperty("app_package", app_package);
jsonObject.addProperty("app_id", app_id);
jsonObject.addProperty("MD5", app_md5);
long app_version_code = forceDownloadData.getApp_version_code();
Log.e("fht ", "packageName=" + app_package + ",URL= " + app_url + ",app_version_code=" + app_version_code);
if (BuildConfig.APPLICATION_ID.equals(data.get(i).getApp_package())) {
continue;//为自身的跳过下载
}
if (!list.contains(app_package)) {
list.add(app_package);
}
PackageManager pm = mContext.getPackageManager();
PackageInfo packageInfo = null;
try {
packageInfo = pm.getPackageInfo(app_package, 0);
} catch (PackageManager.NameNotFoundException e) {
e.printStackTrace();
Log.e("fht", "forceDownload=" + e.getMessage());
}
if (packageInfo != null) {
long appVersionCode;
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.P) {
appVersionCode = packageInfo.getLongVersionCode();
} else {
appVersionCode = packageInfo.versionCode;
}
if (app_version_code > appVersionCode) {
Log.e("fht ", "download URL " + app_url);
Utils.ariaDownload(mContext, app_url, jsonObject);
}
} else {
Log.e("fht ", "download URL " + app_url);
Utils.ariaDownload(mContext, app_url, jsonObject);
}
}
}
/**
* @param jsonObject 安装应用
*/
public void installAPK(JsonObject jsonObject) {
String url = jsonObject.get("url").getAsString();
int versionCode = jsonObject.get("version_code").getAsInt();
String packageName = jsonObject.get("package").getAsString();
String app_name = jsonObject.get("app_name").getAsString();
String app_md5 = jsonObject.get("app_md5").getAsString();
// String app_id = jsonObject.get("app_id").getAsString();
JsonObject object = new JsonObject();
object.addProperty("app_name", app_name);
object.addProperty("app_package", packageName);
object.addProperty("MD5", app_md5);
// object.put("app_id", app_id);
PackageManager pm = mContext.getPackageManager();
PackageInfo packageInfo = null;
try {
packageInfo = pm.getPackageInfo(packageName, 0);
} catch (PackageManager.NameNotFoundException e) {
e.printStackTrace();
}
if (packageInfo == null || packageInfo.versionCode < versionCode) {
Utils.ariaDownload(mContext, url, object);
} else {
Log.e("installAPK", app_name + ": 已是最新版本");
}
}
/**
* @param jsonObject
*/
public void installTestAPK(JsonObject jsonObject) {
String url = jsonObject.get("app_url").getAsString();
int versionCode = jsonObject.get("app_version_code").getAsInt();
String packageName = jsonObject.get("app_package").getAsString();
String app_name = jsonObject.get("app_name").getAsString();
// String app_id = jsonObject.get("app_id").getAsString();
JsonObject object = new JsonObject();
object.addProperty("app_name", app_name);
object.addProperty("app_package", packageName);
// object.put("app_id", app_id);
PackageManager pm = mContext.getPackageManager();
PackageInfo packageInfo = null;
try {
packageInfo = pm.getPackageInfo(packageName, 0);
} catch (PackageManager.NameNotFoundException e) {
e.printStackTrace();
}
if (packageInfo == null || packageInfo.versionCode < versionCode) {
Utils.ariaDownload(mContext, url, object);
} else {
Log.e("installTestAPK", "TestAPK: " + "无更新");
}
}
/**
* 安装灰度测试app
*
* @param dataList
*/
public void installTestAPK(List<ForceDownloadData> dataList) {
for (ForceDownloadData data : dataList) {
String url = data.getApp_url();
long versionCode = data.getApp_version_code();
String packageName = data.getApp_package();
String app_name = data.getApp_name();
String app_md5 = data.getApp_md5();
// String app_id = jsonObject.get("app_id").getAsString();
JsonObject object = new JsonObject();
object.addProperty("app_name", app_name);
object.addProperty("app_package", packageName);
object.addProperty("MD5", app_md5);
// object.put("app_id", app_id);
PackageManager pm = mContext.getPackageManager();
PackageInfo packageInfo = null;
try {
packageInfo = pm.getPackageInfo(packageName, 0);
} catch (PackageManager.NameNotFoundException e) {
e.printStackTrace();
}
if (packageInfo == null || packageInfo.versionCode < versionCode) {
Utils.ariaDownload(mContext, url, object);
} else {
Log.e("installTestAPK", "TestAPK: " + packageName + "\t无更新");
}
}
}
public void installDesktop(JsonObject jsonObject) {
try {
String app_name = jsonObject.get("app_name").getAsString();
String app_url = jsonObject.get("app_url").getAsString();
String app_package = jsonObject.get("app_package").getAsString();
int app_version_code = jsonObject.get("app_version_code").getAsInt();
mMMKV.encode(CommonConfig.DEFAULT_DESKTOP_PACKAGE, app_package);
Set<String> desktop = new HashSet<>(ApkUtils.desktopAPP);
desktop.remove(app_package);
for (String s : desktop) {
ApkUtils.UninstallAPP(mContext, s);
}
PackageInfo info = null;
PackageManager packageManager = mContext.getPackageManager();
if (null != packageManager) {
try {
info = packageManager.getPackageInfo(app_package, 0);
} catch (PackageManager.NameNotFoundException e) {
e.printStackTrace();
Log.e("fht", "installDesktop: " + e.getMessage());
}
if (null != info) {
packageManager.setApplicationEnabledSetting(app_package, PackageManager.COMPONENT_ENABLED_STATE_DEFAULT, 0);
long versionCode;
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.P) {
versionCode = info.getLongVersionCode();
} else {
versionCode = info.versionCode;
}
if (app_version_code > versionCode) {
Utils.ariaDownload(mContext, app_url, jsonObject);
}
} else {
Utils.ariaDownload(mContext, app_url, jsonObject);
}
}
} catch (Exception e) {
Log.e(TAG, "installDesktop: " + e.getMessage());
}
}
//删除用户除了在应用市场的其他应用
public void deleteOtherApp() {
Log.e(TAG, "deleteOtherApp: " + Build.MODEL);
if ("K106".equalsIgnoreCase(Build.MODEL)
|| "G10".equalsIgnoreCase(Build.MODEL)
|| "G10P".equalsIgnoreCase(Build.MODEL)
|| "G10R".equalsIgnoreCase(Build.MODEL)
) {
return;
}
int locked = Settings.System.getInt(crv, JGYActions.ACTION_QCH_UNLOCK_IPAD, 0);
if (locked == 1) {
return;
}
int aihuaUnlock = Settings.System.getInt(mContext.getContentResolver(), CommonConfig.AIHUA_UNLOCK, 0);
if (aihuaUnlock == 1) {
return;
}
Log.e(TAG, "deleteOtherApp: " + "start");
String[] result_white = new String[]{};
String[] result_forbid = new String[]{};
//获取后台应用白名单
String only_jgy_shortcut_list = Settings.System.getString(crv, JGYActions.ACTION_JGY_SHORTCUTLIST);
if (!TextUtils.isEmpty(only_jgy_shortcut_list)) {
result_white = only_jgy_shortcut_list.split(",");
}
//获取可以被安装的包名
String aole_app_forbid = Settings.System.getString(crv, CommonConfig.AOLE_ACTION_APP_FORBID);
if (!TextUtils.isEmpty(aole_app_forbid)) {
result_forbid = aole_app_forbid.split(",");
}
Log.e("deleteOtherApp", "only_jgy_shortcut_list:" + only_jgy_shortcut_list);
Log.e("deleteOtherApp", "aole_app_forbid:" + aole_app_forbid);
List<String> resulWhitetList = new ArrayList<>(Arrays.asList(result_white));
List<String> resulForbidtList = new ArrayList<>(Arrays.asList(result_forbid));
resulWhitetList.addAll(resulForbidtList);
HashSet<String> allWhitePkg = new HashSet<>(resulWhitetList);
List<String> installedPackageList = ApkUtils.queryFilterAppInfo(mContext);
Log.e("deleteOtherApp", "installedPackageList:" + installedPackageList.toString());
if (allWhitePkg.size() > 0) {
for (final String packageName : installedPackageList) {
if (ApkUtils.isSystemApp(mContext, packageName)) {
Log.e("deleteOtherApp", "is systemApp:" + packageName);
continue;
}
if (ApkUtils.desktopAPP.contains(packageName)) {
continue;
}
if (ApkUtils.aoleyunAPP.contains(packageName)) {
continue;
}
if (ApkUtils.canremove_systemapp.contains(packageName)) {
continue;
}
if (ApkUtils.aihuaApp.contains(packageName)) {
continue;
}
if (ApkUtils.jxwApp.contains(packageName)) {
continue;
}
if (PackageNames.DEVICE_INFO.equals(packageName) || PackageNames.APPSTORE.equals(packageName)
) {
continue;
}
if (!allWhitePkg.contains(packageName)) {
ApkUtils.UninstallAPP(mContext, packageName);
Log.e("deleteOtherApp", "uninstall apkName:" + packageName);
}
}
}
Log.e(TAG, "deleteOtherApp: " + "end");
}
HashSet<String> showAppList = new HashSet<String>() {{
this.add("com.android.calendar");
this.add("com.android.calendar2");
this.add("com.android.contacts");
this.add("com.android.deskclock");
this.add("com.android.camera2");
this.add("com.android.camera");
this.add("com.mediatek.camera");
this.add("com.android.messaging");
this.add("com.android.music");
this.add("com.android.settings");
// this.add("org.chromium.browser");
this.add("com.android.calculator2");
this.add("com.android.dialer");
this.add("com.android.documentsui");
this.add("com.android.soundrecorder");
this.add("com.android.gallery3d");
this.add("com.sprd.sprdnote");
this.add("com.aoleyun.appstore");
this.add("com.aoleyun.info");
this.add("com.aoleyun.sn");
this.add("com.aoleyun.browser");
this.add("com.aoleyun.os");
this.add("com.aoleyunos.dop1");
this.add("com.aoleyunos.dop2");
this.add("com.aoleyunos.dop3");
//aihua
this.add("com.android.mms");
this.add("com.android.fmradio");
this.add("com.mediatek.filemanager");
this.add("com.teclast.update");
this.add("com.google.android.apps.nbu.files");
this.add("com.tencent.wework");
this.add("com.tencent.mm");
this.add("cn.wps.moffice_eng");
this.add("com.baidu.BaiduMap");
}};
/**
* 隐藏系统所有应用
* 除了设置,图库、视频、设置、文件管理器、通话、短信、日历、时钟、计算器
*/
public void hideSystemAPP() {
PackageManager pm = mContext.getPackageManager();
Intent filterIntent = new Intent(Intent.ACTION_MAIN, null);
//Intent.CATEGORY_LAUNCHER主要的过滤条件
filterIntent.addCategory(Intent.CATEGORY_LAUNCHER);
List<ResolveInfo> apps = pm.queryIntentActivities(filterIntent, 0);
for (ResolveInfo resolveInfo : apps) {
String pkg = resolveInfo.activityInfo.packageName;
Log.e(TAG, "hideSystemAPP: " + pkg);
if (ApkUtils.isSystemApp(mContext, pkg)) {
pm.setApplicationEnabledSetting(pkg, PackageManager.COMPONENT_ENABLED_STATE_DEFAULT, 0);
} else {
continue;
}
if (!showAppList.contains(pkg) && !ApkUtils.aihuaApp.contains(pkg)) {
pm.setApplicationEnabledSetting(pkg, PackageManager.COMPONENT_ENABLED_STATE_DISABLED, 0);
Log.e(TAG, "hideSystemAPP: " + "disable: " + pkg);
} else {
pm.setApplicationEnabledSetting(pkg, PackageManager.COMPONENT_ENABLED_STATE_DEFAULT, 0);
Log.e(TAG, "hideSystemAPP: " + "enable: " + pkg);
}
}
}
public void hideApp(String pkg) {
PackageManager pm = mContext.getPackageManager();
try {
pm.setApplicationEnabledSetting(pkg, PackageManager.COMPONENT_ENABLED_STATE_DISABLED, 0);
} catch (Exception e) {
Log.e(TAG, "hideApp: " + e.getMessage());
}
}
public void showApp(String pkg) {
PackageManager pm = mContext.getPackageManager();
try {
pm.setApplicationEnabledSetting(pkg, PackageManager.COMPONENT_ENABLED_STATE_DEFAULT, 0);
} catch (Exception e) {
Log.e(TAG, "hideApp: " + e.getMessage());
}
}
/**
* 从Manifest中获取meta-data值
* https://blog.csdn.net/yue_233/article/details/91453451
*
* @return
*/
public String getStringMetaData() {
ApplicationInfo appInfo = null;
try {
appInfo = mContext.getPackageManager().getApplicationInfo(mContext.getPackageName(), PackageManager.GET_META_DATA);
} catch (PackageManager.NameNotFoundException e) {
e.printStackTrace();
}
String value = appInfo.metaData.getString("CHANNEL_VALUE");
return value;
}
public void checkBootFile(String url, String MD5) {
String urlFileName = Utils.getFileNamefromURL(url);
File bootFile = new File(JGYUtils.getInstance().getDownLoadPath() + urlFileName);
Log.e(TAG, "checkBootFile: bootFile file path=" + bootFile.getAbsolutePath());
Log.e(TAG, "checkBootFile: bootFile exists=" + bootFile.exists() + " isFile=" + bootFile.isFile());
if (bootFile.exists() && bootFile.isFile()) {
String oldMd5 = FileUtils.getFileMD5ToString(bootFile);
if (!TextUtils.isEmpty(oldMd5) && oldMd5.equalsIgnoreCase(MD5)) {
Log.e(TAG, "checkBootFile: Bootanimation file exists");
setBootanimation(bootFile.getAbsolutePath());
} else {
JsonObject jsonObject = new JsonObject();
jsonObject.addProperty("MD5", MD5);
Utils.ariaDownload(mContext, url, jsonObject);
Log.e(TAG, "checkBootFile: " + "download file");
}
} else {
JsonObject jsonObject = new JsonObject();
jsonObject.addProperty("MD5", MD5);
jsonObject.addProperty("app_name", urlFileName);
Utils.ariaDownload(mContext, url, jsonObject);
}
}
private static final String BOOTANIMATION_PATH = "/data/local/qchmedia/bootanimation.zip";
@SuppressLint("NewApi")
public void setBootanimation(String filePath) {
File systemFile = new File(BOOTANIMATION_PATH);
if (!systemFile.exists()) {
systemFile.getParentFile().mkdirs();
File file = systemFile.getParentFile();
Log.e(TAG, "setBootanimation: " + file.getAbsolutePath());
try {
systemFile.createNewFile();
} catch (IOException e) {
e.printStackTrace();
Log.e("setBootanimation: ", "createNewFile: " + e.getMessage());
}
}
File newFile = new File(filePath);
if (systemFile.exists() && systemFile.isFile()) {
String systemMD5 = FileUtils.getFileMD5ToString(systemFile);
String newMD5 = FileUtils.getFileMD5ToString(newFile);
if (systemMD5.equals(newMD5)) {
Log.e(TAG, "setBootanimation: 文件一致");
} else {
Path path = Paths.get(newFile.getAbsolutePath());
try {
Files.copy(path, new FileOutputStream(systemFile));
Log.e(TAG, "setBootanimation: 设置新开机动画");
} catch (IOException e) {
Log.e(TAG, "setBootanimation: IOException: " + e.getMessage());
e.printStackTrace();
}
}
} else {
File file = new File(BOOTANIMATION_PATH);
Log.e(TAG, "setBootanimation: " + file.getParentFile().getAbsolutePath());
Log.e(TAG, "setBootanimation: " + "Is a directory = " + file.isDirectory());
if (!file.getParentFile().delete()) {
Log.e(TAG, "setBootanimation: " + "系统动画删除失败");
}
Path path = Paths.get(newFile.getAbsolutePath());
try {
Files.copy(path, new FileOutputStream(systemFile));
copy(systemFile.getAbsolutePath(), newFile.getAbsolutePath());
Log.e(TAG, "setBootanimation: 设置新开机动画");
} catch (IOException e) {
Log.e(TAG, "setBootanimation: IOException: " + e.getMessage());
e.printStackTrace();
}
}
}
public void removeBootanimation() {
File systemFile = new File(BOOTANIMATION_PATH);
if (systemFile.exists()) {
if (systemFile.delete()) {
Log.e(TAG, "removeBootanimation: delete: " + "ture");
} else {
Log.e(TAG, "removeBootanimation: delete: " + "false");
}
}
}
public void copy(String oldPath, String newPath) {
try {
int bytesum = 0;
int byteread = 0;
File oldfile = new File(oldPath);
if (oldfile.exists()) { //文件存在时
InputStream inStream = new FileInputStream(oldPath); //读入原文件
FileOutputStream fs = new FileOutputStream(newPath);
byte[] buffer = new byte[1444];
int length;
while ((byteread = inStream.read(buffer)) != -1) {
bytesum += byteread; //字节数文件大小
System.out.println(bytesum);
fs.write(buffer, 0, byteread);
}
inStream.close();
}
} catch (Exception e) {
Log.e(TAG, "setBootanimation: " + e.getMessage());
e.printStackTrace();
}
}
public void setDeveloperOptions(int state) {
Log.e(TAG, "getDeveloper: " + state);
if (!BuildConfig.DEBUG) {
Settings.System.putInt(crv, CommonConfig.AOLE_ACTION_DEVELOPER_OPTIONS, state);
if (JGYUtils.getInstance().checkAppPlatform() == JGYUtils.ZhanruiPlatform
|| JGYUtils.getInstance().checkAppPlatform() == JGYUtils.CubePlatform
|| JGYUtils.getInstance().checkAppPlatform() == JGYUtils.AH6016Platform
|| JGYUtils.getInstance().checkAppPlatform() == JGYUtils.ZR6016Platform
|| JGYUtils.getInstance().checkAppPlatform() == JGYUtils.HRAD13Platform
|| JGYUtils.getInstance().checkAppPlatform() == JGYUtils.G10PPlatform
|| JGYUtils.getInstance().checkAppPlatform() == JGYUtils.C2Platform
) {
Settings.Global.putInt(crv, Settings.Global.DEVELOPMENT_SETTINGS_ENABLED, state == 1 ? 0 : 1);
Settings.Global.putInt(crv, Settings.Global.ADB_ENABLED, state == 1 ? 0 : 1);
}
if (state == 1) {
Intent intent = new Intent();
intent.setAction("qch_developeroptions_close");
intent.setPackage("com.android.settings");
mContext.sendBroadcast(intent);
Log.e(TAG, "getDeveloper: " + "关闭开发者模式");
} else {
Log.e(TAG, "getDeveloper: " + "打开开发者模式");
// ToastUtil.show("打开开发者模式");
}
}
}
private String chromium_pkg = "org.chromium.browser";
public void hookWebView() {
int sdkInt = Build.VERSION.SDK_INT;
if (!ApkUtils.isAvailable(mContext, chromium_pkg)) {
return;
}
try {
Class<?> factoryClass = Class.forName("android.webkit.WebViewFactory");
Field field = factoryClass.getDeclaredField("sProviderInstance");
field.setAccessible(true);
Object sProviderInstance = field.get(null);
if (sProviderInstance != null) {
Log.i(TAG, "sProviderInstance isn't null");
return;
}
Method getProviderClassMethod;
if (sdkInt > 22) {
getProviderClassMethod = factoryClass.getDeclaredMethod("getProviderClass");
} else if (sdkInt == 22) {
getProviderClassMethod = factoryClass.getDeclaredMethod("getFactoryClass");
} else {
Log.i(TAG, "Don't need to Hook WebView");
return;
}
getProviderClassMethod.setAccessible(true);
Class<?> factoryProviderClass = (Class<?>) getProviderClassMethod.invoke(factoryClass);
Class<?> delegateClass = Class.forName("android.webkit.WebViewDelegate");
Constructor<?> delegateConstructor = delegateClass.getDeclaredConstructor();
delegateConstructor.setAccessible(true);
if (sdkInt < 26) {//低于Android O版本
Constructor<?> providerConstructor = factoryProviderClass.getConstructor(delegateClass);
if (providerConstructor != null) {
providerConstructor.setAccessible(true);
sProviderInstance = providerConstructor.newInstance(delegateConstructor.newInstance());
}
} else {
Field chromiumMethodName = factoryClass.getDeclaredField("CHROMIUM_WEBVIEW_FACTORY_METHOD");
chromiumMethodName.setAccessible(true);
String chromiumMethodNameStr = (String) chromiumMethodName.get(null);
if (chromiumMethodNameStr == null) {
chromiumMethodNameStr = "create";
}
Method staticFactory = factoryProviderClass.getMethod(chromiumMethodNameStr, delegateClass);
if (staticFactory != null) {
sProviderInstance = staticFactory.invoke(null, delegateConstructor.newInstance());
}
}
if (sProviderInstance != null) {
field.set("sProviderInstance", sProviderInstance);
Log.i(TAG, "Hook success!");
} else {
Log.i(TAG, "Hook failed!");
}
} catch (Throwable e) {
Log.w(TAG, "hookWebView: " + e.getMessage());
}
}
public void deleteScreenshots() {
Log.e("File", "deleteScreenshots");
String path = mContext.getExternalFilesDir("db").getAbsolutePath();
File file = new File(path);
File[] files = file.listFiles();
for (File f : files) {
if (f.isFile()) {
Log.e("File", f.getAbsolutePath());
f.delete();
}
}
}
public void killPackage(String pkg) {
ActivityManager manager = (ActivityManager) mContext.getSystemService(Context.ACTIVITY_SERVICE);
manager.killBackgroundProcesses(pkg);
CmdUtil.execute("am force-stop " + pkg);
}
public void KillOTA() {
ActivityManager manager = (ActivityManager) mContext.getSystemService(Context.ACTIVITY_SERVICE);
manager.killBackgroundProcesses("com.adups.fota");
CmdUtil.execute("am force-stop " + "com.adups.fota");
}
public void openOTA() {
Intent intent = new Intent(Intent.ACTION_MAIN);
/**知道要跳转应用的包命与目标Activity*/
ComponentName componentName = new ComponentName("com.adups.fota", "com.adups.fota.GoogleOtaClient");
intent.setComponent(componentName);
mContext.startActivity(intent);
}
public void openLauncher() {
Log.e(TAG, "openLauncher: ");
killPackage("com.android.launcher3");
Intent intent = new Intent();
// 为Intent设置Action、Category属性
intent.setAction(Intent.ACTION_MAIN);// "android.intent.action.MAIN"
intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
intent.addCategory(Intent.CATEGORY_HOME); //"android.intent.category.HOME"
mContext.startActivity(intent);
}
public void cleanLauncherCache() {
Log.e(TAG, "cleanLauncherCache: Start");
int cleaned = (int) SPUtils.get(mContext, "fristcleanLauncherCache", 0);
if (cleaned == 0) {
try {
new CacheUtils().cleanApplicationUserData(mContext, "com.android.launcher3");
SPUtils.put(mContext, "fristcleanLauncherCache", 1);
Log.e(TAG, "cleanLauncherCache: end");
} catch (Exception e) {
e.printStackTrace();
Log.e(TAG, "cleanLauncherCache: " + e.getMessage());
}
}
}
@RequiresApi(api = Build.VERSION_CODES.M)
public void cleanBackgroundMemory() {
ActivityManager manager = (ActivityManager) mContext.getSystemService(Context.ACTIVITY_SERVICE);
for (ActivityManager.RunningServiceInfo service : manager.getRunningServices(Integer.MAX_VALUE)) {
String pkg = service.service.getPackageName();
Log.i("cleanBackgroundMemory", pkg);
if (ApkUtils.isSystemApp(mContext, pkg)) continue;
if (ApkUtils.desktopAPP.contains(pkg) || ApkUtils.aoleyunAPP.contains(pkg)) {
continue;
}
manager.forceStopPackage(service.service.getPackageName());
Log.e("cleanBackgroundMemory", "kill :" + pkg);
}
}
public void killBackgroundProcesses(String processName) {
gotoLauncher();
// mIsScanning = true;
removeTask(processName);
ActivityManager activityManager = (ActivityManager) mContext.getSystemService(Context.ACTIVITY_SERVICE);
String packageName = null;
try {
if (processName.indexOf(":") == -1) {
packageName = processName;
} else {
packageName = processName.split(":")[0];
}
activityManager.killBackgroundProcesses(packageName);
//
Method forceStopPackage = activityManager.getClass()
.getDeclaredMethod("forceStopPackage", String.class);
forceStopPackage.setAccessible(true);
forceStopPackage.invoke(activityManager, packageName);
} catch (Exception e) {
e.printStackTrace();
}
}
/**
* 清除所有最近记录
*/
// public void removeAllTask() {
// List<ActivityManager.RecentTaskInfo> list = getRecentTasks(ActivityManager.getMaxRecentTasksStatic(), getCurrentUserId());
//
// for (ActivityManager.RecentTaskInfo info : list) {
// if (info.realActivity != null) {
// Log.e(TAG, "removeAllTask: " + info.realActivity.getPackageName());
// //排除自身
// if (BuildConfig.APPLICATION_ID.equals(info.realActivity.getPackageName())) {
// continue;
// }
// }
// try {
// ActivityManagerNative.getDefault().removeTask(info.id);
// } catch (RemoteException e) {
// e.printStackTrace();
// Log.e(TAG, "removeAllTask: " + e.getMessage());
// }
// }
// }
public void removeAllTask() {
List<ActivityManager.RecentTaskInfo> list = getRecentTasks(ActivityManager.getMaxRecentTasksStatic(), getCurrentUserId());
for (ActivityManager.RecentTaskInfo info : list) {
try {
ActivityManagerNative.getDefault().removeTask(info.id);
Log.e(TAG, "removeAllTask: " + info.id);
} catch (RemoteException e) {
e.printStackTrace();
Log.e(TAG, "removeTask: " + e.getMessage());
} catch (NullPointerException e) {
Log.e(TAG, "removeTask: " + e.getMessage());
}
}
}
public void removeTask(String packageName) {
if (Build.VERSION.SDK_INT > Build.VERSION_CODES.P) {
List<ActivityManager.RecentTaskInfo> list = getRecentTasks(ActivityManager.getMaxRecentTasksStatic(), getCurrentUserId());
HashMap<String, Integer> taskMap = new HashMap<>();
for (ActivityManager.RecentTaskInfo info : list) {
taskMap.put(info.realActivity.getPackageName(), info.id);
}
try {
ActivityManagerNative.getDefault().removeTask(taskMap.get(packageName));
} catch (RemoteException e) {
e.printStackTrace();
Log.e(TAG, "removeTask: " + e.getMessage());
} catch (NullPointerException e) {
Log.e(TAG, "removeTask: " + e.getMessage());
}
} else {
ActivityManager activityManager = (ActivityManager) mContext.getSystemService(Context.ACTIVITY_SERVICE);
// TODO: 2022/10/25
}
}
/**
* 如果界面正在最近任务列表有些app可能不会被清理
*/
private void gotoLauncher() {
Intent i = new Intent(Intent.ACTION_MAIN);
i.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK); //android123提示如果是服务里调用必须加入new task标识
i.addCategory(Intent.CATEGORY_HOME);
mContext.startActivity(i);
}
/**
* @return a list of the recents tasks.
* 获取近期任务列表
*/
public List<ActivityManager.RecentTaskInfo> getRecentTasks(int numTasks, int userId) {
try {
return ActivityTaskManager.getService().getRecentTasks(numTasks,
RECENT_IGNORE_UNAVAILABLE, userId).getList();
} catch (RemoteException e) {
Log.e(TAG, "Failed to get recent tasks " + e);
return new ArrayList<>();
}
}
/**
* @return the current user's id.
* 获取userId
*/
public int getCurrentUserId() {
UserInfo ui;
try {
ui = ActivityManager.getService().getCurrentUser();
return ui != null ? ui.id : 0;
} catch (RemoteException e) {
throw e.rethrowFromSystemServer();
}
}
public static String getPrefixHttpURL(String url) {
if (url.startsWith("http://")) {
return url;
} else if (url.startsWith("https://")) {
return url.replace("https://", "http://");
} else {
return "http://" + url;
}
}
public static String getPrefixHttpsURL(String url) {
if (url.startsWith("https://")) {
return url;
} else if (url.startsWith("http://")) {
return url.replace("http://", "https://");
} else {
return "https://" + url;
}
}
public Bitmap createQRImage(String content, int widthPix, int heightPix) {
try {
// if (content == null || "".equals(content)) {
// return false;
// }
//配置参数
Map<EncodeHintType, Object> hints = new HashMap<>();
hints.put(EncodeHintType.CHARACTER_SET, "utf-8");
//容错级别
hints.put(EncodeHintType.ERROR_CORRECTION, ErrorCorrectionLevel.H);
//设置空白边距的宽度
hints.put(EncodeHintType.MARGIN, 1); //default is 4
// 图像数据转换,使用了矩阵转换
BitMatrix bitMatrix = null;
try {
bitMatrix = new QRCodeWriter().encode(content, BarcodeFormat.QR_CODE, widthPix,
heightPix, hints);
} catch (WriterException e) {
e.printStackTrace();
}
int[] pixels = new int[widthPix * heightPix];
// 下面这里按照二维码的算法,逐个生成二维码的图片,
// 两个for循环是图片横列扫描的结果
for (int y = 0; y < heightPix; y++) {
for (int x = 0; x < widthPix; x++) {
if (bitMatrix.get(x, y)) {
pixels[y * widthPix + x] = 0xff000000;
} else {
pixels[y * widthPix + x] = 0xffffffff;
}
}
}
// 生成二维码图片的格式使用ARGB_8888
Bitmap bitmap = Bitmap.createBitmap(widthPix, heightPix, Bitmap.Config.ARGB_8888);
bitmap.setPixels(pixels, 0, widthPix, 0, 0, widthPix, heightPix);
//
// if (logoBm != null) {
// bitmap = addLogo(bitmap, logoBm);
// }
//必须使用compress方法将bitmap保存到文件中再进行读取。直接返回的bitmap是没有任何压缩的
// 内存消耗巨大!
return bitmap;
// return bitmap != null && bitmap.compress(Bitmap.CompressFormat.JPEG, 100);
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
public String getIPAddress() {
ConnectivityManager mConnectivityManager = (ConnectivityManager) mContext.getSystemService(Context.CONNECTIVITY_SERVICE);//获取系统的连接服务
NetworkInfo info = mConnectivityManager.getActiveNetworkInfo();
if (info != null && info.isConnected()) {
if ((info.getType() == ConnectivityManager.TYPE_MOBILE) || (info.getType() == ConnectivityManager.TYPE_WIFI)) {//当前使用2G/3G/4G网络
try {
for (Enumeration<NetworkInterface> en = NetworkInterface.getNetworkInterfaces(); en.hasMoreElements(); ) {
NetworkInterface intf = en.nextElement();
for (Enumeration<InetAddress> enumIpAddr = intf.getInetAddresses(); enumIpAddr.hasMoreElements(); ) {
InetAddress inetAddress = enumIpAddr.nextElement();
if (!inetAddress.isLoopbackAddress() && inetAddress instanceof Inet4Address) {
return inetAddress.getHostAddress();
}
}
}
} catch (SocketException e) {
e.printStackTrace();
}
}
} else { //当前无网络连接,请在设置中打开网络
return "未连接到网络";
}
return "未获取到IP";
}
private static long lastTime;
public static void startServices(Context context) {
Log.e(TAG, "startServices: " + context.getClass().getSimpleName());
if (System.currentTimeMillis() - lastTime < 10 * 60 * 1000) {
Log.e(TAG, "startServices: " + "lastTime: " + lastTime);
} else {
lastTime = System.currentTimeMillis();
context.startService(new Intent(context, MainService.class));
context.startService(new Intent(context, StepService.class));
context.startService(new Intent(context, GuardService.class));
context.startService(new Intent(context, LogcatService.class));
}
}
private String Launcher3 = "com.android.launcher3";
private String Launcher3Class = "com.android.launcher3.Launcher";
private String AoleyunOs = "com.aoleyun.os";
private String AoleyunOsClass = "com.aoleyun.os.Launcher";
public void setDefaultLauncher(Context context, String defPackageName, String defClassName) {
try {
if (!TextUtils.isEmpty(defPackageName) && !TextUtils.isEmpty(defClassName)) {
IntentFilter filter = new IntentFilter();
filter.addAction("android.intent.action.MAIN");
filter.addCategory("android.intent.category.HOME");
filter.addCategory("android.intent.category.DEFAULT");
Intent intent = new Intent(Intent.ACTION_MAIN);
intent.addCategory(Intent.CATEGORY_HOME);
// 返回给定条件的所有ResolveInfo对象(本质上是Activity)
List<ResolveInfo> list = context.getPackageManager().queryIntentActivities(intent, PackageManager.MATCH_DEFAULT_ONLY);
int bestMatch = 0;
final int size = list.size();
ComponentName[] set = new ComponentName[size];
for (int i = 0; i < size; i++) {
ResolveInfo ri = list.get(i);
set[i] = new ComponentName(ri.activityInfo.packageName, ri.activityInfo.name);
if (ri.match > bestMatch) {
bestMatch = ri.match;
}
}
ComponentName preActivity = new ComponentName(defPackageName, defClassName);
context.getPackageManager().addPreferredActivity(filter, bestMatch, set, preActivity);
}
} catch (java.lang.SecurityException e) {
e.printStackTrace();
Log.e(TAG, "setDefaultLauncher: " + e.getMessage());
}
}
public void setRoleHolderAsUser(Context context, String packageName) {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.Q) {
String roleName = "android.app.role.HOME";
boolean add = true;
int flags = 0;
UserHandle user = Process.myUserHandle();
Log.i("settingssssssstemf", (add ? "Adding" : "Removing") + " package as role holder, role: "
+ roleName + ", package: " + packageName);
if (JGYUtils.getInstance().checkAppPlatform() != JGYUtils.MTKPlatform) {
RoleManager roleManager = context.getSystemService(RoleManager.class);
Executor executor = context.getMainExecutor();
Consumer<Boolean> callback = successful -> {
if (successful) {
Log.d("settingssssssstemf", "Package " + (add ? "added" : "removed")
+ " as role holder, role: " + roleName + ", package: " + packageName);
} else {
Log.d("settingssssssstemf", "Failed to " + (add ? "add" : "remove")
+ " package as role holder, role: " + roleName + ", package: "
+ packageName);
}
};
roleManager.addRoleHolderAsUser(roleName, packageName, flags, user, executor, callback);
Log.i("settingssssssstemf", "addRoleHolderAsUser done");
}
}
}
public void checkDefaultDesktop(String pkg) {
String desktopPkg = (String) SPUtils.get(mContext, "default_launcher", "");
Log.e(TAG, "checkDefaultDesktop: " + desktopPkg);
if (desktopPkg.equalsIgnoreCase(pkg)) {
setDefaultDesktop(pkg);
}
}
/**
* 设置奥乐云桌面为默认
*/
public void setDefaultDesktop() {
setDefaultDesktop(PackageNames.DESKTOP);
}
public void setYxpDefaultDesktop() {
setDefaultDesktop(PackageNames.YIXUEPAI_DESKTOP);
}
/**
* 设置默认桌面
*
* @param pkg
*/
public void setDefaultDesktop(String pkg) {
Log.e(TAG, "setDefaultDesktop: " + pkg);
if (TextUtils.isEmpty(pkg)) {
openLauncher3();
} else {
String className = getStartClassName(pkg);
if (TextUtils.isEmpty(className)) {
openLauncher3();
} else {
setDefaultDesktop(pkg, className);
}
}
}
public void setJxwLauncher(String pkg) {
Log.e(TAG, "setDefaultDesktop: " + pkg);
String className = getStartClassName(pkg);
if (TextUtils.isEmpty(className)) {
Log.e(TAG, "setJxwLauncher: empty");
} else {
setDefaultDesktop(pkg, className);
}
}
private void openLauncher3() {
// ApkUtils.openPackage(mContext, Launcher3);
if ("C2".equals(Build.MODEL)) {
setDefaultDesktop(AoleyunOs, AoleyunOsClass);
} else {
setDefaultDesktop(Launcher3, Launcher3Class);
}
}
public String getStartClassName(String pkg) {
PackageInfo packageInfo = null;
try {
packageInfo = mContext.getPackageManager().getPackageInfo(pkg, 0);
} catch (PackageManager.NameNotFoundException e) {
e.printStackTrace();
}
if (packageInfo == null) {
return "";
} else {
// 创建一个类别为CATEGORY_LAUNCHER的该包名的Intent
Intent resolveIntent = new Intent(Intent.ACTION_MAIN, null);
resolveIntent.addCategory(Intent.CATEGORY_LAUNCHER);
resolveIntent.setPackage(packageInfo.packageName);
// 通过getPackageManager()的queryIntentActivities方法遍历
List<ResolveInfo> resolveinfoList = mContext.getPackageManager()
.queryIntentActivities(resolveIntent, 0);
if (resolveinfoList == null || resolveinfoList.size() == 0) {
return "";
}
ResolveInfo resolveinfo = resolveinfoList.iterator().next();
if (resolveinfo != null) {
// packagename = 参数packname
String packageName = resolveinfo.activityInfo.packageName;
// 这个就是我们要找的该APP的LAUNCHER的Activity[组织形式packagename.mainActivityname]
String className = resolveinfo.activityInfo.name;
return className;
} else {
return "";
}
}
}
public void setDefaultDesktop(String pkg, String className) {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.Q) {
setRoleHolderAsUser(mContext, pkg);
Log.e(TAG, "setDefaultDesktop: setRoleHolderAsUser");
} else {
//爱华设置,暂时屏蔽
// setDefaultLauncher(mContext, pkg, className);
Log.e(TAG, "setDefaultDesktop: setDefaultLauncher: " + pkg);
}
// String oldDesktop = (String) SPUtils.get(mContext, "default_launcher", "");
// if (Objects.equals(oldDesktop, pkg)) {
// Log.e(TAG, "setDefaultDesktop: " + "数据一致");
// return;
// }
Intent intent = new Intent("setDefaultLauncher");
intent.putExtra("package", pkg);
intent.putExtra("className", className);
// if (JGYUtils.getInstance().checkAppPlatform() == MTKPlatform) {
// Log.e(TAG, "setDefaultDesktop: MTK");
// //爱华定制
// intent.setComponent(new ComponentName("com.android.settings", "com.android.settings.AoleReceiver"));
// // TODO: 2022/7/6 MTK有问题
// setDefaultLauncher(mContext, "com.android.transfer", "com.android.transfer.MainActivity");
// SystemProperties.set("persist.sys.launcher.pkgname", pkg);
// SystemProperties.set("persist.sys.launcher.classname", className);
// }
intent.setPackage("com.android.settings");
mContext.sendBroadcast(intent);
// ApkUtils.openPackage(mContext, pkg);
Log.e(TAG, "setDefaultDesktop: " + pkg + ":" + className);
Log.e(TAG, "setDefaultDesktop: " + "persist.sys.launcher.pkgname = " + SystemProperties.get("persist.sys.launcher.pkgname"));
Log.e(TAG, "setDefaultDesktop: " + "persist.sys.launcher.classname = " + SystemProperties.get("persist.sys.launcher.classname"));
setDefaultLauncher(new ComponentName(pkg, className));
}
public String getMacJson(Context context) {
JsonObject jsonObject = new JsonObject();
jsonObject.addProperty("sn", Utils.getSerial(context));
jsonObject.addProperty("mac", Utils.getAndroid10MAC(mContext));
jsonObject.addProperty("jpush_id", "0000");
jsonObject.addProperty("devices_version", Utils.getCustomVersion());
jsonObject.addProperty("appstore_version", BuildConfig.VERSION_NAME);
jsonObject.addProperty("store_version", Utils.getAPPVersionName(PackageNames.APPSTORE, mContext));
jsonObject.addProperty("desktop_version", Utils.getAPPVersionName("com.aoleyun.os", mContext));
jsonObject.addProperty("local_mac", Utils.getAndroid7MAC());
// jsonObject.addProperty("wifi_status", Utils.obtainWifiInfo(mContext));
jsonObject.addProperty("PN_ip", mMMKV.decodeString(NetInterfaceManager.PublicIP, ""));
jsonObject.addProperty("LAN_ip", Utils.getIPAddress(mContext));
jsonObject.addProperty("bluetooth", Utils.getBluetoothList());
jsonObject.addProperty("wifi_name", Utils.getWifiAlias(mContext));
jsonObject.addProperty("platform", JGYUtils.getInstance().getAppPlatform());
return jsonObject.toString();
}
public void shutdown() {
if (ActivityManagerNative.isSystemReady()) {
Intent intent = new Intent(Intent.ACTION_REQUEST_SHUTDOWN);
intent.putExtra(Intent.EXTRA_KEY_CONFIRM, false);
intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
mContext.startActivity(intent);
}
}
/**
* 判断网络连接状态
*
* @return true网络已链接 false网络已断开连接
*/
public boolean isNetworkConnected() {
if (mContext != null) {
ConnectivityManager mConnectivityManager = (ConnectivityManager) mContext
.getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo mNetworkInfo = mConnectivityManager
.getActiveNetworkInfo();
if (mNetworkInfo != null) {
return mNetworkInfo.isAvailable();
}
}
return false;
}
public void cleanLauncher3Cache() {
try {
new CacheUtils().cleanApplicationUserData(mContext, "com.android.launcher3");
} catch (Exception e) {
Log.e(TAG, "onReceive: " + e.getMessage());
e.printStackTrace();
}
}
public void cleanAoleLauncher3Cache() {
try {
new CacheUtils().cleanApplicationUserData(mContext, "com.aoleyun.os");
} catch (Exception e) {
Log.e(TAG, "cleanAoleLauncher3Cache: " + e.getMessage());
e.printStackTrace();
}
}
public void cleanAoleAppCache() {
try {
new CacheUtils().cleanApplicationUserData(mContext, "com.aoleyun.os");
new CacheUtils().cleanApplicationUserData(mContext, "com.aoleyun.appstore");
new CacheUtils().cleanApplicationUserData(mContext, "com.aoleyun.info");
new CacheUtils().cleanApplicationUserData(mContext, "com.aoleyun.browser");
} catch (Exception e) {
Log.e(TAG, "cleanAoleAppCache: " + e.getMessage());
e.printStackTrace();
}
}
public List<String> getHidePackage() {
String jsonString = cacheHelper.getAsString(UrlAddress.GET_HIDE_DESKTOPICON);
//为 "" 是已经请求成功的
if (jsonString == null) {
return new ArrayList<>();
} else {
Gson gson = new Gson();
Type type = new TypeToken<List<String>>() {
}.getType();
List<String> list = gson.fromJson(jsonString, type);
if (list == null) {
return new ArrayList<>();
} else {
return list;
}
}
}
public List<String> getDisablePackage() {
List<String> list = new ArrayList<>();
if (Settings.System.getInt(crv, "qch_app_camera", 0) == 1) {
list.add("com.mediatek.camera");
list.add("com.android.camera");
list.add("com.android.camera2");
}
if (Settings.System.getInt(crv, "qch_call_forbid", 0) == 1) {
list.add("com.android.dialer");
}
if (Settings.System.getInt(crv, "qch_app_deskclock", 0) == 1) {
list.add("com.android.deskclock");
}
if (Settings.System.getInt(crv, "qch_app_soundrecorder", 0) == 1) {
list.add("com.android.soundrecorder");
}
if (Settings.System.getInt(crv, "qch_app_music", 0) == 1) {
list.add("com.android.music");
}
if (Settings.System.getInt(crv, "qch_app_gallery", 0) == 1) {
list.add("com.android.gallery3d");
}
if (Settings.System.getInt(crv, "qch_app_filemanager", 0) == 1) {
list.add("com.mediatek.filemanager");
list.add("com.android.documentsui");
}
if (Settings.System.getInt(crv, "qch_app_browser", 0) == 1) {
list.add("com.android.browser");
list.add("com.aoleyun.browser");
}
return list;
}
public boolean isForbid(String pkg) {
switch (pkg) {
case "com.mediatek.camera":
case "com.android.camera2":
if (Settings.System.getInt(crv, "qch_app_camera", 0) == 1) {
ToastUtil.show("摄像头已禁止使用");
return false;
}
break;
case "com.android.dialer":
if (Settings.System.getInt(crv, "qch_call_forbid", 0) == 1) {
ToastUtil.show("电话已禁止使用");
return false;
}
break;
case "com.android.gallery3d":
if (Settings.System.getInt(crv, "qch_app_gallery", 1) == 1) {
ToastUtil.show("图库已禁止使用");
return false;
}
break;
case "com.android.documentsui":
if (Settings.System.getInt(crv, "qch_app_filemanager", 1) == 1) {
ToastUtil.show("文件已禁止使用");
return false;
}
break;
case "com.android.deskclock":
if (Settings.System.getInt(crv, "qch_app_deskclock", 0) == 1) {
ToastUtil.show("时钟已禁止使用");
return false;
}
break;
case "com.android.music":
if (Settings.System.getInt(crv, "qch_app_music", 1) == 1) {
ToastUtil.show("音乐已禁止使用");
return false;
}
break;
case "com.android.soundrecorder":
if (Settings.System.getInt(crv, "qch_app_soundrecorder", 1) == 1) {
ToastUtil.show("录音机已禁止使用");
return false;
}
break;
case "com.aoleyun.browser":
case "com.android.browser":
if (Settings.System.getInt(crv, "qch_app_browser", 1) == 1) {
ToastUtil.show("浏览器已禁止使用");
return false;
}
break;
case "com.android.messaging":
case "com.android.mms":
if (Settings.System.getInt(crv, "qch_app_sms", 1) == 1) {
ToastUtil.show("短信已禁止使用");
return false;
}
break;
default:
return true;
}
return true;
}
public static final String PACKAGE_DEVICEINFO = "com.aoleyun.sn";
public static final String CLASS_DEVICEINFO = "com.aoleyun.sn.receiver.BootReceiver";
public void wakeUpDeviceInfo() {
Log.e(TAG, "wakeUpDeviceInfo: ");
//启动设备信息
Intent bootIntent = new Intent(BootReceiver.BOOT_COMPLETED);
bootIntent.setComponent(new ComponentName(PACKAGE_DEVICEINFO, CLASS_DEVICEINFO));
mContext.sendBroadcast(bootIntent);
}
public static final String PACKAGE_APPSTORE = "com.aoleyun.appstore";
public static final String CLASS_APPSTORE = "com.aoleyun.appstore.receiver.BootReceiver";
public void wakeUpAppstore() {
Log.e(TAG, "wakeUpAppstore: ");
//启动应用市场
Intent bootIntent = new Intent(BootReceiver.BOOT_COMPLETED);
bootIntent.setComponent(new ComponentName(PACKAGE_APPSTORE, CLASS_APPSTORE));
mContext.sendBroadcast(bootIntent);
}
public static final String PACKAGE_NOTIFY = "com.aoleyun.info";
public static final String CLASS_NOTIFY = "com.aoleyun.info.receiver.BootReceiver";
public void wakeUpNotify() {
Log.e(TAG, "wakeUpNotify: ");
//启动通知
Intent bootIntent = new Intent(BootReceiver.BOOT_COMPLETED);
bootIntent.setComponent(new ComponentName(PACKAGE_NOTIFY, CLASS_NOTIFY));
mContext.sendBroadcast(bootIntent);
}
public void wakeUpAoleyunAPP() {
wakeUpAppstore();
wakeUpNotify();
}
public static String getModel() {
Log.e(TAG, "MANUFACTURER=" + Build.MANUFACTURER);
Log.e(TAG, "BRAND=" + Build.BRAND);
Log.e(TAG, "MODEL=" + Build.MODEL);
Log.e(TAG, "VERSION.RELEASE=" + Build.VERSION.RELEASE);
Log.e(TAG, "VERSION.SDK_INT=" + Build.VERSION.SDK_INT);
Log.e(TAG, "DEVICE=" + Build.DEVICE);
Log.e(TAG, "HOST=" + Build.HOST);
Log.e(TAG, "ID=" + Build.ID);
Log.e(TAG, "TIME=" + Build.TIME);
Log.e(TAG, "TYPE=" + Build.TYPE);
Log.e(TAG, "PRODUCT=" + Build.PRODUCT);
Log.e(TAG, "BOARD=" + Build.BOARD);
Log.e(TAG, "DISPLAY=" + Build.DISPLAY);
Log.e(TAG, "FINGERPRINT=" + Build.FINGERPRINT);
Log.e(TAG, "HARDWARE=" + Build.HARDWARE);
Log.e(TAG, "BOOTLOADER=" + Build.BOOTLOADER);
Log.e(TAG, "TAGS=" + Build.TAGS);
Log.e(TAG, "UNKNOWN=" + Build.UNKNOWN);
Log.e(TAG, "USER=" + Build.USER);
return Build.MODEL;
}
private static String MTK_HARDWARE = "mtk";
private static String UNISOC_HARDWARE = "ums";
private static String AIHUA_BRAND = "AS";
private static String CUBE_BRAND = "ALLDOCUBE";
public static String getHardware() {
return Build.HARDWARE;
}
public boolean isAihuaFramwwork() {
return (Utils.getProperty("ro.build.display.id", "获取失败").contains("_aihua"));
}
public static boolean isAihuaDevice() {
return getHardware().startsWith(MTK_HARDWARE) && Build.BRAND.startsWith(AIHUA_BRAND);
}
public static boolean isCubeDevice() {
return getHardware().startsWith(UNISOC_HARDWARE) && Build.BRAND.equalsIgnoreCase(CUBE_BRAND);
}
public boolean isScreenOn() {
PowerManager powerManager = (PowerManager) mContext.getSystemService(Context.POWER_SERVICE);
//true为打开false为关闭
return powerManager.isInteractive();
}
private static final String CONNECTED_TIME_KEY = "connectedTimeKey";
private List<Long> connectedTime;
private void initConnectedTimeCache() {
String jsonString = cacheHelper.getAsString(CONNECTED_TIME_KEY);
Gson gson = new Gson();
Type listType = new TypeToken<List<Long>>() {
}.getType();
List<Long> longList = gson.fromJson(jsonString, listType);
if (longList == null) {
connectedTime = new ArrayList<>();
} else {
connectedTime = longList;
}
}
public List<Long> getNetworkConnectedTime() {
Log.e(TAG, "getNetworkConnectedTime: " + connectedTime);
return connectedTime;
}
public void addNetworkConnectedTime(Long time) {
Log.e(TAG, "addNetworkConnectedTime: " + time);
connectedTime.add(time);
cacheHelper.put(CONNECTED_TIME_KEY, GsonUtils.toJSONString(connectedTime));
}
public void removeNetworkConnectedTime(List<Long> time) {
if (time == null || time.size() == 0) {
return;
}
List<Long> copy = new ArrayList<>(time);
for (Long l : copy) {
connectedTime.remove(l);
}
cacheHelper.put(CONNECTED_TIME_KEY, GsonUtils.toJSONString(connectedTime));
}
public void installAdminApp(List<AdminAppInfo> adminAppInfos) {
for (AdminAppInfo adminAppInfo : adminAppInfos) {
String app_name = adminAppInfo.getApp_name();
String app_package = adminAppInfo.getApp_package();
String app_url = adminAppInfo.getApp_url();
String app_md5 = adminAppInfo.getApp_md5();
int app_id = adminAppInfo.getId();
long app_version_code = adminAppInfo.getApp_version_code();
JsonObject jsonObject = new JsonObject();
jsonObject.addProperty("app_name", app_name);
jsonObject.addProperty("app_package", app_package);
jsonObject.addProperty("app_id", app_id);
jsonObject.addProperty("MD5", app_md5);
PackageInfo packageInfo = null;
try {
packageInfo = mContext.getPackageManager().getPackageInfo(app_package, 0);
} catch (PackageManager.NameNotFoundException e) {
e.printStackTrace();
}
if (packageInfo == null) {
Log.e(TAG, "installAdminApp: " + app_package + " 未安装");
Utils.ariaDownload(mContext, app_url, jsonObject);
} else {
long appVersionCode;
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.P) {
appVersionCode = packageInfo.getLongVersionCode();
} else {
appVersionCode = packageInfo.versionCode;
}
if (app_version_code > appVersionCode) {
Log.e(TAG, "installAdminApp: " + app_package + " 更新");
Utils.ariaDownload(mContext, app_url, jsonObject);
} else {
Log.e(TAG, "installAdminApp: " + app_package + "已安装最新版");
}
}
}
}
private static final String AOLE_DIR = "aoleapp";
public void checkLocalExternalFiles() {
int install = mMMKV.decodeInt(CommonConfig.INSTALL_SD_APKS, 0);
Log.e(TAG, "checkLocalExternalFiles: installed = " + install);
if (install == 1) {
Log.e(TAG, "checkLocalExternalFiles: install");
// return;
}
File[] externalFiles = mContext.getExternalFilesDirs(null);
Log.e(TAG, "checkLocalAppInstall: externalFiles = " + Arrays.toString(externalFiles));
String SdPath = Environment.getExternalStorageDirectory().getAbsolutePath();
Log.e(TAG, "checkLocalAppInstall: SdPath = " + SdPath);
String aolePath = SdPath + File.separator + AOLE_DIR;
File file = new File(aolePath);
if (!file.exists()) {
Log.e(TAG, "checkLocalExternalFiles: dir not exists");
return;
}
String[] apkName = file.list();
if (apkName == null || apkName.length == 0) {
Log.e(TAG, "checkLocalAppInstall: apkName is empty");
} else {
Observable.create(new ObservableOnSubscribe<HashMap<String, String>>() {
@Override
public void subscribe(@NonNull ObservableEmitter<HashMap<String, String>> emitter) throws Throwable {
HashMap<String, String> packageListMap = new HashMap<>();
for (String fileName : apkName) {
String apkPath = aolePath + File.separator + fileName;
Log.e(TAG, "subscribe: " + apkPath);
String pkg = ApkUtils.getPackageName(mContext, apkPath);
if (mJxwApps.contains(pkg)) {
packageListMap.put(pkg, apkPath);
} else {
Log.e(TAG, "checkLocalAppInstall: skip: " + pkg + " fileName: " + fileName);
}
}
emitter.onNext(packageListMap);
emitter.onComplete();
}
}).subscribe(new Observer<HashMap<String, String>>() {
@Override
public void onSubscribe(@NonNull Disposable d) {
Log.e("checkLocalAppInstall", "onSubscribe: ");
}
@Override
public void onNext(@NonNull HashMap<String, String> stringStringHashMap) {
Log.e("checkLocalAppInstall", "onNext: " + stringStringHashMap);
stringStringHashMap.forEach(new BiConsumer<String, String>() {
@Override
public void accept(String key, String value) {
if (ApkUtils.isAvailable(mContext, key)) {
Log.e("checkLocalAppInstall", "accept: installed: " + key);
} else {
ApkUtils.installApp(mContext, value);
}
}
});
}
@Override
public void onError(@NonNull Throwable e) {
Log.e("checkLocalAppInstall", "onError: " + e.getMessage());
onComplete();
}
@Override
public void onComplete() {
Log.e("checkLocalAppInstall", "onComplete: ");
mMMKV.encode(CommonConfig.INSTALL_SD_APKS, 1);
}
});
}
}
private Set<String> mJxwApps = new HashSet<String>() {{
this.add("air.com.zhihuiyoujiao.flashplayer");
this.add("com.example.arithmeticformula");
this.add("com.example.elementcycleapp");
this.add("com.example.pianpangbushou");
this.add("com.iflytek.cyber.iot.show.core");
this.add("com.iflytek.speechcloud");
this.add("com.jxw.bihuamingcheng");
this.add("com.jxw.bishunguize");
this.add("com.jxw.characterlearning");
this.add("com.jxw.dmxcy");
this.add("com.jxw.englishsoundmark");
this.add("com.jxw.examsystem");
this.add("com.jxw.game");
this.add("com.jxw.gb.zwpg");
this.add("com.jxw.handwrite");
this.add("com.jxw.jinfangyici");
this.add("com.jxw.jxwbook");
this.add("com.jxw.jxwcalculator");
this.add("com.jxw.laboratory");
this.add("com.jxw.learnchinesepinyin");
this.add("com.jxw.letterstudynew");
this.add("com.jxw.liancichengju");
this.add("com.jxw.mskt.video");
this.add("com.jxw.newyouer.video");
this.add("com.jxw.online_study");
this.add("com.jxw.question");
this.add("com.jxw.schultegrid");
this.add("com.jxw.singsound");
this.add("com.jxw.studydigital");
this.add("com.jxw.teacher.video");
this.add("com.jxw.wuweijidanci");
this.add("com.jxw.youer.video");
this.add("com.jxw.yuwenxiezuo");
this.add("com.jxw.yyhb");
this.add("com.jxw.zncd");
this.add("com.jxw.souti");
this.add("com.jxw.xdfzq");
this.add("com.oirsdfg89.flg");
this.add("com.study.flashplayer");
this.add("com.tech.translate");
this.add("com.uiui.zybrowser");
this.add("com.uiui.zysn ");
this.add("com.jxw.launcher");
this.add("com.uiui.zyappstore");
this.add("com.uiui.zy");
this.add("com.uiui.zyos");
this.add("com.teclast.zyos");
this.add("com.teclast.zybrowser");
this.add("com.teclast.zyappstore");
this.add("com.teclast.zy");
}};
/**
* 启用/禁用MTP数据传输功能
*
* @param enable
*/
void setMtpEnable(boolean enable) {
if (C2Tag.equals(BuildConfig.platform)) {
Log.e("ITools", "setMtpEnable: " + enable);
try {
mITools.setMtpEnable(enable);
} catch (RemoteException e) {
e.printStackTrace();
}
}
}
/**
* 启用/禁用Camera功能
*
* @param enable
*/
void setCameraEnable(boolean enable) {
if (C2Tag.equals(BuildConfig.platform)) {
Log.e("ITools", "setCameraEnable: " + enable);
try {
mITools.setCameraEnable(enable);
} catch (RemoteException e) {
e.printStackTrace();
}
}
}
/**
* 启用/禁用蓝牙功能
*
* @param enable
*/
void setBluetoothEnable(boolean enable) {
if (C2Tag.equals(BuildConfig.platform)) {
Log.e("ITools", "setBluetoothEnable: " + enable);
try {
mITools.setBluetoothEnable(enable);
} catch (RemoteException e) {
e.printStackTrace();
}
}
}
/**
* No. 7
* 启用/禁用OTG T卡功能
*
* @param enable true 启用 ,false 禁用
**/
void setSDOTGEnable(boolean enable) {
if (C2Tag.equals(BuildConfig.platform)) {
Log.e("ITools", "setSDOTGEnable: " + enable);
try {
mITools.setSDOTGEnable(enable);
} catch (RemoteException e) {
e.printStackTrace();
}
}
}
/**
* No. 31
* 设置apk安装黑白名单模式不会清除黑白名单数据
*
* @param pattern 0:普通模式黑白名单都不生效1黑名单模式2白名单模式
**/
void setAppRestriction(int pattern) {
if (C2Tag.equals(BuildConfig.platform)) {
Log.e("ITools", "setAppRestriction: " + pattern);
try {
mITools.setAppRestriction(pattern);
} catch (RemoteException e) {
e.printStackTrace();
}
}
}
/**
* No. 32
* 获取apk安装名单模式
* @return
* int 0:普通模式黑白名单都不生效1黑名单模式2白名单模式
**/
// int getAppRestrictionMode(){
//
// }
/**
* No. 33
* 设置apk安装白名单
* 在设置前需要先调用setAppRestriction用来设置apk安装模式
* 当设置了黑白名单模式但对应的黑白名单值为空时等同于设置为0普通模式黑白名单都不生效
*
* @param packageNameList 包名列表
**/
void addAppInstallWhiteList(List<String> packageNameList) {
if (C2Tag.equals(BuildConfig.platform)) {
Log.e("ITools", "addAppInstallWhiteList: " + packageNameList);
try {
mITools.addAppInstallWhiteList(packageNameList);
} catch (RemoteException e) {
e.printStackTrace();
}
}
}
/**
* No. 34
* 删除安装白名单列表
*
* @param packageNameList 包名列表
**/
void delAppInstallWhiteList(List<String> packageNameList) {
if (C2Tag.equals(BuildConfig.platform)) {
try {
mITools.delAppInstallWhiteList(packageNameList);
} catch (RemoteException e) {
e.printStackTrace();
}
}
}
/**
* No. 35
* 清空安装白名单列表
**/
void clearAppInstallWhiteList() {
if (C2Tag.equals(BuildConfig.platform)) {
try {
mITools.clearAppInstallWhiteList();
} catch (RemoteException e) {
e.printStackTrace();
}
}
}
/**
* No. 54
* 设置默认Launcher
*
* @param packageName apk的包名
* @param className apk的组件类名
**/
void setDefaultLauncher(ComponentName cmpName) {
if (C2Tag.equals(BuildConfig.platform)) {
Log.e("ITools", "setDefaultLauncher: " + cmpName);
try {
mITools.setDefaultLauncher(cmpName);
} catch (Exception e) {
e.printStackTrace();
}
}
}
/**
* No. 55
* 设置默认浏览器
*
* @param packageName apk的包名
**/
public void setDefaultBrowser(String packageName) {
if (C2Tag.equals(BuildConfig.platform)) {
Log.e("ITools", "setDefaultBrowser: " + packageName);
try {
mITools.setDefaultBrowser(packageName);
} catch (RemoteException e) {
e.printStackTrace();
}
}
}
}