package com.aoleyun.sn.utils; import android.annotation.SuppressLint; import android.app.ActivityManager; import android.app.ActivityManagerNative; import android.app.ActivityTaskManager; import android.app.WallpaperManager; 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.ActivityInfo; 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.Debug; 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 android.view.inputmethod.InputMethodInfo; import android.view.inputmethod.InputMethodManager; import androidx.annotation.Nullable; import androidx.annotation.RequiresApi; import androidx.core.content.ContextCompat; import com.alibaba.sdk.android.push.noonesdk.PushServiceFactory; import com.aoleyun.sn.BuildConfig; import com.aoleyun.sn.bean.AdminAppInfo; import com.aoleyun.sn.bean.AppID; 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.LessonJson; 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.manager.AllwinnerCubeMdmManager; 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.StepService; import com.aoleyun.sn.service.main.MainService; import com.blankj.utilcode.util.FileUtils; import com.bumptech.glide.Glide; import com.bumptech.glide.request.target.SimpleTarget; import com.bumptech.glide.request.transition.Transition; import com.google.gson.Gson; import com.google.gson.JsonObject; import com.google.gson.JsonParser; 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.hjq.toast.Toaster; 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.util.ArrayList; import java.util.Arrays; import java.util.Enumeration; import java.util.HashMap; import java.util.HashSet; import java.util.List; import java.util.Map; import java.util.Optional; import java.util.Set; import java.util.concurrent.Executor; import java.util.function.BiConsumer; import java.util.function.Consumer; import java.util.function.Function; 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"; /*九学王*/ public static final String JXW_LAUNCHER_PACKAGE_NAME = "com.jxw.launcher"; /*注册服务*/ public static final String JXW_LAUNCHER_CLASS_NAME = "com.jht.engine.platsign.PlatformService"; /*学习资源*/ public static final String JXW_LAUNCHER_UPDATE_CLASS_NAME = "com.jxw.engine.platsign.UpdateActivity"; @SuppressLint("StaticFieldLeak") private static JgyUtils sInstance; private MMKV mMMKV = MMKV.mmkvWithID(CommonConfig.MMKV_ID, MMKV.MULTI_PROCESS_MODE); private Context mContext; private ContentResolver crv; private LessonJson mLessonJson; private TimeUtils.ContralTime mContralTime; public static final int UnknowPlatform = 0; public static final int MTKPlatform = 1; public static final int ZhanruiPlatform = 2; // public static final int CubePlatform = 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 int YXPD1Platform = 15; public static final int G11Platform = 16; public static final int MT8768Platform = 17; public static final int AUDG104Platform = 18; public static final int HL500Platform = 20; public static final int G11JPlatform = 21; public static final int P50Platform = 23; public static final int seewoPlatform = 25; public static final int U1302Platform = 26; public static final int MT6765Platform = 28; public static final int G128TPlatform = 29; public static final String Other = "其他"; public static final String MTKTag = "MTK"; public static final String ZhanruiTag = "展锐"; // public static final String CubeTag = "展锐cube"; 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"; public static final String YXPD1TAG = "YXPD1"; public static final String G11TAG = "MTKG11"; public static final String MT8768Tag = "MT8768"; public static final String AUDG104Tag = "AUDG104"; public static final String HL500Tag = "HL500"; public static final String G11JTag = "aud8786"; public static final String P50Tag = "P50TD"; public static final String seewoTag = "seewo"; public static final String allwinner_U1302 = "QZA15"; public static final String MT6765_TAG = "MT6765"; public static final String G128T_TAG = "G128T"; 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(); } refresh(); } 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 (MTKTag.equalsIgnoreCase(platform)) { Log.i(TAG, "checkAppPlatform: " + "MTK平台"); return MTKPlatform; } else if (ZhanruiTag.equalsIgnoreCase(platform)) { Log.i(TAG, "checkAppPlatform: " + "展锐平台"); return ZhanruiPlatform; } // else if (CubeTag.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 if (YXPD1TAG.equalsIgnoreCase(platform)) { Log.i(TAG, "checkAppPlatform: " + "YXPD1"); return YXPD1Platform; } else if (G11TAG.equalsIgnoreCase(platform)) { Log.i(TAG, "checkAppPlatform: " + "MTKG11"); return G11Platform; } else if (MT8768Tag.equalsIgnoreCase(platform)) { Log.i(TAG, "checkAppPlatform: " + "MT8768"); return MT8768Platform; } else if (AUDG104Tag.equalsIgnoreCase(platform)) { Log.i(TAG, "checkAppPlatform: " + "AUDG104"); return AUDG104Platform; } else if (HL500Tag.equalsIgnoreCase(platform)) { Log.i(TAG, "checkAppPlatform: " + "HL500"); return HL500Platform; } else if (G11JTag.equalsIgnoreCase(platform)) { Log.i(TAG, "checkAppPlatform: " + "G11J"); return G11JPlatform; } else if (P50Tag.equalsIgnoreCase(platform)) { Log.i(TAG, "checkAppPlatform: " + "P50TD"); return P50Platform; } else if (seewoTag.equalsIgnoreCase(platform)) { Log.i(TAG, "checkAppPlatform: " + "seewo"); return seewoPlatform; } else if (allwinner_U1302.equalsIgnoreCase(platform)) { Log.i(TAG, "checkAppPlatform: " + "U1302"); return U1302Platform; } else if (MT6765_TAG.equalsIgnoreCase(platform)) { Log.i(TAG, "checkAppPlatform: " + "MT6765"); return MT6765Platform; } else if (G128T_TAG.equalsIgnoreCase(platform)) { Log.i(TAG, "checkAppPlatform: " + "G128T"); return G128TPlatform; } else { Log.i(TAG, "checkAppPlatform: " + "没有数据"); return UnknowPlatform; } } public boolean isSamePlatform(String platform) { String AppPlatform = BuildConfig.platform; if (ZhanruiTag.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 (MTKTag.equalsIgnoreCase(platform)) { getAppPlatformCallback.AppPlatform(MTKPlatform); } else if (ZhanruiTag.equalsIgnoreCase(platform)) { getAppPlatformCallback.AppPlatform(ZhanruiPlatform); } // else if ("ZhanRuiCube".equalsIgnoreCase(platform)) { // getAppPlatformCallback.AppPlatform(CubePlatform); // } else if (MTK11Tag.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 if (YXPD1TAG.equalsIgnoreCase(platform)) { getAppPlatformCallback.AppPlatform(YXPD1Platform); } else if (G11TAG.equalsIgnoreCase(platform)) { getAppPlatformCallback.AppPlatform(G11Platform); } else if (MT8768Tag.equalsIgnoreCase(platform)) { getAppPlatformCallback.AppPlatform(MT8768Platform); } else if (AUDG104Tag.equalsIgnoreCase(platform)) { getAppPlatformCallback.AppPlatform(AUDG104Platform); } else if (HL500Tag.equalsIgnoreCase(platform)) { getAppPlatformCallback.AppPlatform(HL500Platform); } else if (G11JTag.equalsIgnoreCase(platform)) { getAppPlatformCallback.AppPlatform(G11JPlatform); } else if (P50Tag.equalsIgnoreCase(platform)) { getAppPlatformCallback.AppPlatform(P50Platform); } else if (seewoTag.equalsIgnoreCase(platform)) { getAppPlatformCallback.AppPlatform(seewoPlatform); } else if (allwinner_U1302.equalsIgnoreCase(platform)) { getAppPlatformCallback.AppPlatform(U1302Platform); } else if (MT6765_TAG.equalsIgnoreCase(platform)) { getAppPlatformCallback.AppPlatform(MT6765Platform); } else if (G128T_TAG.equalsIgnoreCase(platform)) { getAppPlatformCallback.AppPlatform(G128TPlatform); } else { getAppPlatformCallback.AppPlatform(UnknowPlatform); } } public String getAppPlatform() { String platform = BuildConfig.platform; if (MTKTag.equalsIgnoreCase(platform)) { return MTKTag; } else if (ZhanruiTag.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 if (YXPD1TAG.equalsIgnoreCase(platform)) { return YXPD1TAG; } else if (G11TAG.equalsIgnoreCase(platform)) { return G11TAG; } 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 */ public void setNetAndlaunch(NetAndLaunchBean netAndLaunchBean, List appListInfos) { Log.e(TAG, "setNetAndlaunch: " + "应用联网管控: " + netAndLaunchBean.getData().toString()); Log.e(TAG, "setNetAndlaunch: "); HashSet autoLaunchApp = new HashSet<>();//开机自启app HashSet allowNetApp = new HashSet<>();//允许联网 HashSet disallowNetApp = new HashSet<>();//禁止联网 HashSet allowUpgrade = new HashSet<>();//允许升级 HashSet disallowUpgrade = new HashSet<>();//禁止升级 HashSet allowSlide = new HashSet<>();//允许滑动 HashSet disallowSlide = new HashSet<>();//禁止滑动 List 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(disallowNetApp, allowNetApp); } public void onBootOpenApp() { if ("G1096JW".equals(Build.MODEL)) { if (ApkUtils.isAvailable(mContext, "com.aisudu.xhb")) { ApkUtils.openPackage(mContext, "com.aisudu.xhb"); } } String qch_app_power_on = Settings.System.getString(crv, CommonConfig.AOLE_ACTION_APP_POWER_ON); if (TextUtils.isEmpty(qch_app_power_on)) { return; } List 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 disallowUpgrade, List appListInfos) { if (appListInfos == null || appListInfos.size() == 0) { return; } Log.e(TAG, "checkPackageAndVersion: " + disallowUpgrade); PackageManager pm = mContext.getPackageManager(); HashMap 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(); } } } } public void setNetAndlaunch(NetAndLaunchBean netAndLaunchBean) { Log.e(TAG, "setNetAndlaunch: " + "应用联网管控: " + netAndLaunchBean.getData().toString()); Log.e(TAG, "setNetAndlaunch: "); HashSet autoLaunchApp = new HashSet<>();//开机自启app HashSet allowNetApp = new HashSet<>();//允许联网 HashSet disallowNetApp = new HashSet<>();//禁止联网 HashSet allowUpgrade = new HashSet<>();//允许升级 HashSet disallowUpgrade = new HashSet<>();//禁止升级 HashSet allowSlide = new HashSet<>();//允许滑动 HashSet disallowSlide = new HashSet<>();//禁止滑动 HashSet disallowNotification = new HashSet<>();//禁止通知栏显示通知 HashSet allowPermissions = new HashSet<>();//默认给所有权限 List 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(); int is_notification = netAndLaunchData.getIs_notification(); int is_dynamic_perm = netAndLaunchData.getIs_dynamic_perm(); 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 (is_notification == 0) { disallowNotification.add(app_package); } if (is_dynamic_perm == 1) { allowPermissions.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(disallowNetApp, allowNetApp); setDisallowNotificationPackage(mContext, disallowNotification); mMMKV.encode("aole_app_privilege", allowPermissions); setAllowPermissionsPackage(); } private void setDisallowNotificationPackage(Context context, HashSet pkgSet) { Log.e(TAG, "setDisallowNotificationPackage: " + pkgSet); if (pkgSet.size() == 0) { Settings.System.putString(context.getContentResolver(), "aole_app_info", ""); } else { Settings.System.putString(context.getContentResolver(), "aole_app_info", String.join(",", pkgSet)); } if (JgyUtils.isAllWinnerDevice()) { AllwinnerCubeMdmManager.getInstance().setDisallowNotification(new ArrayList<>(pkgSet)); } } public void setAllowPermissionsPackage() { Set privilegeApp = mMMKV.decodeStringSet("aole_app_privilege", new HashSet<>()); Log.e(TAG, "setAllowPermissionsPackage: " + privilegeApp); Set pkgSet = privilegeApp.stream().filter(s -> ApkUtils.isAvailable(mContext, s)).collect(Collectors.toSet()); Log.e(TAG, "setAllowPermissionsPackage: " + pkgSet); if (pkgSet.size() == 0) { Settings.System.putString(crv, "aole_app_privilege", ""); } else { Settings.System.putString(crv, "aole_app_privilege", String.join(",", pkgSet)); } if (JgyUtils.isAllWinnerDevice()) { AllwinnerCubeMdmManager.getInstance().setDefaultPermissions(new ArrayList<>(pkgSet)); } } public static final Set DEFAULT_ALLOW_NETWORK_APP_SET = new HashSet() {{ this.add(BuildConfig.APPLICATION_ID); this.add("com.aoleyun.appstore"); this.add("com.aoleyun.camera"); this.add("com.aoleyun.browser"); this.add("com.aoleyun.info"); this.add("com.aoleyun.os"); this.add("com.aoleyun.calculator"); this.add("com.aoleyun.gallery3d"); this.addAll(ApkUtils.mJxwApp); this.addAll(ApkUtils.desktopAPP); this.add("com.android.settings"); this.add("com.aoleyunos.dop"); this.add("com.aoleyunos.dop1"); this.add("com.aoleyunos.dop2"); this.add("com.aoleyunos.dop3"); this.add("com.aoleyunos.dop4"); this.add("com.aoleyunos.dop5"); this.add("com.aoleyunos.dop6"); this.add("com.aoleyunos.dop7"); this.add("com.aoleyunos.dop8"); this.add("com.aoleyunos.dop9"); this.add("com.aoleyunos.dop10"); this.add("com.schoolos.cmcc"); this.add("com.aoleyunos.natuer"); }}; public void setAppNetwork(HashSet blackList, HashSet whiteList) { Log.e(TAG, "setAppNetwork: " + "设置应用联网管控 blackList =" + blackList); Log.e(TAG, "setAppNetwork: " + "设置应用联网管控 whiteList =" + whiteList); if ("Ebox201W".equals(Build.MODEL) || "Ebox201".equals(Build.MODEL)) { } else { try { Settings.System.putString(crv, CommonConfig.AOLE_ACTION_NETWORK_ALLOW, null); CmdUtil.Result result = CmdUtil.execute(" settings delete system aole_network_allow"); Log.e(TAG, "setAppNetwork: " + result); } catch (Exception e) { e.printStackTrace(); } } if (!MTK11Tag.equals(JgyUtils.getInstance().getAppPlatform())) { if (blackList == null || blackList.size() == 0) { Settings.System.putString(crv, CommonConfig.AOLE_ACTION_NETWORK_DISALLOW, null); } else { String net_not = String.join(",", blackList); Settings.System.putString(crv, CommonConfig.AOLE_ACTION_NETWORK_DISALLOW, net_not); Log.e(TAG, "setAppNetwork: " + net_not); } } if (blackList != null) { List installedBlackApps = blackList.stream().filter(s -> ApkUtils.isAvailable(mContext, s)).collect(Collectors.toList()); Log.e(TAG, "setAppNetwork: installedBlackApps = " + installedBlackApps); if (JgyUtils.isAllWinnerDevice()) { AllwinnerCubeMdmManager.getInstance().setBlackNetApp(installedBlackApps); } } mMMKV.encode(CommonConfig.AOLE_ACTION_NETWORK_ALLOW, whiteList); Set pkgs; int is_app_install = Settings.System.getInt(crv, CommonConfig.AOLE_APP_ALLOW_INSTALL, 0); if (is_app_install == 1) { Log.e(TAG, "setAppNetwork: is_app_install = 1"); pkgs = new HashSet<>(ApkUtils.queryFilterAppList(mContext)); } else { pkgs = new HashSet<>(whiteList); } pkgs.addAll(DEFAULT_ALLOW_NETWORK_APP_SET); List filterList = pkgs.stream().filter(s -> ApkUtils.isAvailable(mContext, s)).collect(Collectors.toList()); Log.e(TAG, "setAppNetwork: filterList = " + filterList); if ("Ebox201W".equals(Build.MODEL) || "Ebox201".equals(Build.MODEL)) { if (filterList.size() == 0) { Settings.System.putString(crv, CommonConfig.AOLE_ACTION_NETWORK_ALLOW, null); } else { // TODO: 2024/10/31 需要多写一次保证数据库变化 filterList.add("com.ttstd.utils"); Settings.System.putString(crv, CommonConfig.AOLE_ACTION_NETWORK_ALLOW, String.join(",", filterList)); filterList.remove("com.ttstd.utils"); Settings.System.putString(crv, CommonConfig.AOLE_ACTION_NETWORK_ALLOW, String.join(",", filterList)); } } } /** * 应用安装之后添加到白名单 */ public void updateNetworkWhiteList() { Log.e(TAG, "updateNetworkWhiteList: "); if ("Ebox201W".equals(Build.MODEL) || "Ebox201".equals(Build.MODEL)) { } else { try { Settings.System.putString(crv, CommonConfig.AOLE_ACTION_NETWORK_ALLOW, null); CmdUtil.Result result = CmdUtil.execute(" settings delete system aole_network_allow"); Log.e(TAG, "updateNetworkWhiteList: " + result); } catch (Exception e) { e.printStackTrace(); } } if ("Ebox201W".equals(Build.MODEL) || "Ebox201".equals(Build.MODEL)) { } else { try { Settings.System.putString(mContext.getContentResolver(), CommonConfig.AOLE_APP_WEB_BLACK_LIST, null); CmdUtil.Result result = CmdUtil.execute(" settings delete system app_web_black_list"); Log.e(TAG, "updateNetworkWhiteList: " + result); } catch (Exception e) { e.printStackTrace(); } } if ("Ebox201W".equals(Build.MODEL) || "Ebox201".equals(Build.MODEL)) { } else { try { Settings.System.putString(mContext.getContentResolver(), CommonConfig.AOLE_APP_WEB_WHITE_LIST, null); CmdUtil.Result result = CmdUtil.execute(" settings delete system app_web_white_list"); Log.e(TAG, "getWhiteList: " + result); } catch (Exception e) { e.printStackTrace(); } } Set pkgs; int is_app_install = Settings.System.getInt(crv, CommonConfig.AOLE_APP_ALLOW_INSTALL, 0); if (is_app_install == 1) { Log.e(TAG, "updateNetworkWhiteList: is_app_install = 1"); pkgs = new HashSet<>(ApkUtils.queryFilterAppList(mContext)); } else { pkgs = mMMKV.decodeStringSet(CommonConfig.AOLE_ACTION_NETWORK_ALLOW, new HashSet<>()); } pkgs.addAll(DEFAULT_ALLOW_NETWORK_APP_SET); List whiteList = new ArrayList<>(pkgs); List filterList = whiteList.stream().filter(s -> ApkUtils.isAvailable(mContext, s)).collect(Collectors.toList()); Log.e(TAG, "updateNetworkWhiteList: filterList = " + filterList); if ("Ebox201W".equals(Build.MODEL) || "Ebox201".equals(Build.MODEL)) { if (filterList.size() == 0) { Settings.System.putString(crv, CommonConfig.AOLE_ACTION_NETWORK_ALLOW, null); } else { // TODO: 2024/10/31 需要多写一次保证数据库变化 filterList.add("com.ttstd.utils"); Settings.System.putString(crv, CommonConfig.AOLE_ACTION_NETWORK_ALLOW, String.join(",", filterList)); filterList.remove("com.ttstd.utils"); Settings.System.putString(crv, CommonConfig.AOLE_ACTION_NETWORK_ALLOW, String.join(",", filterList)); } } Log.e(TAG, "updateNetworkWhiteList: " + filterList); } public void onBootSendNetwork() { if (!MTK11Tag.equals(JgyUtils.getInstance().getAppPlatform())) { String oldBlackListString = (String) SPUtils.get(mContext, CommonConfig.AOLE_ACTION_NETWORK_DISALLOW, ""); HashSet oldBlackListSet = new HashSet<>(Arrays.asList(oldBlackListString.split(","))); Log.e(TAG, "setAppNetwork: oldBlackListSet: " + oldBlackListSet); oldBlackListSet.removeIf(new Predicate() { @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); } } } public void writeDeselectIDtoSystem(List appIDList) { if (!"Ebox201".equals(Build.MODEL) && !"Ebox201W".equals(Build.MODEL)) { Log.e(TAG, "writeDeselectIDtoSystem: not match Ebox201 or Ebox201W"); return; } if (appIDList == null || appIDList.isEmpty()) { if ("G10".equals(Build.MODEL) || "D1".equals(Build.MODEL)) { Settings.System.putString(mContext.getContentResolver(), CommonConfig.APP_VIEW_CLICK_DISABLED, "com.arivoc.wordhd:2131624676,2131624689;com.ttstd.utils:12345"); } else { try { Settings.System.putString(crv, CommonConfig.APP_VIEW_CLICK_DISABLED, null); // TODO: 2024/9/11 修复1.4.0907版本数据为空系统报错 CmdUtil.Result result = CmdUtil.execute(" settings delete system app_view_click_disabled"); Log.e(TAG, "writeDeselectIDtoSystem: " + result); } catch (Exception e) { e.printStackTrace(); } } } else { String s = appIDList.stream().map(new Function() { @Override public String apply(AppID appID) { return appID.toString(); } }).collect(Collectors.joining(";")); Log.e(TAG, "writeDeselectIDtoSystem: " + s); Settings.System.putString(crv, CommonConfig.APP_VIEW_CLICK_DISABLED, s); } } public void setAppinsideWeb(BaseResponse> response) { if (response.code == 200) { List 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); //Toaster.show(msg); Log.e("setAppinsideWeb", "setAppinsideWeb: " + response.msg); } } /** * @param response 黑白名单都可以管控 */ 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>() { }.getType(); List appgrounds = gson.fromJson(jsonString, type); List whiteApp = new ArrayList<>(); List 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 whiteApp = new ArrayList<>(); setWhiteApp(whiteApp); sendAllweb(mContext); sendwebUrl(mContext); //Toaster.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") private void setWhiteApp(List appgrounds) { //去重 List ttAppgrounds = appgrounds.stream().distinct().collect(Collectors.toList()); List old = getOldWhitelist(); comparedAppground(old, ttAppgrounds); setWhiteList(ttAppgrounds); } private void comparedAppground(List oldAppgrounds, List newAppgrounds) { List addAppgrounds = new ArrayList<>(); List deleteAppgrounds = new ArrayList<>(); List changedAppgrounds = new ArrayList<>(); HashMap oldAppgroundsMap = new HashMap<>(); HashMap 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 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 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 appgroundList) { for (TTAppground appground : appgroundList) { deleteWhitelistUrl(appground.getPackages(), appground.getAddress()); deleteOtherAppWhitelist(appground.getPackages()); Log.e("comparedAppground", "deleteAppground: " + appground.getAddress()); } } private void changeAppground(HashMap oldAppgroundsMap, List appgroundList) { for (TTAppground appground : appgroundList) { HashSet newURL = new HashSet<>(Arrays.asList(appground.getAddress().split(","))); TTAppground oldAppground = oldAppgroundsMap.get(appground.getPackages()); HashSet 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 getOldWhitelist() { String whiteListString = (String) SPUtils.get(mContext, JGY_APPINSIDE_WHITELIST, ""); Log.e(TAG, "getOldWhitelist: " + whiteListString); Gson gson = new Gson(); Type listType = new TypeToken>() { }.getType(); List whiteList = gson.fromJson(whiteListString, listType); if (whiteList == null) { whiteList = new ArrayList<>(); } //去重 whiteList.removeIf(new Predicate() { @Override public boolean test(TTAppground ttAppground) { return !ApkUtils.isAvailable(mContext, ttAppground.getPackages()); } }); List ttAppgrounds = whiteList.stream().distinct().collect(Collectors.toList()); return ttAppgrounds; } /** * @param appgrounds 写入缓存 */ private void setWhiteList(List appgrounds) { appgrounds.removeIf(new Predicate() { @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 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白名单 */ 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白名单 */ private void addToWhitelist(String pkg, String urls) { if (TextUtils.isEmpty(urls)) { Log.e(TAG, "addToWhitelist: " + "urls is NULL"); return; } HashSet 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 内某个白名单 */ private void deleteWhitelistUrl(String pkg, String urls) { if (TextUtils.isEmpty(urls)) { Log.e(TAG, "addToWhitelist: " + "urls is NULL"); return; } HashSet 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 开启和关闭白名单管控都需要发送 */ 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 设置黑名单管控 */ private void setBlackApp(List 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); } } 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); } 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); } public void SettingSysData(String data) { if (TextUtils.isEmpty(data)) { Log.e(TAG, "SettingSysData: " + "data is empty"); int locked = Settings.System.getInt(crv, JGYActions.ACTION_QCH_UNLOCK_IPAD, JGYActions.FRAME_CODE_LOCKED); if (locked == JGYActions.FRAME_CODE_LOCKED) { SysSettingUtils.setDisableSetting(mContext); } SPUtils.put(mContext, JGYActions.ACTION_STATUSBAR_STATUS, ""); } else { if (JgyUtils.getInstance().getAppPlatform().equals(JgyUtils.ZR6016Tag)) { Log.e(TAG, "SettingSysData: ZR6016Tag"); SysSettingUtils.setBluetooth(mContext, 0); } SysSettingUtils.setSystemSetting(mContext, data); } } HashSet defaultPackages = new HashSet() {{ this.add(BuildConfig.APPLICATION_ID); 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.aoleyun.audos"); this.add("com.aoleyunos.dop"); this.add("com.aoleyunos.dop1"); this.add("com.aoleyunos.dop2"); this.add("com.aoleyunos.dop3"); this.add("com.aoleyunos.dop4"); this.add("com.aoleyunos.dop5"); this.add("com.aoleyunos.dop6"); this.add("com.aoleyunos.dop7"); this.add("com.aoleyunos.dop8"); this.add("com.aoleyunos.dop9"); this.add("com.aoleyunos.dop10"); this.add("com.schoolos.cmcc"); this.add("com.aoleyunos.natuer"); 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"); this.add("com.books.wisdom"); this.add("com.qi.airoom"); this.add("com.qi.AiStudyRoom"); this.add("com.eusoft.eudic"); this.add("com.fenbi.android.solar"); this.add("com.eduyun.app.factory.ykt"); this.add("com.yaerxing.fkst"); this.add("com.jxw.usagedate"); }}; private Set getWhitePkgList() { HashSet pkgSet = new HashSet<>(defaultPackages); pkgSet.addAll(showAppList); pkgSet.addAll(ApkUtils.desktopAPP); pkgSet.addAll(ApkUtils.aoleyunAPP); pkgSet.addAll(ApkUtils.mJxwApp); if (G128T_TAG.equals(BuildConfig.platform)) { pkgSet.add("com.dmjc.xinhuo"); } if ("K101".equals(Build.MODEL) || "AS001".equals(Build.MODEL)) { pkgSet.addAll(ApkUtils.aihuaApp); pkgSet.addAll(aihuaAppList); } if ("D1".equals(Build.MODEL)) { pkgSet.addAll(ApkUtils.dongwa); } if ("G23".equals(Build.MODEL)) { pkgSet.addAll(ApkUtils.zhengwu); } if (JgyUtils.getInstance().checkAppPlatform() == JgyUtils.G11Platform) { pkgSet.addAll(ApkUtils.G11Pkgs); } if (JgyUtils.getInstance().checkAppPlatform() == JgyUtils.YXPD1Platform) { pkgSet.add("com.tencent.wemeet.app"); } if (JgyUtils.getInstance().checkAppPlatform() == JgyUtils.G10PPlatform) { pkgSet.add("com.gaomuxuexi34"); } if (JgyUtils.C2Tag.equalsIgnoreCase(JgyUtils.getInstance().getAppPlatform())) { pkgSet.remove("com.tencent.mm"); } return pkgSet; } @SuppressLint("NewApi") public void writeAppPackageList(List pkgs) { if (isUnlocked(mContext)) { addAppInstallWhiteList(new ArrayList<>()); setAppRestriction(0); return; } ApkUtils.addShortcut(mContext); HashSet pkgSet = new HashSet<>(defaultPackages); if (BuildConfig.DEBUG) { pkgSet.add("com.reqable.android"); pkgSet.add("com.ttstd.codetest1"); } pkgSet.addAll(pkgs); pkgSet.addAll(getWhitePkgList()); pkgSet.removeIf(TextUtils::isEmpty); if (JgyUtils.isAllWinnerDevice()) { AllwinnerCubeMdmManager.getInstance().setInstallPackageWhiteList(new ArrayList<>(pkgSet)); } 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() { if (isUnlocked(mContext)) { addAppInstallWhiteList(new ArrayList<>()); setAppRestriction(0); return; } HashSet pkgSet = new HashSet<>(defaultPackages); if (BuildConfig.DEBUG) { pkgSet.add("com.reqable.android"); pkgSet.add("com.ttstd.codetest1"); } pkgSet.addAll(getWhitePkgList()); pkgSet.removeIf(TextUtils::isEmpty); if (JgyUtils.isAllWinnerDevice()) { AllwinnerCubeMdmManager.getInstance().setInstallPackageWhiteList(new ArrayList<>(pkgSet)); } 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>() { // }.getType(); // List forceDownloadData = gson.fromJson(jsonString, listType); // if (forceDownloadData != null) { // JgyUtils.getInstance().forceDownload(forceDownloadData); // } // } NetInterfaceManager.getInstance().getForceDownload(); } public void forceDownload(List data) { if (data == null || data.size() <= 0) { return; } Log.e(TAG, "forceDownload: data size = " + data.size()); List 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("forceDownload", "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("forceDownload", "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("forceDownload ", "download URL " + app_url); Utils.ariaDownload(mContext, app_url, jsonObject); } else { Log.e(TAG, "forceDownload: installed skip"); } } else { Log.e("forceDownload ", "download URL " + app_url); Utils.ariaDownload(mContext, app_url, jsonObject); } startServices(mContext); } } /** * @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 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 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; } if (isUnlocked(mContext)) { return; } int aihuaUnlock = Settings.System.getInt(crv, CommonConfig.AIHUA_UNLOCK, 0); if (aihuaUnlock == 1) { Log.e(TAG, "deleteOtherApp: aihuaUnlock"); return; } int is_app_install = Settings.System.getInt(crv, CommonConfig.AOLE_APP_ALLOW_INSTALL, 0); if (is_app_install == 1) { Log.e(TAG, "deleteOtherApp: is_app_install = 1"); return; } Log.e(TAG, "deleteOtherApp: " + "start"); Set allAppWhiteSet = mMMKV.decodeStringSet(CommonConfig.AOLE_ALL_APP_WHITE_LIST_KEY, new HashSet<>()); Log.e("deleteOtherApp", "allAppWhiteSet:" + allAppWhiteSet); List resulWhitetList = new ArrayList<>(defaultPackages); resulWhitetList.addAll(allAppWhiteSet); //获取可以被安装的包名 String aole_app_forbid = Settings.System.getString(crv, CommonConfig.AOLE_ACTION_APP_FORBID); Log.e("deleteOtherApp", "aole_app_forbid:" + aole_app_forbid); if (!TextUtils.isEmpty(aole_app_forbid)) { List result_forbid = new ArrayList<>(Arrays.asList(aole_app_forbid.split(","))); resulWhitetList.addAll(result_forbid); } List installedPackageList = ApkUtils.queryFilterAppInfo(mContext); Log.e("deleteOtherApp", "installedPackageList:" + installedPackageList.toString()); if (resulWhitetList.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.mJxwApp.contains(packageName)) { continue; } if (PackageNames.DEVICE_INFO.equals(packageName) || PackageNames.APPSTORE.equals(packageName) ) { continue; } if (!resulWhitetList.contains(packageName)) { ApkUtils.UninstallAPP(mContext, packageName); Log.e("deleteOtherApp", "uninstall apkName:" + packageName); } } } Log.e(TAG, "deleteOtherApp: " + "end"); } HashSet showAppList = new HashSet() {{ 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.dop"); this.add("com.aoleyunos.dop1"); this.add("com.aoleyunos.dop2"); this.add("com.aoleyunos.dop3"); this.add("com.aoleyunos.dop4"); this.add("com.aoleyunos.dop5"); this.add("com.aoleyunos.dop6"); this.add("com.aoleyunos.dop7"); this.add("com.aoleyunos.dop8"); this.add("com.aoleyunos.dop9"); this.add("com.aoleyunos.dop10"); this.add("com.schoolos.cmcc"); this.add("com.aoleyunos.natuer"); }}; HashSet aihuaAppList = new HashSet() {{ //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"); this.add("com.tongyi.aistudent"); }}; /** * 隐藏系统所有应用 * 除了设置,图库、视频、设置、文件管理器、通话、短信、日历、时钟、计算器 */ public void hideSystemAPP() { PackageManager pm = mContext.getPackageManager(); try { pm.setApplicationEnabledSetting("com.yxxmk.uiui", PackageManager.COMPONENT_ENABLED_STATE_DEFAULT, 0); } catch (Exception e) { Log.e(TAG, "hideSystemAPP: " + e.getMessage()); } Intent filterIntent = new Intent(Intent.ACTION_MAIN, null); //Intent.CATEGORY_LAUNCHER主要的过滤条件 filterIntent.addCategory(Intent.CATEGORY_LAUNCHER); List 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 (!getWhitePkgList().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) { Log.e(TAG, "hideApp: " + 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) { Log.e(TAG, "showApp: " + 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"); setBootanimationG10J(bootFile.getAbsolutePath()); } else { JsonObject jsonObject = new JsonObject(); jsonObject.addProperty("MD5", MD5); jsonObject.addProperty("app_name", "开机动画"); jsonObject.addProperty("app_package", "开机动画"); Utils.ariaDownload(mContext, url, jsonObject); Log.e(TAG, "checkBootFile: " + "download file"); } } else { JsonObject jsonObject = new JsonObject(); jsonObject.addProperty("MD5", MD5); jsonObject.addProperty("app_name", "开机动画"); jsonObject.addProperty("app_package", "开机动画"); Utils.ariaDownload(mContext, url, jsonObject); } } // @Deprecated // private static final String BOOTANIMATION_PATH = "/data/local/qchmedia/bootanimation.zip"; // // @Deprecated // 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(); // } // } // } private static final String BOOTANIMATION_PATH_G10J = "/storage/emulated/0/Download/bootanimation.zip"; public void setBootanimationG10J(String filePath) { File newFile = new File(filePath); if (!newFile.exists()) { Log.e(TAG, "setBootanimationG10J: file not exists"); return; } File file = new File(BOOTANIMATION_PATH_G10J); String oldMD5 = FileUtils.getFileMD5ToString(file); String newMD5 = FileUtils.getFileMD5ToString(newFile); if (oldMD5.equals(newMD5)) { Log.e(TAG, "setBootanimationG10J: file md5 is the same"); } else { if (file.exists() && !file.isDirectory()) { if (file.delete()) { Log.e(TAG, "setBootanimationG10J: delete old Bootanimation file successful"); } else { Toaster.show("删除动画文件失败"); } } if (FileUtils.copy(newFile, file)) { Toaster.show("设置开机动画成功"); Log.e(TAG, "setBootanimationG10J: set Bootanimation successful"); } else { Log.e(TAG, "setBootanimationG10J: set Bootanimation failed"); } } Intent intent = new Intent("com.hra.setBootanimation"); mContext.sendBroadcast(intent); } public void removeBootanimation() { File systemFile; // if (JgyUtils.getInstance().checkAppPlatform() == JgyUtils.MT8768Platform) { systemFile = new File(BOOTANIMATION_PATH_G10J); // } else { // systemFile = new File(BOOTANIMATION_PATH); // } if (systemFile.exists()) { if (systemFile.delete()) { Log.e(TAG, "removeBootanimation: delete: " + "ture"); } else { Log.e(TAG, "removeBootanimation: delete: " + "false"); } } // if (JgyUtils.getInstance().checkAppPlatform() == JgyUtils.MT8768Platform) { Intent intent = new Intent("com.hra.setBootanimation"); mContext.sendBroadcast(intent); // } } 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(); } } /** * @param state 1打开 0关闭 */ public void setDeveloperOptions(int state) { Log.e(TAG, "setDeveloperOptions: state = " + state); int oldStatu = Settings.System.getInt(crv, CommonConfig.AOLE_ACTION_DEVELOPER_OPTIONS, 0); if (oldStatu == (state ^ 1)) { Log.e(TAG, "setDeveloperOptions: oldStatu = " + oldStatu + " no changed"); } if (MT8768Tag.equalsIgnoreCase(BuildConfig.platform) || G128T_TAG.equalsIgnoreCase(BuildConfig.platform) ) { Settings.System.putInt(crv, CommonConfig.AOLE_ACTION_DEVELOPER_OPTIONS, state); } else { //这个需要反着来 Settings.System.putInt(crv, CommonConfig.AOLE_ACTION_DEVELOPER_OPTIONS, state ^ 1); } Log.e(TAG, "setDeveloperOptions: DEVELOPMENT_SETTINGS_ENABLED = " + Settings.Global.getInt(crv, Settings.Global.DEVELOPMENT_SETTINGS_ENABLED, 0)); Log.e(TAG, "setDeveloperOptions: ADB_ENABLED = " + Settings.Global.getInt(crv, Settings.Global.ADB_ENABLED, 0)); // if (!BuildConfig.DEBUG) { if (Settings.Global.getInt(crv, Settings.Global.DEVELOPMENT_SETTINGS_ENABLED, 0) != state) { Settings.Global.putInt(crv, Settings.Global.DEVELOPMENT_SETTINGS_ENABLED, state); } if (Settings.Global.getInt(crv, Settings.Global.ADB_ENABLED, 0) != state) { Settings.Global.putInt(crv, Settings.Global.ADB_ENABLED, state); } // } if (JgyUtils.isAllWinnerDevice()) { AllwinnerCubeMdmManager.getInstance().setDeveloperEnable(state == 1); } } 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) { Log.e(TAG, "killPackage: " + 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); intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK); /*知道要跳转应用的包命与目标Activity*/ ComponentName componentName = new ComponentName("com.adups.fota", "com.adups.fota.GoogleOtaClient"); intent.setComponent(componentName); try { mContext.startActivity(intent); } catch (Exception e) { Log.e(TAG, "openOTA: " + e.getMessage()); Toaster.show("打开失败"); } } public void openRomOta() { Intent intent = new Intent(Intent.ACTION_MAIN); intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK); /*知道要跳转应用的包命与目标Activity*/ switch (JgyUtils.getInstance().checkAppPlatform()) { default: case JgyUtils.YXPD1Platform: intent.setComponent(new ComponentName("com.adups.fota", "com.adups.fota.GoogleOtaClient")); break; case JgyUtils.C2Platform: intent.setComponent(new ComponentName("com.jintaiyi.update", "com.jintaiyi.update.activity.NoVersionActivity")); break; case JgyUtils.ZhanruiPlatform: intent.setComponent(new ComponentName("com.cube.update", "com.cube.update.GoogleOtaClient")); break; case JgyUtils.MT6765Platform: intent.setComponent(new ComponentName("com.waterworld.update", "com.waterworld.update.GoogleOtaClient")); break; } try { mContext.startActivity(intent); } catch (Exception e) { Log.e(TAG, "openRomOta: " + e.getMessage()); Toaster.show("打开失败"); } } 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); } @Deprecated 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 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 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 list = getRecentTasks(ActivityManager.getMaxRecentTasksStatic(), getCurrentUserId()); HashMap 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可能不会被清理 */ public 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 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 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 en = NetworkInterface.getNetworkInterfaces(); en.hasMoreElements(); ) { NetworkInterface intf = en.nextElement(); for (Enumeration 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 Launcher3QuickstepClass = "com.android.launcher3.uioverrides.QuickstepLauncher"; private String AoleyunOs = "com.aoleyun.os"; private String AoleyunOsClass = "com.aoleyun.os.Launcher"; private String AiUDuOs = "com.aoleyun.audos"; private String AiUDuOsClass = "com.aoleyun.audos.Launcher"; private String schoolosOs = "com.schoolos.cmcc"; private String schoolosClass = "com.schoolos.cmcc.activity.main.MainActivity"; private String AlyOs = "com.aly.os"; private String AlyOsClass = "com.aly.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 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 setDefaultLauncher2(Context context, String pkg, String cls) { PackageManager pm = context.getPackageManager(); ComponentName component = new ComponentName(pkg, cls); // 创建 IntentFilter IntentFilter filter = new IntentFilter(Intent.ACTION_MAIN); filter.addCategory(Intent.CATEGORY_HOME); filter.addCategory(Intent.CATEGORY_DEFAULT); // 获取所有支持 HOME 的 Activity List homeApps = pm.queryIntentActivities(new Intent(Intent.ACTION_MAIN).addCategory(Intent.CATEGORY_HOME), 0); ComponentName[] components = new ComponentName[homeApps.size()]; for (int i = 0; i < homeApps.size(); i++) { ActivityInfo ai = homeApps.get(i).activityInfo; components[i] = new ComponentName(ai.packageName, ai.name); } // 替换默认桌面 pm.replacePreferredActivity(filter, IntentFilter.MATCH_CATEGORY_EMPTY, components, component); } 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("setRoleHolderAsUser", (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 callback = successful -> { if (successful) { Log.d("setRoleHolderAsUser", "Package " + (add ? "added" : "removed") + " as role holder, role: " + roleName + ", package: " + packageName); } else { Log.d("setRoleHolderAsUser", "Failed to " + (add ? "add" : "remove") + " package as role holder, role: " + roleName + ", package: " + packageName); } }; roleManager.addRoleHolderAsUser(roleName, packageName, flags, user, executor, callback); Log.i("setRoleHolderAsUser", "addRoleHolderAsUser done"); } } } public void checkDefaultDesktop(String pkg) { String desktopPkg = getDefaultDesktop(); // String desktopPkg = (String) SPUtils.get(mContext, "default_launcher", ""); Log.e(TAG, "checkDefaultDesktop: pkg = " + pkg); Log.e(TAG, "checkDefaultDesktop: desktopPkg = " + desktopPkg); if (TextUtils.isEmpty(pkg)) { if (JgyUtils.getInstance().checkAppPlatform() == JgyUtils.YXPD1Platform) { JgyUtils.getInstance().setDop7DefaultDesktop(); } else if (JgyUtils.getInstance().checkAppPlatform() == JgyUtils.G11Platform) { JgyUtils.getInstance().setJXWDefaultDesktop(); // } else if (JgyUtils.getInstance().checkAppPlatform() == JgyUtils.ZhanruiPlatform) { // JgyUtils.getInstance().setJXWDefaultDesktop(); } else if (JgyUtils.getInstance().checkAppPlatform() == JgyUtils.AUDG104Platform || JgyUtils.getInstance().checkAppPlatform() == JgyUtils.G11JPlatform ) { JgyUtils.getInstance().setAiuduDefaultDesktop(); } else if (JgyUtils.getInstance().checkAppPlatform() == JgyUtils.MT6765Platform) { setDefaultDesktop(AlyOs, AlyOsClass); } } else { if (pkg.equalsIgnoreCase(desktopPkg)) { setDefaultDesktop(pkg); } else if (JgyUtils.getInstance().checkAppPlatform() == JgyUtils.MT6765Platform) { setDefaultDesktop(AlyOs, AlyOsClass); } } } /** * 获取默认的简易桌面,学习桌面或者默认应用桌面 * * @return */ public String getDefaultDesktop() { String defaultDesktop = mMMKV.decodeString(CommonConfig.DEFAULT_DESKTOP_PACKAGE_NAME, ""); String defaultLauncher = mMMKV.decodeString(CommonConfig.DEFAULT_LAUNCHER_PACKAGE_NAME, ""); Log.e(TAG, "getDefaultDesktop: defaultDesktop = " + defaultDesktop); Log.e(TAG, "getDefaultDesktop: defaultLauncher = " + defaultLauncher); if (TextUtils.isEmpty(defaultDesktop)) { if (TextUtils.isEmpty(defaultLauncher)) { return ""; } else { return defaultLauncher; } } else { return defaultDesktop; } } /** * 设置奥乐云桌面为默认 */ public void setDefaultDesktop() { Log.e(TAG, "setDefaultDesktop: "); setDefaultDesktop(PackageNames.DESKTOP); } public void setYxpDefaultDesktop() { Log.e(TAG, "setYxpDefaultDesktop: "); setDefaultDesktop(PackageNames.YIXUEPAI_DESKTOP); } public void setDop7DefaultDesktop() { Log.e(TAG, "setDop7DefaultDesktop: "); setDefaultDesktop("com.aoleyunos.dop7"); } public void setJXWDefaultDesktop() { Log.e(TAG, "setJXWDefaultDesktop: "); setDefaultDesktop("com.jxw.launcher"); } public void setAiuduDefaultDesktop() { Log.e(TAG, "setAiuduDefaultDesktop: "); // setDefaultDesktop("com.aoleyun.audos"); // setLauncher3(); setDefaultDesktop(Launcher3, Launcher3QuickstepClass); } /** * 设置默认桌面 * * @param pkg */ public void setDefaultDesktop(String pkg) { Log.e(TAG, "setDefaultDesktop: pkg = " + pkg); if (TextUtils.isEmpty(pkg)) { setLauncher3(); } else { String className = getStartClassName(pkg); Log.e(TAG, "setDefaultDesktop: className = " + className); if (TextUtils.isEmpty(className)) { setLauncher3(); } 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); } } public void setLauncher3() { if (ApkUtils.isAvailable(mContext, AoleyunOs) || "C2".equals(Build.MODEL)) { setDefaultDesktop(AoleyunOs, AoleyunOsClass); } else if (JgyUtils.getInstance().isAiuduPlatform()) { setDefaultDesktop(AiUDuOs, AiUDuOsClass); } else if (JgyUtils.isAllWinnerDevice()) { setDefaultDesktop(schoolosOs, schoolosClass); } else if (JgyUtils.getInstance().checkAppPlatform() == JgyUtils.MT6765Platform) { setDefaultDesktop(AlyOs, AlyOsClass); } else { if (Build.VERSION.SDK_INT > Build.VERSION_CODES.Q) { setDefaultDesktop(Launcher3, Launcher3QuickstepClass); } else { setDefaultDesktop(Launcher3, Launcher3Class); } } } public void openLauncher3() { if (ApkUtils.isAvailable(mContext, AoleyunOs) || "C2".equals(Build.MODEL)) { ApkUtils.openPackage(mContext, AoleyunOs, AoleyunOsClass); } else if (JgyUtils.getInstance().isAiuduPlatform()) { ApkUtils.openPackage(mContext, AiUDuOs, AiUDuOsClass); } else if (JgyUtils.isAllWinnerDevice()) { ApkUtils.openPackage(mContext, schoolosOs, schoolosClass); } else if (JgyUtils.getInstance().checkAppPlatform() == JgyUtils.MT6765Platform) { ApkUtils.openPackage(mContext, AlyOs, AlyOsClass); } else { if (Build.VERSION.SDK_INT > Build.VERSION_CODES.Q) { ApkUtils.openPackage(mContext, Launcher3, Launcher3QuickstepClass); } else { ApkUtils.openPackage(mContext, 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 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) { Log.e(TAG, "setDefaultDesktop: pkg=" + pkg + " className=" + className); if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.Q) { setRoleHolderAsUser(mContext, pkg); Log.e(TAG, "setDefaultDesktop: setRoleHolderAsUser"); } else if (Build.VERSION.SDK_INT >= 31) { setDefaultLauncher(mContext, pkg, className); } else { //爱华设置,暂时屏蔽 // setDefaultLauncher(mContext, pkg, className); Log.e(TAG, "setDefaultDesktop: setDefaultLauncher: pkg = " + 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); if (JgyUtils.isAllWinnerDevice()) { if (!ApkUtils.isAvailable(mContext, pkg)) { Log.e(TAG, "cubeMdmManager setDefaultLauncher: " + pkg + " is not installed"); return; } AllwinnerCubeMdmManager.getInstance().setDefaultLauncher(pkg); } // 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")); Log.e(TAG, "setDefaultDesktop: getDefaultLaunchers = " + getDefaultLaunchers()); setDefaultLauncher(new ComponentName(pkg, className)); } public Set getDefaultLaunchers() { Set defaultLaunchers = new HashSet(); PackageManager packageManager = mContext.getPackageManager(); Intent intent = new Intent(Intent.ACTION_MAIN); intent.addCategory(Intent.CATEGORY_HOME); // 查询所有已安装的桌面应用 List launcherList = packageManager.queryIntentActivities(intent, PackageManager.MATCH_DEFAULT_ONLY); // 获取默认的桌面应用,没有指定默认桌面时返回"android" ResolveInfo defaultLauncher = packageManager.resolveActivity(intent, PackageManager.MATCH_DEFAULT_ONLY); if (launcherList != null && defaultLauncher != null) { String pkgName = defaultLauncher.activityInfo.packageName; Log.e("getDefaultLaunchers", "default launcher is : " + pkgName); // 没有指定默认桌面时返回的是"android",故这里过滤下防止"android"被添加到默认桌面列表中 for (ResolveInfo info : launcherList) { Log.e("getDefaultLaunchers", "launcher : " + info.activityInfo.packageName); if (info.activityInfo.packageName.equals(pkgName)) { defaultLaunchers.add(pkgName); } } } // 有多个桌面应用,且目前没有指定默认桌面时,返回所有的桌面应用 if (defaultLaunchers.isEmpty() && launcherList != null) { for (ResolveInfo resolveInfo : launcherList) { defaultLaunchers.add(resolveInfo.activityInfo.packageName); } } Log.e("getDefaultLaunchers", "defaultLaunchers : " + defaultLaunchers); return defaultLaunchers; } 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", PushServiceFactory.getCloudPushService().getDeviceId()); 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(mContext)); 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 getHidePackage() { String jsonString = cacheHelper.getAsString(UrlAddress.GET_HIDE_DESKTOPICON); //为 "" 是已经请求成功的 if (jsonString == null) { return new ArrayList<>(); } else { Gson gson = new Gson(); Type type = new TypeToken>() { }.getType(); List list = gson.fromJson(jsonString, type); if (list == null) { return new ArrayList<>(); } else { return list; } } } public List getDisablePackage() { List 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) { Toaster.show("摄像头已禁止使用"); return true; } break; case "com.android.dialer": if (Settings.System.getInt(crv, "qch_call_forbid", 0) == 1) { Toaster.show("电话已禁止使用"); return true; } break; case "com.android.gallery3d": if (Settings.System.getInt(crv, "qch_app_gallery", 1) == 1) { Toaster.show("图库已禁止使用"); return true; } break; case "com.android.documentsui": if (Settings.System.getInt(crv, "qch_app_filemanager", 1) == 1) { Toaster.show("文件已禁止使用"); return true; } break; case "com.android.deskclock": if (Settings.System.getInt(crv, "qch_app_deskclock", 0) == 1) { Toaster.show("时钟已禁止使用"); return true; } break; case "com.android.music": if (Settings.System.getInt(crv, "qch_app_music", 1) == 1) { Toaster.show("音乐已禁止使用"); return true; } break; case "com.android.soundrecorder": if (Settings.System.getInt(crv, "qch_app_soundrecorder", 1) == 1) { Toaster.show("录音机已禁止使用"); return true; } break; case "com.aoleyun.browser": case "com.android.browser": if (Settings.System.getInt(crv, "qch_app_browser", 1) == 1) { Toaster.show("浏览器已禁止使用"); return true; } break; case "com.android.messaging": case "com.android.mms": if (Settings.System.getInt(crv, "qch_app_sms", 1) == 1) { Toaster.show("短信已禁止使用"); return true; } break; default: return false; } return false; } 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.setPackage("com.aoleyun.info"); bootIntent.setComponent(new ComponentName(PACKAGE_NOTIFY, CLASS_NOTIFY)); mContext.sendBroadcast(bootIntent); // Intent intent = new Intent(); // intent.setComponent(new ComponentName("com.aoleyun.info", "com.aoleyun.info.service.main.MainService")); // intent.setPackage("com.aoleyun.info"); //// intent.setClassName("com.aoleyun.info", "com.aoleyun.info.service.main.MainService"); // try { // mContext.startService(intent); // } catch (Exception e) { // Log.e(TAG, "wakeUpNotify: " + e.getMessage()); // } } @Deprecated 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 isAihuaFramework() { 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 static boolean isAllWinnerDevice() { return JgyUtils.getInstance().checkAppPlatform() == U1302Platform; } public boolean isScreenOn() { PowerManager powerManager = (PowerManager) mContext.getSystemService(Context.POWER_SERVICE); boolean isScreenOn; // 使用新版本的 API,更准确 if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT_WATCH) { isScreenOn = powerManager.isInteractive(); } else { // 旧版本 API(已过时,但用于兼容低版本系统) isScreenOn = powerManager.isScreenOn(); } Log.e(TAG, "isScreenOn: " + isScreenOn); return isScreenOn; //true为打开,false为关闭 } private static final String CONNECTED_TIME_KEY = "connectedTimeKey"; private List connectedTime; private void initConnectedTimeCache() { String jsonString = cacheHelper.getAsString(CONNECTED_TIME_KEY); Gson gson = new Gson(); Type listType = new TypeToken>() { }.getType(); try { List longList = gson.fromJson(jsonString, listType); if (longList == null) { connectedTime = new ArrayList<>(); } else { connectedTime = longList; } } catch (Exception e) { Log.e(TAG, "initConnectedTimeCache: " + e.getMessage()); cacheHelper.remove(CONNECTED_TIME_KEY); connectedTime = new ArrayList<>(); } } public List 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 time) { if (time == null || time.size() == 0) { return; } List copy = new ArrayList<>(time); for (Long l : copy) { connectedTime.remove(l); } cacheHelper.put(CONNECTED_TIME_KEY, GsonUtils.toJSONString(connectedTime)); } public void installAdminApp(List 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>() { @Override public void subscribe(@NonNull ObservableEmitter> emitter) throws Throwable { HashMap 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 (ApkUtils.mJxwApp.contains(pkg)) { packageListMap.put(pkg, apkPath); } else { Log.e(TAG, "checkLocalAppInstall: skip: " + pkg + " fileName: " + fileName); } } emitter.onNext(packageListMap); emitter.onComplete(); } }).subscribe(new Observer>() { @Override public void onSubscribe(@NonNull Disposable d) { Log.e("checkLocalAppInstall", "onSubscribe: "); } @Override public void onNext(@NonNull HashMap stringStringHashMap) { Log.e("checkLocalAppInstall", "onNext: " + stringStringHashMap); stringStringHashMap.forEach(new BiConsumer() { @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); } }); } } public static boolean isUnlocked(Context context) { int locked = Settings.System.getInt(context.getContentResolver(), JGYActions.ACTION_QCH_UNLOCK_IPAD, JGYActions.FRAME_CODE_LOCKED); return locked == JGYActions.FRAME_CODE_UNLOCKED; } /** * 启用/禁用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:白名单模式 **/ public 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 包名列表 **/ public void addAppInstallWhiteList(List packageNameList) { if (C2Tag.equals(BuildConfig.platform)) { Log.e("ITools", "addAppInstallWhiteList: " + packageNameList); try { if (mITools != null) { mITools.addAppInstallWhiteList(packageNameList); } } catch (RemoteException e) { e.printStackTrace(); } } } /** * No. 34 * 删除安装白名单列表 * * @param packageNameList 包名列表 **/ void delAppInstallWhiteList(List 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(); } } } public void setTongyiAppTop() { if (ApkUtils.isAvailable(mContext, "com.tongyi.aistudent")) { ForegroundAppUtil.setTopAppClass(mContext, "com.tongyi.aistudent"); Settings.Global.putString(crv, ForegroundAppUtil.TOPAPP_KEY, "com.tongyi.aistudent"); ForegroundAppUtil.openTopApp(mContext); } } public void refresh() { String jsonString = mMMKV.decodeString(CommonConfig.CLOUD_LESSON_SETTINGS_KEY); if (!TextUtils.isEmpty(jsonString)) { Gson gson = new Gson(); Type type = new TypeToken() { }.getType(); LessonJson lessonJson = gson.fromJson(jsonString, type); if (lessonJson != null) { this.mLessonJson = lessonJson; TimeUtils.ContralTime contralTime = TimeUtils.getContralTime(mContext, lessonJson.getStart_time(), lessonJson.getEnd_time()); if (contralTime != null) { mContralTime = contralTime; } } } } /** * @param pkg * @return true为能打开 */ public boolean isCloudLessonMod(String pkg) { if (JgyUtils.getInstance().isForbid(pkg)) { return false; } if (ApkUtils.isSystemApp(mContext, pkg)) { Log.e(TAG, "isCloudLessonMod: is system app"); return true; } if (ApkUtils.mJxwApp.contains(pkg)) { return true; } if (mLessonJson == null) return true; if (mLessonJson.getIs_lesson() == 1) { if (mContralTime == null) { return false; } else { String pkgs = mLessonJson.getPkgs(); if (mContralTime.inControlTime()) { return pkgs.contains(pkg); } else { Toaster.show("专注模式只允许使用指定应用"); return false; } } } else { return true; } } public String getAppName(String pkg) { PackageManager pm = mContext.getPackageManager(); PackageInfo info = null; try { info = pm.getPackageInfo(pkg, 0); } catch (PackageManager.NameNotFoundException e) { e.printStackTrace(); } if (info == null) { return "未知"; } else { return info.applicationInfo.loadLabel(pm).toString(); } } /** * @param pkg * @return */ public boolean isHidedApp(String pkg) { String appString = Settings.Global.getString(mContext.getContentResolver(), CommonConfig.AOLE_ACTION_DISABLE_APP); if (TextUtils.isEmpty(appString)) { return true; } else { List pkgs = new ArrayList<>(Arrays.asList(appString.split(","))); return pkgs.contains(pkg); } } public void setWallpaper(String url) { String oldUrl = mMMKV.decodeString(CommonConfig.WALLPAPER_URL_KEY, ""); if (oldUrl.equals(url)) { Log.e(TAG, "setWallpaper: Already set"); return; } // Bitmap bitmap = BitmapFactory.decodeFile(path); //利用WallpaparManager,添加权限set_wallpaper WallpaperManager wallpaperManager = WallpaperManager.getInstance(mContext); // // 获取当前壁纸(非缩略图) // Drawable drawable = wallpaperManager.getDrawable(); // // 获取当前壁纸的缩略图 // Bitmap bitmap = wallpaperManager.getBitmap(); // // 获取当前壁纸的尺寸 // int width = wallpaperManager.getDesiredMinimumWidth(); // int height = wallpaperManager.getDesiredMinimumHeight(); Glide.with(mContext).asBitmap().load(url).into(new SimpleTarget() { @Override public void onResourceReady(@androidx.annotation.NonNull Bitmap resource, @Nullable Transition transition) { try { wallpaperManager.setBitmap(resource); mMMKV.encode(CommonConfig.WALLPAPER_URL_KEY, url); Log.e("setWallpaper", "onResourceReady: set wallpaper Successful"); } catch (IOException e) { e.printStackTrace(); Log.e("setWallpaper", "onResourceReady: " + e.getMessage()); Log.e("setWallpaper", "onResourceReady: set wallpaper failed"); } } }); } public boolean isAiuduPlatform() { return checkAppPlatform() == G11JPlatform || "Aiud_A8_ag_1095".equals(Build.MODEL) || "G11J".equals(Build.MODEL); } public void checkAoleyunApp() { boolean availableSn = ApkUtils.isAvailable(mContext, "com.aoleyun.sn"); if (availableSn) { boolean disableSn = ApkUtils.isDisable(mContext, "com.aoleyun.sn"); Log.e(TAG, "checkAoleyunApp: sn isAvailable = " + availableSn); if (disableSn) { CmdUtil.Result installResult = CmdUtil.execute("cmd package install-existing com.aoleyun.sn"); Log.e(TAG, "checkAoleyunApp: sn install = " + installResult); CmdUtil.Result enableResult = CmdUtil.execute("pm enable com.aoleyun.sn"); Log.e(TAG, "checkAoleyunApp: sn enable = " + enableResult); } } else { CmdUtil.Result installResult = CmdUtil.execute("cmd package install-existing com.aoleyun.sn"); Log.e(TAG, "checkAoleyunApp: sn install = " + installResult); CmdUtil.Result enableResult = CmdUtil.execute("pm enable com.aoleyun.sn"); Log.e(TAG, "checkAoleyunApp: sn enable = " + enableResult); } // boolean availableAudos = ApkUtils.isAvailable(mContext, "com.aoleyun.audos"); // if (availableAudos) { // boolean disableAudos = ApkUtils.isDisable(mContext, "com.aoleyun.audos"); // Log.e(TAG, "checkAoleyunApp: audos isAvailable = " + availableAudos); // if (disableAudos) { // CmdUtil.Result installResult = CmdUtil.execute("cmd package install-existing com.aoleyun.audos"); // Log.e(TAG, "checkAoleyunApp: audos install = " + installResult); // CmdUtil.Result enableResult = CmdUtil.execute("pm enable com.aoleyun.audos"); // Log.e(TAG, "checkAoleyunApp: audos enable = " + enableResult); // } // } else { // CmdUtil.Result installResult = CmdUtil.execute("cmd package install-existing com.aoleyun.audos"); // Log.e(TAG, "checkAoleyunApp: audos install = " + installResult); // CmdUtil.Result enableResult = CmdUtil.execute("pm enable com.aoleyun.audos"); // Log.e(TAG, "checkAoleyunApp: audos enable = " + enableResult); // } boolean availableOs = ApkUtils.isAvailable(mContext, "com.aoleyun.os"); if (availableOs) { boolean disableOs = ApkUtils.isDisable(mContext, "com.aoleyun.os"); Log.e(TAG, "checkAoleyunApp: os isAvailable = " + availableOs); if (disableOs) { CmdUtil.Result installResult = CmdUtil.execute("cmd package install-existing com.aoleyun.os"); Log.e(TAG, "checkAoleyunApp: os install = " + installResult); CmdUtil.Result enableResult = CmdUtil.execute("pm enable com.aoleyun.os"); Log.e(TAG, "checkAoleyunApp: os enable = " + enableResult); } } else { CmdUtil.Result installResult = CmdUtil.execute("cmd package install-existing com.aoleyun.os"); Log.e(TAG, "checkAoleyunApp: os install = " + installResult); CmdUtil.Result enableResult = CmdUtil.execute("pm enable com.aoleyun.os"); Log.e(TAG, "checkAoleyunApp: os enable = " + enableResult); } boolean availableAppstore = ApkUtils.isAvailable(mContext, "com.aoleyun.appstore"); if (availableAppstore) { boolean disableAppstore = ApkUtils.isDisable(mContext, "com.aoleyun.appstore"); Log.e(TAG, "checkAoleyunApp: appstore isAvailable = " + availableAppstore); if (disableAppstore) { CmdUtil.Result installResult = CmdUtil.execute("cmd package install-existing com.aoleyun.appstore"); Log.e(TAG, "checkAoleyunApp: appstore install = " + installResult); CmdUtil.Result enableResult = CmdUtil.execute("pm enable com.aoleyun.appstore"); Log.e(TAG, "checkAoleyunApp: appstore enable = " + enableResult); } } else { CmdUtil.Result installResult = CmdUtil.execute("cmd package install-existing com.aoleyun.appstore"); Log.e(TAG, "checkAoleyunApp: appstore install = " + installResult); CmdUtil.Result enableResult = CmdUtil.execute("pm enable com.aoleyun.appstore"); Log.e(TAG, "checkAoleyunApp: appstore enable = " + enableResult); } } public void setAllwinnerDefaulInputMeth(String pkg) { if (!ApkUtils.isAvailable(mContext, pkg)) { Log.e(TAG, "cubeMdmManager setDefaultInputMethod: " + pkg + " is not installed"); return; } String componentName = JgyUtils.getInstance().getInputMethComponentName(pkg); Log.e(TAG, "setDefaultInputMethod: " + componentName); if (JgyUtils.isAllWinnerDevice()) { AllwinnerCubeMdmManager.getInstance().setDefaultInputMethod(componentName); } } public String getInputMethComponentName(String pkg) { InputMethodManager imeManager = (InputMethodManager) mContext.getSystemService(Context.INPUT_METHOD_SERVICE); List InputMethods = imeManager.getInputMethodList(); Optional inputMethodInfoOptional = InputMethods.stream().filter(new Predicate() { @Override public boolean test(InputMethodInfo inputMethodInfo) { return pkg.equals(inputMethodInfo.getPackageName()); } }).findAny(); if (inputMethodInfoOptional.isPresent()) { InputMethodInfo inputMethodInfo = inputMethodInfoOptional.get(); return inputMethodInfo.getComponent().toString(); } else { return ""; } } public String getDefaultIme() { return mMMKV.decodeString(CommonConfig.DEFAULT_IME_PACKAGE_NAME_KEY, ""); } public void setAllwinnerDefaulBrowser(String pkg) { if (JgyUtils.isAllWinnerDevice()) { if (!ApkUtils.isAvailable(mContext, pkg)) { Log.e(TAG, "cubeMdmManager setAllwinnerDefaulBrowser: " + pkg + " is not installed"); return; } Log.e(TAG, "setAllwinnerDefaulBrowser: " + pkg); if (JgyUtils.isAllWinnerDevice()) { AllwinnerCubeMdmManager.getInstance().setDefaultBrowser(pkg); } } } public List getAllRunningAppProcessInfo() { ActivityManager am = (ActivityManager) mContext.getSystemService(Context.ACTIVITY_SERVICE); PackageManager pm = mContext.getPackageManager(); List processes = am.getRunningAppProcesses(); List processList = new ArrayList<>(); for (ActivityManager.RunningAppProcessInfo process : processes) { String[] pkgList = process.pkgList; for (String pkg : pkgList) { try { ApplicationInfo appInfo = pm.getApplicationInfo(pkg, 0); processList.add(new ProcessInfo( pkg, appInfo.loadLabel(pm).toString(), process.pid, getProcessMemory(am, process.pid), (appInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0 )); } catch (Exception ignored) { } } } String jsonString = GsonUtils.toJSONString(processList); Log.e(TAG, "getAllRunningAppProcessInfo: " + jsonString); return processList; } // 获取进程内存占用(KB) private static long getProcessMemory(ActivityManager am, int pid) { Debug.MemoryInfo[] memoryInfo = am.getProcessMemoryInfo(new int[]{pid}); return memoryInfo[0].getTotalPss(); } public static class ProcessInfo { public String packageName, appName; public int pid; public long memory; public boolean isSystem; public ProcessInfo(String pkg, String name, int pid, long memory, boolean isSystem) { this.packageName = pkg; this.appName = name; this.pid = pid; this.memory = memory; this.isSystem = isSystem; } @androidx.annotation.NonNull @Override public String toString() { return JsonParser.parseString(new Gson().toJson(this)).getAsJsonObject().toString(); } } // 获取所有正在运行的服务 public List getAllRunningServices() { ActivityManager am = (ActivityManager) mContext.getSystemService(Context.ACTIVITY_SERVICE); List runningServices = am.getRunningServices(Integer.MAX_VALUE); List serviceList = new ArrayList<>(); for (ActivityManager.RunningServiceInfo service : runningServices) { serviceList.add(new ServiceInfo( service.service.getClassName(), service.service.getPackageName(), service.pid, service.uid )); } String jsonString = GsonUtils.toJSONString(serviceList); Log.e(TAG, "getAllRunningServices: " + jsonString); return serviceList; } public static class ServiceInfo { public String className, packageName; public int pid, uid; public ServiceInfo(String cls, String pkg, int pid, int uid) { this.className = cls; this.packageName = pkg; this.pid = pid; this.uid = uid; } @androidx.annotation.NonNull @Override public String toString() { return JsonParser.parseString(new Gson().toJson(this)).getAsJsonObject().toString(); } } }