refactor(app): 统一工具类并简化服务架构

- 移除 GuardService、StepService、ControlPanelService,替换为 SocketService
- 将 QR 码生成从 Utils 迁移到 BitmapUtils
- 将缓存目录选择逻辑统一到 FileUtils.getCacheFileDir
- 将 ServiceAliveUtils、NetStateUtils 合并到 SystemUtils
- 将 CacheUtils 同步清理替换为 ApkUtils.cleanApplicationUserDataAsync
- 用 EncryptUtils 替代自定义 MD5Util
- 重写 catchException 支持主线程兜底循环与子线程 Bugly 上报
- 移除 RunningAppManager 中未使用的 killBackgroundProcesses 方法
- 移除 ControlManager 中冗余的 hideSystemSettingAPP 调用
- MyGlideModule 重命名为 BaseGlideModule
This commit is contained in:
tongtong committed 2026-11-07 17:55:56 +08:00
1 parent df8a7bc153
commit a972ce7b89
46 files changed
+1583 -1812

No files matched your search

-2
View File
@@ -546,8 +546,6 @@ dependencies {
//Aria
implementation 'com.arialyy.aria:core:3.8.15'
annotationProcessor 'com.arialyy.aria:compiler:3.8.15'
//Java WebSocket
implementation "org.java-websocket:Java-WebSocket:1.5.3"
//MMKV
implementation 'com.tencent:mmkv-static:2.4.0'
//bugly
+7 -23
View File
@@ -119,9 +119,9 @@
</intent-filter>
</activity>
<!-- <activity-->
<!-- android:name=".activity.SplashActivity"-->
<!-- android:launchMode="singleTask" />-->
<!-- <activity-->
<!-- android:name=".activity.SplashActivity"-->
<!-- android:launchMode="singleTask" />-->
<activity
android:name=".activity.update.UpdateActivity"
android:launchMode="singleTask"
@@ -130,11 +130,6 @@
android:name=".activity.usage.UsageDetailActivity"
android:launchMode="singleTask" />
<service
android:name=".service.ControlPanelService"
android:enabled="true"
android:exported="true" />
<service
android:name=".service.RemoteService"
android:enabled="true"
@@ -149,23 +144,12 @@
android:enabled="true"
android:exported="true" />
<service android:name=".service.GuardService" />
<service android:name=".service.DownloadService" />
<service
android:name=".service.StepService"
android:exported="true">
<intent-filter android:priority="1000">
<action android:name="android.intent.action.SCREEN_OFF" />
<action android:name="android.intent.action.SCREEN_ON" />
<action android:name="android.intent.action.BOOT_COMPLETED" />
<action android:name="android.intent.action.USER_PRESENT" />
<action android:name="android.intent.action.ACTION_SHUTDOWN" />
<action android:name="android.intent.action.FACTORY_RESET" />
<action android:name="android.intent.action.MASTER_CLEAR" />
<data android:scheme="package" />
</intent-filter>
</service>
<service
android:name=".service.SocketService"
android:exported="false" />
<service android:name=".service.ManagerService">
<intent-filter android:priority="1000">
<action android:name="android.intent.action.USER_PRESENT" />
@@ -16,6 +16,7 @@ import com.fuying.sn.sync.AppInventorySync;
import com.fuying.sn.sync.AppUpdateCoordinator;
import com.fuying.sn.sync.DeviceProfileSync;
import com.fuying.sn.sync.RequestCallbacks;
import com.fuying.sn.utils.BitmapUtils;
import com.fuying.sn.utils.CXAESUtil;
import com.fuying.sn.utils.Utils;
@@ -59,7 +60,7 @@ public class HomeViewModel extends BaseAndroidViewModel {
public void getQRCode() {
String encryptString = CXAESUtil.encrypt(CommonConfig.AES_KEY, Utils.getIMEI(getApplication()));
Log.e("getQRCode", "setImageAndText: " + encryptString);
Bitmap bitmap = Utils.createQRImage(encryptString, 400, 400);
Bitmap bitmap = BitmapUtils.createQRImage(encryptString, 400, 400);
mQRCodeData.setValue(bitmap);
}
@@ -40,11 +40,9 @@ import com.fuying.sn.fragment.dialog.RestartFragment;
import com.fuying.sn.gson.GsonUtils;
import com.fuying.sn.manager.ControlManager;
import com.fuying.sn.manager.DeviceManager;
import com.fuying.sn.service.ControlPanelService;
import com.fuying.sn.service.DownloadService;
import com.fuying.sn.service.GuardService;
import com.fuying.sn.service.ManagerService;
import com.fuying.sn.service.StepService;
import com.fuying.sn.service.SocketService;
import com.fuying.sn.service.main.MainService;
import com.fuying.sn.sync.AppUpdateCoordinator;
import com.fuying.sn.utils.JgyUtils;
@@ -394,11 +392,9 @@ public class MainActivity extends BaseMvvmActivity<MainViewModel, ActivityMainBi
private void startService() {
startService(new Intent(this, MainService.class));
startService(new Intent(this, GuardService.class));
startService(new Intent(this, StepService.class));
startService(new Intent(this, SocketService.class));
startService(new Intent(this, DownloadService.class));
startService(new Intent(this, ManagerService.class));
startService(new Intent(this, ControlPanelService.class));
}
private void registerReceiver() {
@@ -17,6 +17,7 @@ import com.fuying.sn.sync.AppInventorySync;
import com.fuying.sn.sync.AppUpdateCoordinator;
import com.fuying.sn.sync.DeviceProfileSync;
import com.fuying.sn.sync.RequestCallbacks;
import com.fuying.sn.utils.BitmapUtils;
import com.fuying.sn.utils.CXAESUtil;
import com.fuying.sn.utils.Utils;
@@ -65,7 +66,7 @@ public class MainViewModel extends BaseAndroidViewModel {
public void getQRCode() {
String encryptString = CXAESUtil.encrypt(CommonConfig.AES_KEY, Utils.getIMEI(getAppContext()));
Log.e("getQRCode", "setImageAndText: " + encryptString);
Bitmap bitmap = Utils.createQRImage(encryptString, 400, 400);
Bitmap bitmap = BitmapUtils.createQRImage(encryptString, 400, 400);
mQRCodeData.setValue(bitmap);
}
@@ -24,11 +24,9 @@ import com.fuying.sn.manager.DeviceManager;
import com.fuying.sn.manager.time.TimeManager;
import com.fuying.sn.push.PushManager;
import com.fuying.sn.rlog.LogDBManager;
import com.fuying.sn.service.ControlPanelService;
import com.fuying.sn.service.DownloadService;
import com.fuying.sn.service.GuardService;
import com.fuying.sn.service.ManagerService;
import com.fuying.sn.service.StepService;
import com.fuying.sn.service.SocketService;
import com.fuying.sn.service.main.MainService;
import com.fuying.sn.sync.AppInventorySync;
import com.fuying.sn.sync.AppPolicySync;
@@ -51,6 +49,15 @@ import com.tencent.mmkv.MMKV;
public class BaseApplication extends Application {
private static final String TAG = "BaseApplication";
/**
* 兜底循环内允许的连续主线程异常次数,超过后交回默认处理器重启进程
*/
private static final int MAX_CONTINUOUS_CRASH = 5;
/**
* 两次主线程异常超过该间隔(毫秒)就重新计数,避免偶发异常被累计成连续崩溃
*/
private static final long CRASH_RESET_INTERVAL = 30_000L;
/**
* ViewModel中因为经常旋转导致弱引用为空
*/
@@ -68,7 +75,6 @@ public class BaseApplication extends Application {
//非主进程不初始化
if (SystemUtils.isMainProcessName(this, android.os.Process.myPid())) {
if (BuildConfig.DEBUG) {
// ApkUtils.openApp(this, "com.android.settings");
//静音
// AudioManager audioManager = (AudioManager) getSystemService(Context.AUDIO_SERVICE);
// int ringMax = audioManager.getStreamMinVolumeInt(AudioManager.STREAM_RING);
@@ -87,9 +93,6 @@ public class BaseApplication extends Application {
}
private void utilsInint() {
if (!BuildConfig.DEBUG) {
catchException();
}
String rootDir = MMKV.initialize(this);
Log.i(TAG, "mmkv root: " + rootDir);
@@ -100,6 +103,10 @@ public class BaseApplication extends Application {
JgyUtils.init(this);
CrashReport.initCrashReport(getApplicationContext(), "e5f026c8d5", false);
CrashReport.setDeviceId(this, Utils.getSerial());
if (!BuildConfig.DEBUG) {
// Bugly 先接管默认异常处理器,兜底处理器才能把子线程异常继续传递给它完成上报
catchException();
}
LogDBManager.init(this);
Aria.init(this);
@@ -141,40 +148,80 @@ public class BaseApplication extends Application {
private void startService() {
startService(new Intent(this, MainService.class));
startService(new Intent(this, GuardService.class));
startService(new Intent(this, StepService.class));
startService(new Intent(this, SocketService.class));
startService(new Intent(this, DownloadService.class));
startService(new Intent(this, ManagerService.class));
startService(new Intent(this, ControlPanelService.class));
}
/**
* 线上崩溃兜底:主线程单次异常只记录并继续分发消息,避免常驻进程被一次异常打断;
* 子线程异常继续交给原有处理器(Bugly),保证崩溃能正常上报。
*/
private void catchException() {
Thread.setDefaultUncaughtExceptionHandler(
new Thread.UncaughtExceptionHandler() {
@Override
public void uncaughtException(Thread t, Throwable e) {
Log.e("捕获异常子线程:", Thread.currentThread().getName() +
"在:" + e.getStackTrace()[0].getClassName());
}
final Thread.UncaughtExceptionHandler originHandler =
Thread.getDefaultUncaughtExceptionHandler();
Thread.setDefaultUncaughtExceptionHandler(new Thread.UncaughtExceptionHandler() {
@Override
public void uncaughtException(Thread t, Throwable e) {
logCrash("子线程", t, e);
if (originHandler != null) {
// 不吞掉异常:默认处理器里是 Bugly 的上报与系统退出逻辑
originHandler.uncaughtException(t, e);
} else {
Log.e(TAG, "catchException: 默认异常处理器为空,子线程崩溃无法上报");
}
);
//下面是新增方法!
}
});
// 主线程消息分发的异常会冒泡出 Looper.loop() 直接结束进程,用嵌套循环拦下来单独记录
new Handler(Looper.getMainLooper()).post(new Runnable() {
@Override
public void run() {
int crashCount = 0;
long lastCrashTime = 0L;
while (true) {
try {
Looper.loop(); //会先执行这个方法,然后在执行下面的异常捕获方法!
} catch (Exception e) {
Log.e("捕获异常主线程:", Thread.currentThread().getName() +
"在:" + e.getStackTrace()[0].getClassName());
e.printStackTrace();
Looper.loop(); // 接管主线程消息分发,消息里抛出的异常会落到下面的 catch
} catch (Throwable e) {
long now = System.currentTimeMillis();
if (now - lastCrashTime > CRASH_RESET_INTERVAL) {
crashCount = 0;
}
lastCrashTime = now;
crashCount++;
logCrash("主线程", Thread.currentThread(), e);
if (e instanceof Error || crashCount >= MAX_CONTINUOUS_CRASH) {
// Error 不可恢复、或短时间内反复崩溃说明进程状态已不可信,
// 交回默认处理器让系统按 START_STICKY 重新拉起,不再继续兜底
Log.e(TAG, "catchException: 主线程连续异常次数=" + crashCount);
if (originHandler != null) {
originHandler.uncaughtException(Thread.currentThread(), e);
return;
}
throw new RuntimeException("默认异常处理器为空", e);
}
reportCatchedException(e);
}
}
}
});
}
private void logCrash(String source, Thread thread, Throwable e) {
// 直接取 getStackTrace()[0] 在堆栈为空时会在异常处理里二次崩溃,这里取完整堆栈
Log.e(TAG, "logCrash: " + source + " thread=" + thread.getName()
+ " 在:" + Log.getStackTraceString(e));
}
private void reportCatchedException(Throwable e) {
try {
// 被兜底拦下的异常不会经过 Bugly 的 UncaughtExceptionHandler,必须主动上报
CrashReport.postCatchedException(e);
} catch (Throwable reportError) {
Log.e(TAG, "reportCatchedException: 崩溃上报失败 "
+ Log.getStackTraceString(reportError));
}
}
private void aliyunPushInit() {
// PushInitConfig pushInitConfig = new PushInitConfig.Builder()
// .application(this)
@@ -18,7 +18,6 @@ import android.content.pm.PackageManager;
import android.content.pm.ResolveInfo;
import android.content.pm.UserInfo;
import android.os.Build;
import android.os.PowerManager;
import android.os.RemoteException;
import android.provider.Settings;
import android.text.TextUtils;
@@ -43,12 +42,12 @@ import com.fuying.sn.sync.RequestCallbacks;
import com.fuying.sn.sync.TimePolicySync;
import com.fuying.sn.utils.AppUsedTimeUtils;
import com.fuying.sn.utils.JgyUtils;
import com.fuying.sn.utils.SystemUtils;
import com.fuying.sn.utils.ToastUtil;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import com.tencent.mmkv.MMKV;
import java.lang.reflect.Method;
import java.lang.reflect.Type;
import java.text.DateFormat;
import java.text.ParseException;
@@ -152,7 +151,7 @@ public class RunningAppManager {
}
public static void init(Context context) {
Log.e(TAG, "init: " );
Log.e(TAG, "init: ");
if (sInstance == null) {
sInstance = new RunningAppManager(context);
}
@@ -175,12 +174,6 @@ public class RunningAppManager {
.subscribe(new Consumer<Long>() {
@Override
public void accept(Long aLong) throws Throwable {
// Log.i(TAG, "accept: " + aLong);
PowerManager pm = (PowerManager) mContext.getSystemService(Context.POWER_SERVICE);
boolean isScreenOn = pm.isScreenOn();
// if (!isScreenOn) {
// return;
// }
checkForegroundAppName();
}
});
@@ -198,7 +191,7 @@ public class RunningAppManager {
Log.d(TAG, "checkForegroundAppName: topPackage = " + topPackage);
Log.d(TAG, "checkForegroundAppName: appPackageName = " + appPackageName);
if (!JgyUtils.getInstance().isScreenOn()) {
if (!SystemUtils.isScreenOn(mContext)) {
Log.d(TAG, "checkForegroundAppName: isScreenOn = false");
if (!TextUtils.isEmpty(appPackageName)) {
Log.d(TAG, "checkForegroundAppName: isEmpty = false");
@@ -389,29 +382,6 @@ public class RunningAppManager {
});
}
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();
}
}
/**
* 清除所有最近记录
*/
@@ -3,9 +3,9 @@ package com.fuying.sn.disklrucache;
import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.drawable.Drawable;
import android.os.Environment;
import android.util.Log;
import com.fuying.sn.utils.FileUtils;
import com.jakewharton.disklrucache.DiskLruCache;
import org.json.JSONArray;
@@ -460,17 +460,8 @@ public class CacheHelper {
// =======================================
private File getDiskCacheDir(Context context, String uniqueName) {
File cacheDir;
if (Environment.MEDIA_MOUNTED.equals(Environment.getExternalStorageState())
|| !Environment.isExternalStorageRemovable()) {
cacheDir = context.getExternalCacheDir();
if (cacheDir == null) {
cacheDir = context.getCacheDir();
}
} else {
cacheDir = context.getCacheDir();
}
return new File(cacheDir, uniqueName);
// 与 FileUtils 共用同一套缓存目录选择逻辑,避免两处判定不一致
return new File(FileUtils.getCacheFileDir(context), uniqueName);
}
}
@@ -2,17 +2,17 @@ package com.fuying.sn.fragment;
import android.graphics.Bitmap;
import android.os.Bundle;
import androidx.fragment.app.Fragment;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import androidx.fragment.app.Fragment;
import com.fuying.sn.R;
import com.fuying.sn.config.CommonConfig;
import com.fuying.sn.utils.BitmapUtils;
import com.fuying.sn.utils.CXAESUtil;
import com.fuying.sn.utils.Utils;
@@ -72,7 +72,7 @@ public class QRCodeFragment extends Fragment {
qr_code =mView.findViewById(R.id.qr_code);
try {
String encryptString = CXAESUtil.encrypt(CommonConfig.AES_KEY, Utils.getSerial());
Bitmap bitmap = Utils.createQRImage(encryptString, 300, 300);
Bitmap bitmap = BitmapUtils.createQRImage(encryptString, 300, 300);
qr_code.setImageBitmap(bitmap);
} catch (Exception e) {
Log.e(TAG, "onCreate: " + e.getMessage());
@@ -6,13 +6,15 @@ import com.bumptech.glide.GlideBuilder;
import com.bumptech.glide.annotation.GlideModule;
import com.bumptech.glide.load.engine.cache.DiskLruCacheFactory;
import com.bumptech.glide.module.AppGlideModule;
import com.fuying.sn.utils.StorageUtils;
import com.fuying.sn.utils.FileUtils;
import java.io.File;
/**
* Created by Administrator on 2017/2/9.
*/
@GlideModule
public class MyGlideModule extends AppGlideModule {
public class BaseGlideModule extends AppGlideModule {
@Override
public void applyOptions(final Context context, GlideBuilder builder) {
// 设置图片的显示格式 低内存时降低图片质量
@@ -24,16 +26,17 @@ public class MyGlideModule extends AppGlideModule {
// }
// builder.setDecodeFormat(DecodeFormat.PREFER_RGB_565);
//设置磁盘缓存目录(和创建的缓存目录相同)
String downloadDirectoryPath = StorageUtils.getFileCache(context, "imageCache");
String downloadDirectoryPath = new File(FileUtils.getCacheFileDir(context), "imageCache").getPath();
//设置缓存的大小为100M
int cacheSize = 100 * 1024 * 1024;
builder.setDiskCache(
new DiskLruCacheFactory(downloadDirectoryPath, cacheSize));
builder.setDiskCache(new DiskLruCacheFactory(downloadDirectoryPath, cacheSize));
}
/**
* 清单解析的开启
*
* <p>
* 这里不开启,避免添加相同的modules两次
*
* @return
*/
@Override
@@ -5,7 +5,6 @@ import android.bluetooth.BluetoothAdapter;
import android.content.ContentResolver;
import android.content.Context;
import android.content.Intent;
import android.os.Build;
import android.provider.Settings;
import android.text.TextUtils;
import android.util.Log;
@@ -14,17 +13,11 @@ import com.fuying.sn.BuildConfig;
import com.fuying.sn.bean.SystemSettings;
import com.fuying.sn.config.CommonConfig;
import com.fuying.sn.gson.GsonUtils;
import com.fuying.sn.utils.ApkUtils;
import com.fuying.sn.utils.JgyUtils;
import com.fuying.sn.utils.SPUtils;
import com.fuying.sn.utils.ToastUtil;
import com.google.gson.JsonObject;
import com.tencent.mmkv.MMKV;
import java.util.Arrays;
import java.util.HashSet;
import java.util.function.Predicate;
/**
* 系统管理处理
* 所有数据 后台1是0否,底层0是1否
@@ -132,7 +125,6 @@ public class ControlManager {
if (!DeviceManager.isDebugMode()) {
setDeveloperOptions(1);
}
// setSearchTopic(0);
}
/**
@@ -437,22 +429,18 @@ public class ControlManager {
//时钟
int deskclock = changeNum(settings.getSetting_clock());
Settings.System.putInt(mResolver, "qch_app_deskclock", deskclock);
ApkUtils.hideSystemSettingAPP(mContext, "com.android.deskclock");
Log.e("SystemSetting", "qch_app_deskclock:" + deskclock);
//录音机
int soundrecorder = changeNum(settings.getSetting_recording());
Settings.System.putInt(mResolver, "qch_app_soundrecorder", soundrecorder);
ApkUtils.hideSystemSettingAPP(mContext, "com.android.soundrecorder");
Log.e("SystemSetting", "qch_app_soundrecorder:" + soundrecorder);
//音乐
int music = changeNum(settings.getSetting_music());
Settings.System.putInt(mResolver, "qch_app_music", music);
ApkUtils.hideSystemSettingAPP(mContext, "com.android.music");
Log.e("SystemSetting", "qch_app_music:" + music);
//图库
int gallery = changeNum(settings.getSetting_picture());
Settings.System.putInt(mResolver, "qch_app_gallery", gallery);
ApkUtils.hideSystemSettingAPP(mContext, "com.android.gallery3d");
Log.e("SystemSetting", "qch_app_gallery:" + gallery);
//壁纸
int wallpaper = changeNum(settings.getSetting_wallpaper());
@@ -461,11 +449,6 @@ public class ControlManager {
//文件管理器
int filemanager = changeNum(settings.getSetting_file());
Settings.System.putInt(mResolver, "qch_app_filemanager", filemanager);
if (Build.VERSION.SDK_INT < Build.VERSION_CODES.O) {
ApkUtils.hideSystemSettingAPP(mContext, "com.mediatek.filemanager");
} else {
ApkUtils.hideSystemSettingAPP(mContext, "com.android.documentsui");
}
Log.e("SystemSetting", "qch_app_filemanager:" + filemanager);
//浏览器
int browser = changeNum(settings.getSetting_browser());
@@ -483,31 +466,22 @@ public class ControlManager {
//时钟
// int deskclock = 1;
Settings.System.putInt(mResolver, "qch_app_deskclock", state);
ApkUtils.hideSystemSettingAPP(mContext, "com.android.deskclock");
Log.e(TAG, "qch_app_deskclock" + state);
//录音机
// int soundrecorder = 1;
Settings.System.putInt(mResolver, "qch_app_soundrecorder", state);
ApkUtils.hideSystemSettingAPP(mContext, "com.android.soundrecorder");
Log.e(TAG, "qch_app_soundrecorder" + state);
//音乐
// int music = 1;
Settings.System.putInt(mResolver, "qch_app_music", state);
ApkUtils.hideSystemSettingAPP(mContext, "com.android.music");
Log.e(TAG, "qch_app_music" + state);
//图库
// int gallery = 1;
Settings.System.putInt(mResolver, "qch_app_gallery", state);
ApkUtils.hideSystemSettingAPP(mContext, "com.android.gallery3d");
Log.e(TAG, "qch_app_gallery" + state);
//文件管理器
// int filemanager = 1;
Settings.System.putInt(mResolver, "qch_app_filemanager", state);
if (Build.VERSION.SDK_INT < Build.VERSION_CODES.O) {
ApkUtils.hideSystemSettingAPP(mContext, "com.mediatek.filemanager");
} else {
ApkUtils.hideSystemSettingAPP(mContext, "com.android.documentsui");
}
Log.e(TAG, "qch_app_filemanager" + state);
//浏览器
Settings.System.putInt(mResolver, "qch_app_browser", state);
@@ -35,6 +35,7 @@ import com.fuying.sn.sync.AppUsageReporter;
import com.fuying.sn.utils.ApkUtils;
import com.fuying.sn.utils.AppUsedTimeUtils;
import com.fuying.sn.utils.JgyUtils;
import com.fuying.sn.utils.SystemUtils;
import com.hjq.toast.Toaster;
import java.time.DayOfWeek;
@@ -345,7 +346,7 @@ public class TimeManager {
.subscribeOn(Schedulers.io())
.observeOn(AndroidSchedulers.mainThread())
.subscribe(aLong -> {
if (JgyUtils.getInstance().isScreenOn()) {
if (SystemUtils.isScreenOn(mContext)) {
checkForegroundAppName();
}
}, throwable -> Log.e(TAG, "Interval task error: " + throwable.getMessage()));
@@ -1,9 +1,9 @@
package com.fuying.sn.network;
import android.content.Context;
import android.os.Environment;
import com.fuying.sn.BuildConfig;
import com.fuying.sn.utils.FileUtils;
import java.io.File;
import java.util.concurrent.TimeUnit;
@@ -36,7 +36,7 @@ public final class OkHttpManager {
logging.setLevel(HttpLoggingInterceptor.Level.BODY);
builder.addInterceptor(logging);
}
builder.cache(new Cache(new File(getCacheDir(context), "OkHttpCache"), CACHE_SIZE));
builder.cache(new Cache(new File(FileUtils.getCacheFileDir(context), "OkHttpCache"), CACHE_SIZE));
client = builder.build();
retrofit = new Retrofit.Builder()
.client(client)
@@ -50,21 +50,5 @@ public final class OkHttpManager {
return retrofit.create(api);
}
private static String getCacheDir(Context context) {
String cachePath;
if (Environment.MEDIA_MOUNTED.equals(Environment.getExternalStorageState())
|| !Environment.isExternalStorageRemovable()) {
if (context.getExternalCacheDir() != null) {
cachePath = context.getExternalCacheDir().getPath();
} else if (context.getExternalFilesDir("cache") != null) {
cachePath = context.getExternalFilesDir("cache").getPath();
} else {
cachePath = context.getCacheDir().getPath();
}
} else {
cachePath = context.getCacheDir().getPath();
}
return cachePath;
}
}
@@ -2,8 +2,8 @@ package com.fuying.sn.network.interceptor;
import android.util.Log;
import com.blankj.utilcode.util.EncryptUtils;
import com.fuying.sn.BuildConfig;
import com.fuying.sn.utils.MD5Util;
import org.jetbrains.annotations.NotNull;
@@ -173,7 +173,7 @@ public class RepeatRequestInterceptor implements Interceptor {
}
private static String buildRequestKey(Request request, String bodyText) {
return MD5Util.getUpperMD5Str(request.method() + "|" + request.url() + "|" + bodyText);
return EncryptUtils.encryptMD5ToString(request.method() + "|" + request.url() + "|" + bodyText);
}
/**
@@ -44,12 +44,11 @@ import com.fuying.sn.sync.DeviceSettingsSync;
import com.fuying.sn.sync.PushTagSync;
import com.fuying.sn.sync.RemoteDiagnostics;
import com.fuying.sn.utils.ApkUtils;
import com.fuying.sn.utils.CacheUtils;
import com.fuying.sn.utils.CmdUtil;
import com.fuying.sn.utils.FileUtils;
import com.fuying.sn.utils.JgyUtils;
import com.fuying.sn.utils.SPUtils;
import com.fuying.sn.utils.ServiceAliveUtils;
import com.fuying.sn.utils.SystemUtils;
import com.fuying.sn.utils.TimeUtils;
import com.fuying.sn.utils.ToastUtil;
import com.fuying.sn.utils.Utils;
@@ -600,17 +599,15 @@ public class PushManager {
private void setBrowserUrlPath() {
ToastUtil.debugShow("收到推送消息: 浏览器上网管控");
try {
new CacheUtils().cleanApplicationUserData(mContext, "com.android.browser");
} catch (Exception e) {
e.printStackTrace();
}
new Handler(Looper.getMainLooper()).postDelayed(new Runnable() {
@Override
public void run() {
BrowserPolicySync.getInstance().setBrowserWhiteList();
}
}, 2000);
ApkUtils.cleanApplicationUserDataAsync(mContext, "com.android.browser", succeeded -> {
//延时2秒执行,以防收到推送数据库还没有生效;清理完成后再同步,避免白名单被清掉
new Handler(Looper.getMainLooper()).postDelayed(new Runnable() {
@Override
public void run() {
BrowserPolicySync.getInstance().setBrowserWhiteList();
}
}, 2000);
});
}
private void setAppNetworkState() {
@@ -780,19 +777,16 @@ public class PushManager {
private void setBrowserLabel() {
ToastUtil.debugShow("收到推送消息: 浏览器书签");
try {
new CacheUtils().cleanApplicationUserData(mContext, "com.android.browser");
} catch (Exception e) {
e.printStackTrace();
}
//延时2秒执行,以防收到推送数据库还没有生效
new Handler(Looper.getMainLooper()).postDelayed(new Runnable() {
@Override
public void run() {
BrowserPolicySync.getInstance().getBrowserWhiteList();
BrowserPolicySync.getInstance().getBrowserLabel();
}
}, 2000);
ApkUtils.cleanApplicationUserDataAsync(mContext, "com.android.browser", succeeded -> {
//延时2秒执行,以防收到推送数据库还没有生效;清理完成后再同步,避免书签被清掉
new Handler(Looper.getMainLooper()).postDelayed(new Runnable() {
@Override
public void run() {
BrowserPolicySync.getInstance().getBrowserWhiteList();
BrowserPolicySync.getInstance().getBrowserLabel();
}
}, 2000);
});
}
private void setAppNetworkAuto() {
@@ -890,12 +884,7 @@ public class PushManager {
Log.e(TAG, "cleanAppCache: pkg is null");
return;
}
try {
new CacheUtils().cleanApplicationUserData(mContext, pkg);
} catch (Exception e) {
e.printStackTrace();
Log.e(TAG, "cleanAppCache: " + e.getMessage());
}
ApkUtils.cleanApplicationUserDataAsync(mContext, pkg, null);
}
private void handleSystemAppPush() {
@@ -1123,7 +1112,7 @@ public class PushManager {
}
private void recordLog(String jsonString) {
if (!ServiceAliveUtils.isServiceAlive(mContext, LogcatService.class.getName())) {
if (!SystemUtils.isServiceAlive(mContext, LogcatService.class.getName())) {
mContext.startService(new Intent(mContext, LogcatService.class));
}
RemoteDiagnostics.getInstance().getRunLog();
@@ -1259,7 +1248,7 @@ public class PushManager {
DeviceProfileSync.getInstance().updateAdminInfo();
AppInventorySync.getInstance().SendAppInstallInfo();
AppPolicySync.getInstance().getAppAndWhite();
if (JgyUtils.getInstance().isScreenOn()) {
if (SystemUtils.isScreenOn(mContext)) {
RemoteDiagnostics.getInstance().screenshot();
}
}
@@ -1494,7 +1483,6 @@ public class PushManager {
//摄像头开关
int setting_camera = changeNum(jsonObject.get("setting_camera").getAsInt());
Settings.System.putInt(mContext.getContentResolver(), "qch_app_camera", setting_camera);
ApkUtils.hideSystemSettingAPP(mContext, "com.mediatek.camera");
Log.e("SystemSetting", "setting_camera---------" + setting_camera);
String cameraStatus = "";
switch (setting_camera) {
@@ -1522,7 +1510,7 @@ public class PushManager {
JsonObject jSONObject = GsonUtils.getJsonObject(jsonString);
type = jSONObject.get("type").getAsInt();
if (!ServiceAliveUtils.isServiceAlive(mContext, ManagerService.class.getName())) {
if (!SystemUtils.isServiceAlive(mContext, ManagerService.class.getName())) {
mContext.startService(new Intent(mContext, ManagerService.class));
}
Intent intent = new Intent();
@@ -10,7 +10,7 @@ import android.util.Log;
import com.fuying.sn.config.CommonConfig;
import com.fuying.sn.manager.ControlManager;
import com.fuying.sn.manager.time.TimeManager;
import com.fuying.sn.utils.CacheUtils;
import com.fuying.sn.utils.ApkUtils;
import com.fuying.sn.utils.JgyUtils;
import com.fuying.sn.utils.SPUtils;
@@ -37,7 +37,6 @@ public class ApkInstallReceiver extends BroadcastReceiver {
mContext = context;
// 读取安装、卸载或覆盖安装广播的动作。
String action = intent.getAction();
// ApkUtils.addShortcut(context);
JgyUtils.getInstance().cleanLauncherCache();
ControlManager.getInstance().setDefaultApp();
Log.e(TAG, "onReceive: " + "action = " + action);
@@ -76,12 +75,7 @@ public class ApkInstallReceiver extends BroadcastReceiver {
}
private void cleanLauncher3Cache() {
try {
new CacheUtils().cleanApplicationUserData(mContext, "com.android.launcher3");
} catch (Exception e) {
Log.e(TAG, "onReceive: " + e.getMessage());
e.printStackTrace();
}
ApkUtils.cleanApplicationUserDataAsync(mContext, "com.android.launcher3", null);
}
public interface NewAppListener {
@@ -6,15 +6,12 @@ import android.content.Intent;
import android.util.Log;
import com.fuying.sn.config.CommonConfig;
import com.fuying.sn.service.ControlPanelService;
import com.fuying.sn.service.DownloadService;
import com.fuying.sn.service.GuardService;
import com.fuying.sn.service.ManagerService;
import com.fuying.sn.service.StepService;
import com.fuying.sn.service.SocketService;
import com.fuying.sn.service.main.MainService;
import com.tencent.mmkv.MMKV;
public class
BootReceiver extends BroadcastReceiver {
private static final String TAG = "BootReceiver";
@@ -31,11 +28,9 @@ BootReceiver extends BroadcastReceiver {
case BOOT_COMPLETED:
case "android.intent.action.BATTERY_LEVEL_CHANGED":
context.startService(new Intent(context, MainService.class));
context.startService(new Intent(context, GuardService.class));
context.startService(new Intent(context, StepService.class));
context.startService(new Intent(context, SocketService.class));
context.startService(new Intent(context, DownloadService.class));
context.startService(new Intent(context, ManagerService.class));
context.startService(new Intent(context, ControlPanelService.class));
break;
default:
}
@@ -1,104 +0,0 @@
package com.fuying.sn.service;
import android.app.Service;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.hardware.usb.UsbManager;
import android.hardware.usb.UsbPortStatus;
import android.os.Bundle;
import android.os.IBinder;
import android.util.Log;
public class ControlPanelService extends Service {
private static final String TAG = "ControlPanelService";
public ControlPanelService() {
}
@Override
public IBinder onBind(Intent intent) {
return null;
}
@Override
public void onCreate() {
super.onCreate();
registerUsbConnectionReceiver();
}
@Override
public int onStartCommand(Intent intent, int flags, int startId) {
return super.onStartCommand(intent, flags, startId);
}
@Override
public void onDestroy() {
super.onDestroy();
}
private void registerUsbConnectionReceiver() {
if (mUsbConnectionReceiver == null) {
mUsbConnectionReceiver = new UsbConnectionReceiver();
}
IntentFilter filter = new IntentFilter();
filter.addAction(UsbManager.ACTION_USB_STATE);
filter.addAction(UsbManager.ACTION_USB_PORT_CHANGED);
registerReceiver(mUsbConnectionReceiver, filter);
}
UsbConnectionReceiver mUsbConnectionReceiver;
private boolean mConnected;
private long mFunctions;
// private int mDataRole;
// private int mPowerRole;
public class UsbConnectionReceiver extends BroadcastReceiver {
@Override
public void onReceive(Context context, Intent intent) {
Log.e(TAG, "onReceive: " + intent.getAction());
Bundle bundle = intent.getExtras();
if (UsbManager.ACTION_USB_STATE.equals(intent.getAction())) {
mConnected = intent.getExtras().getBoolean(UsbManager.USB_CONNECTED)
|| intent.getExtras().getBoolean(UsbManager.USB_HOST_CONNECTED);
long functions = UsbManager.FUNCTION_NONE;
if (intent.getExtras().getBoolean(UsbManager.USB_FUNCTION_MTP)
&& intent.getExtras().getBoolean(UsbManager.USB_DATA_UNLOCKED, false)) {
functions |= UsbManager.FUNCTION_MTP;
}
if (intent.getExtras().getBoolean(UsbManager.USB_FUNCTION_PTP)
&& intent.getExtras().getBoolean(UsbManager.USB_DATA_UNLOCKED, false)) {
functions |= UsbManager.FUNCTION_PTP;
}
if (intent.getExtras().getBoolean(UsbManager.USB_FUNCTION_MIDI)) {
functions |= UsbManager.FUNCTION_MIDI;
}
if (intent.getExtras().getBoolean(UsbManager.USB_FUNCTION_RNDIS)) {
functions |= UsbManager.FUNCTION_RNDIS;
}
if (intent.getExtras().getBoolean(UsbManager.USB_FUNCTION_ACCESSORY)) {
functions |= UsbManager.FUNCTION_ACCESSORY;
}
mFunctions = functions;
// mDataRole = mUsbBackend.getDataRole();
// mPowerRole = mUsbBackend.getPowerRole();
} else if (UsbManager.ACTION_USB_PORT_CHANGED.equals(intent.getAction())) {
UsbPortStatus portStatus = intent.getExtras()
.getParcelable(UsbManager.EXTRA_PORT_STATUS);
if (portStatus != null) {
// mDataRole = portStatus.getCurrentDataRole();
// mPowerRole = portStatus.getCurrentPowerRole();
}
}
// if (mUsbConnectionListener != null) {
// mUsbConnectionListener.onUsbConnectionChanged(mConnected, mFunctions, mPowerRole,
// mDataRole);
// }
}
}
}
@@ -1,7 +1,6 @@
package com.fuying.sn.service;
import android.app.AlertDialog;
import android.app.Service;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
@@ -41,11 +40,10 @@ public class DownloadService extends BaseService {
@Override
public int onStartCommand(Intent intent, int flags, int startId) {
startService(new Intent(this, StepService.class));
startService(new Intent(this, GuardService.class));
super.onStartCommand(intent, flags, startId);
startService(new Intent(this, SocketService.class));
startService(new Intent(this, MainService.class));
startService(new Intent(this, ManagerService.class));
startService(new Intent(this, ControlPanelService.class));
return START_STICKY;
}
@@ -59,6 +57,7 @@ public class DownloadService extends BaseService {
@Nullable
@Override
public IBinder onBind(Intent intent) {
super.onBind(intent);
return new KeepAliveConnection.Stub() {
};
}
@@ -1,66 +0,0 @@
package com.fuying.sn.service;
/**
* 作者 mjsheng
* 日期 2019/4/1 10:58
* 邮箱 501802639@qq.com
* 来自:
*/
import android.app.Service;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.ServiceConnection;
import android.os.IBinder;
import android.util.Log;
import androidx.annotation.Nullable;
import com.fuying.sn.KeepAliveConnection;
import com.fuying.sn.utils.ServiceAliveUtils;
/**
* 守护进程 双进程通讯
*
* @author LiGuangMin
* @time Created by 2018/8/17 11:27
*/
public class GuardService extends Service {
private static final String TAG = "GuardService";
private ServiceConnection mServiceConnection = new ServiceConnection() {
@Override
public void onServiceConnected(ComponentName componentName, IBinder iBinder) {
Log.e(TAG, "GuardService:建立链接");
boolean isServiceRunning = ServiceAliveUtils.isServiceAlive(GuardService.this, getClass().getName());
if (!isServiceRunning) {
Intent i = new Intent(GuardService.this, DownloadService.class);
startService(i);
}
}
@Override
public void onServiceDisconnected(ComponentName componentName) {
// 断开链接
startService(new Intent(GuardService.this, StepService.class));
// 重新绑定
bindService(new Intent(GuardService.this, StepService.class), mServiceConnection, Context.BIND_IMPORTANT);
}
};
@Nullable
@Override
public IBinder onBind(Intent intent) {
return new KeepAliveConnection.Stub() {
};
}
@Override
public int onStartCommand(Intent intent, int flags, int startId) {
// 绑定建立链接
bindService(new Intent(this, StepService.class), mServiceConnection, Context.BIND_IMPORTANT);
return START_STICKY;
}
}
@@ -45,11 +45,13 @@ public class LogcatService extends BaseService {
public IBinder onBind(Intent intent) {
// TODO: 如需支持绑定服务,在此返回通信接口;当前仅通过启动服务和广播控制。
// throw new UnsupportedOperationException("Not yet implemented");
super.onBind(intent);
return null;
}
@Override
public int onStartCommand(Intent intent, int flags, int startId) {
super.onStartCommand(intent, flags, startId);
return START_STICKY;
}
@@ -72,7 +72,6 @@ public class ManagerService extends BaseService implements NetworkUtils.OnNetwor
@Override
public void onConnected(NetworkUtils.NetworkType networkType) {
// getScreenLockState();
// 网络恢复后立即兜底刷新一次配置(推送可能在此期间丢失)
try {
PushManager.getInstance().triggerRefresh();
@@ -128,6 +127,7 @@ public class ManagerService extends BaseService implements NetworkUtils.OnNetwor
@Override
public IBinder onBind(Intent intent) {
super.onBind(intent);
return null;
}
@@ -137,10 +137,8 @@ public class ManagerService extends BaseService implements NetworkUtils.OnNetwor
NetworkUtils.registerNetworkStatusChangedListener(this);
registLockReceiver();
registerTimeReceiver();
registerScreenLockReceiver();
registAppReceive();
registBootReceive();
registerBatteryReceiver();
setFloatingWindow();
Observable.create(subscribe)
.throttleFirst(3, TimeUnit.HOURS)
@@ -149,6 +147,7 @@ public class ManagerService extends BaseService implements NetworkUtils.OnNetwor
@Override
public int onStartCommand(Intent intent, int flags, int startId) {
super.onStartCommand(intent, flags, startId);
start.onstar(System.currentTimeMillis());
return START_STICKY;
}
@@ -490,13 +489,6 @@ public class ManagerService extends BaseService implements NetworkUtils.OnNetwor
Log.e(TAG, "TimeChangedReceiver:" + "time tick");
setFloatingWindow();
}
// String packages = ForegroundAppUtil.getForegroundPackageName(context);
// if (!packages.equals("com.estrongs.android.pop")) {
// ApkUtils.openApp(context, "com.estrongs.android.pop");
// }
// Log.e("TimeChangedReceiver", "packages:" + packages);
}
}
@@ -511,50 +503,6 @@ public class ManagerService extends BaseService implements NetworkUtils.OnNetwor
setLockedState(is_screen_lock);
}
private ScreenLockReceiver screenLockReceiver;
private void registerScreenLockReceiver() {
if (null == screenLockReceiver) {
screenLockReceiver = new ScreenLockReceiver();
}
IntentFilter filter = new IntentFilter();
filter.setPriority(IntentFilter.SYSTEM_HIGH_PRIORITY);
filter.addAction(Intent.ACTION_SCREEN_OFF);
filter.addAction(Intent.ACTION_SCREEN_ON);
filter.addAction(Intent.ACTION_BOOT_COMPLETED);
filter.addAction(Intent.ACTION_USER_PRESENT);
filter.addAction(Intent.ACTION_SHUTDOWN);
filter.addAction(Intent.ACTION_FACTORY_RESET);
filter.addAction(Intent.ACTION_MASTER_CLEAR);
registerReceiver(screenLockReceiver, filter);
}
private class ScreenLockReceiver extends BroadcastReceiver {
@Override
public void onReceive(Context context, Intent intent) {
String action = intent.getAction();
Log.e(TAG, "onReceive:" + action);
if (TextUtils.isEmpty(action)) {
Log.e(TAG, "onReceive: is NULL");
return;
}
switch (action) {
case Intent.ACTION_USER_PRESENT:
case Intent.ACTION_SCREEN_ON:
// sendScreenState(1);
break;
case Intent.ACTION_SCREEN_OFF:
case Intent.ACTION_SHUTDOWN:
case Intent.ACTION_FACTORY_RESET:
case Intent.ACTION_MASTER_CLEAR:
// sendScreenState(0);
break;
default:
break;
}
}
}
private ApkInstallReceiver apKinstallReceiver;
private void registAppReceive() {
@@ -582,33 +530,6 @@ public class ManagerService extends BaseService implements NetworkUtils.OnNetwor
}
}
private BatteryReceiver batteryReceiver;
private void registerBatteryReceiver() {
if (null == batteryReceiver) {
batteryReceiver = new BatteryReceiver();
}
IntentFilter filter = new IntentFilter();
filter.setPriority(IntentFilter.SYSTEM_HIGH_PRIORITY);
filter.addAction(Intent.ACTION_POWER_DISCONNECTED);
registerReceiver(batteryReceiver, filter);
}
private class BatteryReceiver extends BroadcastReceiver {
@Override
public void onReceive(Context context, Intent intent) {
String action = intent.getAction();
if (Intent.ACTION_BATTERY_CHANGED.equals(action)) {
} else if (Intent.ACTION_POWER_CONNECTED.equals(action) || Intent.ACTION_POWER_DISCONNECTED.equals(action)) {
// ControlManager.getInstance().setDefaultUSBstate();
} else if (Intent.ACTION_BATTERY_LOW.equals(action) || Intent.ACTION_BATTERY_OKAY.equals(action)) {
}
}
}
@Override
public void onDestroy() {
mDisposables.dispose();
@@ -620,9 +541,6 @@ public class ManagerService extends BaseService implements NetworkUtils.OnNetwor
if (null != lockScreenReceiver) {
unregisterReceiver(lockScreenReceiver);
}
if (null != screenLockReceiver) {
unregisterReceiver(screenLockReceiver);
}
if (null != apKinstallReceiver) {
unregisterReceiver(apKinstallReceiver);
}
@@ -0,0 +1,453 @@
package com.fuying.sn.service;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.IBinder;
import android.text.TextUtils;
import android.util.Log;
import androidx.annotation.Nullable;
import androidx.lifecycle.Lifecycle;
import androidx.lifecycle.LifecycleEventObserver;
import androidx.lifecycle.LifecycleOwner;
import androidx.lifecycle.LifecycleService;
import com.blankj.utilcode.util.NetworkUtils;
import com.fuying.sn.utils.ReceiverCompat;
import com.fuying.sn.utils.SystemUtils;
import com.fuying.sn.utils.TimeUtils;
import com.fuying.sn.utils.Utils;
import com.google.gson.JsonObject;
import java.util.concurrent.TimeUnit;
import io.reactivex.rxjava3.android.schedulers.AndroidSchedulers;
import io.reactivex.rxjava3.core.Observable;
import io.reactivex.rxjava3.core.Single;
import io.reactivex.rxjava3.disposables.CompositeDisposable;
import io.reactivex.rxjava3.disposables.SerialDisposable;
import io.reactivex.rxjava3.schedulers.Schedulers;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;
import okhttp3.WebSocket;
import okhttp3.WebSocketListener;
/**
* 设备 WebSocket 长连接服务:用 OkHttp 建立连接,用 RxJava 驱动心跳、重连与错峰。
*
* <p>继承 {@link LifecycleService} 后,所有资源(订阅、广播、网络监听、WebSocket)都在
* Lifecycle 的 ON_CREATE 中创建、ON_DESTROY 中释放;流里还会检查 Lifecycle 状态,
* DESTROYED 之后不再有任何连接动作。不再依赖 Service 自身回调去手动管理生命周期。
*
* <p>连接状态(mConnecting / mOpened / mWebSocket)只在主线程读写:OkHttp 回调和网络
* 状态回调都先切回主线程,心跳流和错峰任务也通过 observeOn 回到主线程。这样建连、
* 关闭、失败回调天然串行,不会出现两个线程同时建连或状态互相覆盖。
*
* <p>连接时机沿用屏幕状态策略:亮屏广播触发重连,息屏广播主动断开并取消在途任务,
* 息屏后心跳流停止,不再重连。
*
* <p>这里不做进程保活:双进程 AIDL 互拉(GuardService / KeepAliveConnection)已移除,
* 服务只由 BaseApplication、BootReceiver、MainService 等入口显式启动。
*/
public class SocketService extends LifecycleService implements NetworkUtils.OnNetworkStatusChangedListener {
private static final String TAG = "SocketService";
private static final String SOCKET_URL = "wss://as.fuyingy.com/wss/device?sn=";
/**
* 恢复出厂与清除数据广播:Intent 没有公开常量,沿用固件约定的 action 字符串
*/
private static final String ACTION_FACTORY_RESET = "android.intent.action.FACTORY_RESET";
private static final String ACTION_MASTER_CLEAR = "android.intent.action.MASTER_CLEAR";
/**
* 正常关闭码与关闭原因
*/
private static final int CLOSE_CODE_NORMAL = 1000;
private static final String CLOSE_REASON = "客户端主动断开";
/**
* 心跳间隔,同时是断线重连的检查周期
*/
private static final long HEART_BEAT_RATE = 30 * 1000L;
/**
* 连接超时,WebSocket 是长连接,读超时必须为 0(不超时)
*/
private static final long CONNECT_TIMEOUT_SECONDS = 10L;
/**
* 网络恢复后的随机错峰区间,避免大批量设备在同一时刻连回服务端
*/
private static final long RECONNECT_JITTER_MIN = 0L;
private static final long RECONNECT_JITTER_MAX = 30 * 1000L;
/**
* 总容器:ON_DESTROY 一次 dispose,连带取消下面三个子容器里的所有订阅
*/
private final CompositeDisposable mDisposables = new CompositeDisposable();
/**
* 心跳流:stopHeartBeat 时 clear,亮屏后还能重新 add,不能用一次性 dispose
*/
private final CompositeDisposable mHeartBeatDisposables = new CompositeDisposable();
/**
* 建连任务:只保留最后一次,避免重复握手
*/
private final SerialDisposable mConnectDisposable = new SerialDisposable();
/**
* 错峰重连任务:后一次网络恢复覆盖前一次,天然去重
*/
private final SerialDisposable mReconnectDisposable = new SerialDisposable();
/**
* WebSocket 专用客户端:不能复用 Retrofit 的 OkHttpManager(它带缓存和 30s 读超时)
*/
private final OkHttpClient mWebSocketClient = new OkHttpClient.Builder()
.connectTimeout(CONNECT_TIMEOUT_SECONDS, TimeUnit.SECONDS)
.writeTimeout(CONNECT_TIMEOUT_SECONDS, TimeUnit.SECONDS)
.readTimeout(0, TimeUnit.MILLISECONDS)
.retryOnConnectionFailure(true)
.build();
/**
* 以下三个字段只在主线程读写,OkHttp 回调和网络回调都先 postToMain
*/
private boolean mConnecting;
private boolean mOpened;
private WebSocket mWebSocket;
private ScreenLockReceiver mScreenLockReceiver;
private final LifecycleEventObserver mLifecycleObserver = new LifecycleEventObserver() {
@Override
public void onStateChanged(LifecycleOwner source, Lifecycle.Event event) {
if (event == Lifecycle.Event.ON_CREATE) {
onServiceCreated();
} else if (event == Lifecycle.Event.ON_DESTROY) {
onServiceDestroyed();
}
}
};
private final WebSocketListener mWebSocketListener = new WebSocketListener() {
@Override
public void onOpen(WebSocket webSocket, Response response) {
postToMain(() -> {
// 不是当前连接说明建连期间已被主动断开(或已销毁),立刻取消掉,避免孤儿连接
if (isDestroyed() || mWebSocket != webSocket) {
webSocket.cancel();
Log.e(TAG, "onOpen: 连接已失效,取消本次连接");
return;
}
mOpened = true;
Log.e(TAG, "onOpen: websocket连接成功");
sendMsg(webSocket);
});
}
@Override
public void onMessage(WebSocket webSocket, String text) {
Log.e(TAG, "onMessage: " + text);
}
@Override
public void onClosing(WebSocket webSocket, int code, String reason) {
// OkHttp 要求收到服务端关闭帧后回一个 close,才能完成关闭握手
webSocket.close(code, reason);
}
@Override
public void onClosed(WebSocket webSocket, int code, String reason) {
Log.e(TAG, "onClosed: code = " + code + ", reason = " + reason);
postToMain(() -> clearIfCurrent(webSocket));
}
@Override
public void onFailure(WebSocket webSocket, Throwable t, Response response) {
Log.e(TAG, "onFailure: " + t);
postToMain(() -> clearIfCurrent(webSocket));
}
};
@Override
public void onCreate() {
super.onCreate();
// LifecycleService 在 onCreate 派发 ON_CREATE,这里注册观察者即可接管全部资源管理
getLifecycle().addObserver(mLifecycleObserver);
}
@Override
public int onStartCommand(Intent intent, int flags, int startId) {
super.onStartCommand(intent, flags, startId);
Log.e(TAG, "onStartCommand: startId = " + startId);
return START_STICKY;
}
@Nullable
@Override
public IBinder onBind(Intent intent) {
super.onBind(intent);
// 双进程保活的 AIDL 绑定已移除,本服务不再提供绑定能力
return null;
}
/**
* 把 OkHttp 回调和网络状态回调切回主线程,保证连接状态单点读写。
*/
private void postToMain(Runnable action) {
AndroidSchedulers.mainThread().scheduleDirect(action);
}
/**
* ON_CREATE:注册监听、启动心跳流,连接由心跳流的首个 tick 触发。
*/
private void onServiceCreated() {
mDisposables.add(mHeartBeatDisposables);
mDisposables.add(mConnectDisposable);
mDisposables.add(mReconnectDisposable);
NetworkUtils.registerNetworkStatusChangedListener(this);
registerScreenLockReceiver();
startHeartBeat();
Log.e(TAG, "onServiceCreated: 已启动websocket心跳流");
}
/**
* ON_DESTROY:取消所有 RxJava 订阅、注销监听与广播、关闭连接。
*/
private void onServiceDestroyed() {
mDisposables.dispose();
NetworkUtils.unregisterNetworkStatusChangedListener(this);
ReceiverCompat.unregisterReceiver(this, mScreenLockReceiver);
mScreenLockReceiver = null;
closeConnect();
Log.e(TAG, "onServiceDestroyed: 已释放websocket资源");
}
@Override
public void onDisconnected() {
Log.e(TAG, "onDisconnected: 网络断开,连接状态交给心跳流检测");
}
@Override
public void onConnected(NetworkUtils.NetworkType networkType) {
Log.e(TAG, "onConnected: " + networkType);
// 网络回调可能在 binder 线程,连接状态只允许在主线程读写
postToMain(() -> {
if (isDestroyed()) {
return;
}
if (!SystemUtils.isScreenOn(this)) {
Log.e(TAG, "onConnected: 息屏不重连");
stopHeartBeat();
return;
}
if (mWebSocket != null || mConnecting) {
return;
}
scheduleNetworkReconnect();
});
}
/**
* 心跳流:RxJava 定时驱动连接检查。每次亮屏都重建心跳流,新流从 0 开始会立即
* 检查一轮连接,同时保证始终只有一条流,不会叠加出多条心跳链。
*/
private void startHeartBeat() {
if (isDestroyed()) {
return;
}
mHeartBeatDisposables.clear();
mHeartBeatDisposables.add(Observable.interval(0, HEART_BEAT_RATE, TimeUnit.MILLISECONDS)
.subscribeOn(Schedulers.io())
.observeOn(AndroidSchedulers.mainThread())
.subscribe(tick -> checkConnection(),
throwable -> Log.e(TAG, "startHeartBeat: " + throwable)));
Log.e(TAG, "startHeartBeat: 已开启心跳检测");
}
private void stopHeartBeat() {
mHeartBeatDisposables.clear();
Log.e(TAG, "stopHeartBeat: 已停止心跳检测");
}
/**
* 取消排队中的建连任务与错峰重连 timer,避免息屏后仍有任务把连接建回来。
*/
private void cancelPendingConnect() {
mConnectDisposable.set(null);
mReconnectDisposable.set(null);
}
/**
* 一轮连接检查:息屏直接停流,握手中跳过,已连接则发 ping,否则重建连接。
*/
private void checkConnection() {
if (isDestroyed()) {
return;
}
// 息屏后不再重连,也不再等下一轮,等亮屏广播重新拉起心跳流
if (!SystemUtils.isScreenOn(this)) {
Log.e(TAG, "checkConnection: 息屏不重连");
stopHeartBeat();
return;
}
WebSocket current = mWebSocket;
if (current != null) {
if (!mOpened) {
Log.e(TAG, "checkConnection: 握手中,跳过本轮");
return;
}
if (sendMsg(current)) {
return;
}
Log.e(TAG, "checkConnection: ping发送失败,重建连接");
closeConnect();
}
connect();
}
/**
* 用 RxJava 在 IO 线程准备 Request,回到主线程后复查状态再发起 OkHttp 建连。
* newWebSocket 本身是异步的,在主线程调用既不会阻塞,也能让状态变更串行化。
*/
private void connect() {
if (isDestroyed() || !SystemUtils.isScreenOn(this) || mConnecting || mWebSocket != null) {
return;
}
mConnecting = true;
mConnectDisposable.set(Single.fromCallable(() -> new Request.Builder()
.url(SOCKET_URL + Utils.getSerial())
.build())
.subscribeOn(Schedulers.io())
.observeOn(AndroidSchedulers.mainThread())
.subscribe(request -> {
// 排队期间可能已经息屏、销毁或被主动断开,回主线程后必须再查一次
if (!canConnect()) {
mConnecting = false;
Log.e(TAG, "connect: 状态已变化,放弃本次建连");
return;
}
mConnecting = false;
mWebSocket = mWebSocketClient.newWebSocket(request, mWebSocketListener);
Log.e(TAG, "connect: 已发起websocket连接");
}, throwable -> {
mConnecting = false;
Log.e(TAG, "connect: 建连失败 " + throwable);
}));
}
private boolean canConnect() {
return !isDestroyed() && SystemUtils.isScreenOn(this) && mWebSocket == null;
}
/**
* 网络恢复是全量设备同时触发的事件,用带抖动的单次任务错峰后再检查连接。
*/
private void scheduleNetworkReconnect() {
if (isDestroyed()) {
return;
}
long delay = TimeUtils.randomDelay(RECONNECT_JITTER_MIN, RECONNECT_JITTER_MAX);
Log.e(TAG, "scheduleNetworkReconnect: 网络恢复, 错峰延时 = " + delay);
mReconnectDisposable.set(Observable.timer(delay, TimeUnit.MILLISECONDS)
.subscribeOn(Schedulers.io())
.observeOn(AndroidSchedulers.mainThread())
.subscribe(tick -> checkConnection(),
throwable -> Log.e(TAG, "scheduleNetworkReconnect: " + throwable)));
}
/**
* 连接关闭或失败:只清理属于当前连接的回调,旧连接迟到的回调不能影响新连接;
* 不在这里直接重连,统一由心跳流按屏幕状态决定。
*/
private void clearIfCurrent(WebSocket webSocket) {
if (mWebSocket != webSocket) {
return;
}
mWebSocket = null;
mOpened = false;
mConnecting = false;
}
/**
* 上报设备在线心跳,send 返回 false 表示连接已不可用。
*/
private boolean sendMsg(WebSocket webSocket) {
JsonObject jsonObject = new JsonObject();
jsonObject.addProperty("sn", Utils.getSerial());
jsonObject.addProperty("type", "ping");
try {
boolean sent = webSocket.send(jsonObject.toString());
Log.e(TAG, "sendMsg: " + jsonObject + ", sent = " + sent);
return sent;
} catch (Exception e) {
Log.e(TAG, "sendMsg: 发送失败 " + e);
return false;
}
}
private void closeConnect() {
WebSocket current = mWebSocket;
mWebSocket = null;
mOpened = false;
mConnecting = false;
if (current == null) {
return;
}
try {
current.close(CLOSE_CODE_NORMAL, CLOSE_REASON);
} catch (Exception e) {
Log.e(TAG, "closeConnect: " + e);
}
}
/**
* 注册屏幕状态广播,只用于管理连接时机(亮屏重连、息屏断开),不用于把服务拉起来。
*/
private void registerScreenLockReceiver() {
if (mScreenLockReceiver != null) {
return;
}
mScreenLockReceiver = new ScreenLockReceiver();
IntentFilter filter = new IntentFilter();
filter.setPriority(IntentFilter.SYSTEM_HIGH_PRIORITY);
filter.addAction(Intent.ACTION_SCREEN_OFF);
filter.addAction(Intent.ACTION_SCREEN_ON);
filter.addAction(Intent.ACTION_BOOT_COMPLETED);
filter.addAction(Intent.ACTION_USER_PRESENT);
filter.addAction(Intent.ACTION_SHUTDOWN);
filter.addAction(ACTION_FACTORY_RESET);
filter.addAction(ACTION_MASTER_CLEAR);
// 只接收系统广播,API 33+ 必须显式声明导出标志,否则注册会抛异常导致服务创建失败
ReceiverCompat.registerReceiver(this, mScreenLockReceiver, filter,
ReceiverCompat.RECEIVER_NOT_EXPORTED);
}
private class ScreenLockReceiver extends BroadcastReceiver {
@Override
public void onReceive(Context context, Intent intent) {
String action = intent.getAction();
Log.e(TAG, "onReceive: action = " + action);
if (TextUtils.isEmpty(action)) {
Log.e(TAG, "onReceive: action 为空");
return;
}
// 广播回调里只提交 RxJava 订阅,连接动作由订阅切到 IO/主线程执行,不在 onReceive 里做
if (Intent.ACTION_BOOT_COMPLETED.equals(action)
|| Intent.ACTION_USER_PRESENT.equals(action)
|| Intent.ACTION_SCREEN_ON.equals(action)) {
Log.e(TAG, "onReceive: 亮屏,重新开启心跳检测");
startHeartBeat();
} else if (Intent.ACTION_SCREEN_OFF.equals(action)
|| Intent.ACTION_SHUTDOWN.equals(action)
|| ACTION_FACTORY_RESET.equals(action)
|| ACTION_MASTER_CLEAR.equals(action)) {
Log.e(TAG, "onReceive: 息屏,主动断开websocket");
stopHeartBeat();
cancelPendingConnect();
closeConnect();
}
}
}
private boolean isDestroyed() {
return getLifecycle().getCurrentState() == Lifecycle.State.DESTROYED;
}
}
@@ -1,340 +0,0 @@
package com.fuying.sn.service;
/**
* 作者 mjsheng
* 日期 2019/4/1 10:57
* 邮箱 501802639@qq.com
* 来自:
*/
import android.app.Service;
import android.content.BroadcastReceiver;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.ServiceConnection;
import android.os.Binder;
import android.os.Handler;
import android.os.IBinder;
import android.text.TextUtils;
import android.util.Log;
import androidx.annotation.Nullable;
import com.blankj.utilcode.util.NetworkUtils;
import com.fuying.sn.KeepAliveConnection;
import com.fuying.sn.utils.JgyUtils;
import com.fuying.sn.utils.ServiceAliveUtils;
import com.fuying.sn.utils.Utils;
import com.fuying.sn.websocket.JWebSocketClient;
import com.google.gson.JsonObject;
import org.java_websocket.handshake.ServerHandshake;
import java.net.URI;
/**
* 主进程 双进程通讯
*
* @author LiGuangMin
* @time Created by 2018/8/17 11:26
*/
public class StepService extends Service implements NetworkUtils.OnNetworkStatusChangedListener {
private static final String TAG = "StepService";
public JWebSocketClient client;
private JWebSocketClientBinder mBinder = new JWebSocketClientBinder();
@Override
public void onDisconnected() {
Log.i("JWebSocketClientService", "网络断开连接");
}
@Override
public void onConnected(NetworkUtils.NetworkType networkType) {
Log.i("JWebSocketClientService", "网络已连接");
// connect();
}
//用于Activity和service通讯
public class JWebSocketClientBinder extends Binder {
public StepService getService() {
return StepService.this;
}
}
private ServiceConnection mServiceConnection = new ServiceConnection() {
@Override
public void onServiceConnected(ComponentName componentName, IBinder iBinder) {
Log.w(TAG, "StepService:建立链接");
boolean isServiceRunning = ServiceAliveUtils.isServiceAlive(StepService.this, GuardService.class.getName());
if (!isServiceRunning) {
Intent i = new Intent(StepService.this, GuardService.class);
startService(i);
}
}
@Override
public void onServiceDisconnected(ComponentName componentName) {
// 断开链接
startService(new Intent(StepService.this, GuardService.class));
// 重新绑定
bindService(new Intent(StepService.this, GuardService.class), mServiceConnection, Context.BIND_IMPORTANT);
}
};
@Nullable
@Override
public IBinder onBind(Intent intent) {
return new KeepAliveConnection.Stub() {
};
}
@Override
public void onCreate() {
super.onCreate();
NetworkUtils.registerNetworkStatusChangedListener(this);
registerScreenLockReceiver();
//初始化websocket
initSocketClient();
mHandler.postDelayed(heartBeatRunnable, HEART_BEAT_RATE);//开启心跳检测
}
@Override
public int onStartCommand(Intent intent, int flags, int startId) {
// 绑定建立链接
Log.e("JWebSocketClientService", "onStartCommand: ");
bindService(new Intent(this, GuardService.class), mServiceConnection, Context.BIND_IMPORTANT);
return START_STICKY;
}
private ScreenLockReceiver screenLockReceiver;
private void registerScreenLockReceiver() {
if (null == screenLockReceiver) {
screenLockReceiver = new ScreenLockReceiver();
}
IntentFilter filter = new IntentFilter();
filter.setPriority(IntentFilter.SYSTEM_HIGH_PRIORITY);
filter.addAction(Intent.ACTION_SCREEN_OFF);
filter.addAction(Intent.ACTION_SCREEN_ON);
filter.addAction(Intent.ACTION_BOOT_COMPLETED);
filter.addAction(Intent.ACTION_USER_PRESENT);
filter.addAction(Intent.ACTION_SHUTDOWN);
filter.addAction(Intent.ACTION_FACTORY_RESET);
filter.addAction(Intent.ACTION_MASTER_CLEAR);
registerReceiver(screenLockReceiver, filter);
}
private class ScreenLockReceiver extends BroadcastReceiver {
@Override
public void onReceive(Context context, Intent intent) {
String action = intent.getAction();
Log.e(TAG, "onReceive:" + action);
if (TextUtils.isEmpty(action)) {
Log.e(TAG, "onReceive: is NULL");
return;
}
switch (action) {
case Intent.ACTION_BOOT_COMPLETED:
case Intent.ACTION_USER_PRESENT:
case Intent.ACTION_SCREEN_ON:
mHandler.post(heartBeatRunnable);//开启心跳检测
// sendMsg(1);
break;
case Intent.ACTION_SCREEN_OFF:
case Intent.ACTION_SHUTDOWN:
case Intent.ACTION_FACTORY_RESET:
case Intent.ACTION_MASTER_CLEAR:
closeConnect();
// sendMsg(0);
break;
default:
break;
}
}
}
@Override
public void onDestroy() {
super.onDestroy();
NetworkUtils.unregisterNetworkStatusChangedListener(this);
closeConnect();
if (screenLockReceiver != null) {
unregisterReceiver(screenLockReceiver);
}
}
/**
* 初始化websocket连接
*/
private void initSocketClient() {
URI uri = URI.create("wss://as.fuyingy.com/wss/device?sn=" + Utils.getSerial());
// URI uri = URI.create(BuildConfig.WEBSOCKET_URL);
// URI uri = URI.create("ws://echo.websocket.org");
// URI uri = URI.create("ws://123.207.136.134:9010/ajaxchattest");
client = new JWebSocketClient(uri) {
@Override
public void onMessage(String message) {
Log.i("JWebSocketClientService", "收到服务器发来的消息:" + message);
}
@Override
public void onOpen(ServerHandshake handshakedata) {
super.onOpen(handshakedata);
Log.i("JWebSocketClientService", "websocket连接成功");
// sendMsg(1);
sendMsg();
}
@Override
public void onClose(int code, String reason, boolean remote) {
super.onClose(code, reason, remote);
Log.i("JWebSocketClientService", "websocket连接关闭:" + reason);
// client.close();
// initSocketClient();
if (JgyUtils.getInstance().isScreenOn()) {
mHandler.postDelayed(heartBeatRunnable, HEART_BEAT_RATE);//开启心跳检测
}
}
@Override
public void onError(Exception ex) {
super.onError(ex);
Log.i("JWebSocketClientService", "websocket连接错误:" + ex.getMessage());
// client.close();
// initSocketClient();
if (JgyUtils.getInstance().isScreenOn()) {
mHandler.postDelayed(heartBeatRunnable, HEART_BEAT_RATE);//开启心跳检测
} else {
Log.i("JWebSocketClientService", "postDelayed off");
}
}
};
connect();
}
/**
* 连接websocket
*/
private void connect() {
new Thread() {
@Override
public void run() {
try {
//connectBlocking多出一个等待操作,会先连接再发送,否则未连接发送会报错
Log.i("JWebSocketClientService", "websocket链接中");
client.connectBlocking();
} catch (Exception e) {
Log.i("JWebSocketClientService", e.getMessage());
// e.printStackTrace();
}
}
}.start();
}
/**
* 发送消息
*/
public void sendMsg() {
JsonObject jsonObject = new JsonObject();
jsonObject.addProperty("sn", Utils.getSerial());
// PowerManager pm = (PowerManager) getSystemService(Context.POWER_SERVICE);
// if (!pm.isScreenOn()) {
// jsonObject.addProperty("online", 0);
// //熄屏状态
// } else {
// jsonObject.addProperty("online", 1);
// }
jsonObject.addProperty("type", "ping");
if (null != client) {
Log.i("JWebSocketClientService", "发送的消息:" + jsonObject.toString());
client.send(jsonObject.toString());
}
}
@Deprecated
public void sendMsg(int state) {
JsonObject jsonObject = new JsonObject();
jsonObject.addProperty("sn", Utils.getSerial());
jsonObject.addProperty("online", state);
if (null != client) {
Log.i("JWebSocketClientService", "发送的消息:" + jsonObject.toString());
try {
client.send(jsonObject.toString());
} catch (Exception e) {
Log.i(TAG, "sendMsg :" + e.getLocalizedMessage());
}
} else {
Log.i("JWebSocketClientService", "未连接");
}
}
/**
* 断开连接
*/
private void closeConnect() {
try {
if (null != client) {
client.close();
}
} catch (Exception e) {
e.printStackTrace();
} finally {
client = null;
}
}
// -------------------------------------websocket心跳检测------------------------------------------------
private static final long HEART_BEAT_RATE = 30 * 1000;//每隔50秒进行一次对长连接的心跳检测
private Handler mHandler = new Handler();
private Runnable heartBeatRunnable = new Runnable() {
@Override
public void run() {
Log.i("JWebSocketClientService", "心跳包检测websocket连接状态");
if (client != null) {
if (client.isOpen()) {
Log.i("JWebSocketClientService", "websocket已连接");
sendMsg();
} else if (client.isClosed()) {
Log.i("JWebSocketClientService", "websocket重连中");
if (JgyUtils.getInstance().isScreenOn()) {
reconnectWs();
} else {
Log.i("JWebSocketClientService", "reconnectWs off");
}
}
} else {
//如果client已为空,重新初始化连接
client = null;
initSocketClient();
}
//每隔一定的时间,对长连接进行一次心跳检测
if (JgyUtils.getInstance().isScreenOn()) {
mHandler.postDelayed(this, HEART_BEAT_RATE);
} else {
Log.i("JWebSocketClientService", "websocket息屏不重连");
}
}
};
/**
* 开启重连
*/
private void reconnectWs() {
mHandler.removeCallbacks(heartBeatRunnable);
new Thread() {
@Override
public void run() {
try {
Log.i("JWebSocketClientService", "开启重连");
client.reconnectBlocking();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}.start();
}
}
@@ -39,16 +39,14 @@ import com.fuying.sn.network.RequestCompletion;
import com.fuying.sn.network.UrlAddress;
import com.fuying.sn.rlog.LogDBManager;
import com.fuying.sn.service.DownloadService;
import com.fuying.sn.service.GuardService;
import com.fuying.sn.service.StepService;
import com.fuying.sn.service.SocketService;
import com.fuying.sn.sync.AppInventorySync;
import com.fuying.sn.sync.AppUsageReporter;
import com.fuying.sn.sync.DeviceProfileSync;
import com.fuying.sn.utils.ApkUtils;
import com.fuying.sn.utils.CacheUtils;
import com.fuying.sn.utils.JgyUtils;
import com.fuying.sn.utils.NetStateUtils;
import com.fuying.sn.utils.SPUtils;
import com.fuying.sn.utils.SystemUtils;
import com.fuying.sn.utils.TimeUtils;
import com.fuying.sn.utils.ToastUtil;
import com.fuying.sn.utils.Utils;
@@ -138,13 +136,13 @@ public class MainService extends BaseService implements ViewModelStoreOwner, Net
boolean reconnect = mReconnectSyncPending;
mStartupSyncPending = false;
mReconnectSyncPending = false;
if ((!startup && !reconnect) || !NetStateUtils.isNetworkConnected(this)) {
if ((!startup && !reconnect) || !SystemUtils.isNetworkConnected(this)) {
return;
}
// 安装清单同步只依赖后台服务和网络,息屏时也能补报。
TimeManager.getInstance().syncInstalledApps();
boolean screenOnReconnect = reconnect && JgyUtils.getInstance().isScreenOn();
boolean screenOnReconnect = reconnect && SystemUtils.isScreenOn(this);
if (!startup && !screenOnReconnect) {
return;
}
@@ -260,7 +258,7 @@ public class MainService extends BaseService implements ViewModelStoreOwner, Net
String aole_app_forbid = Settings.System.getString(getContentResolver(), CommonConfig.AOLE_ACTION_APP_FORBID);
ApkUtils.writeAppPackageList(MainService.this, aole_app_forbid);
new CacheUtils().cleanApplicationUserData(this, "com.aoleyun.os");
ApkUtils.cleanApplicationUserDataAsync(this, "com.aoleyun.os", null);
File file = new File(JgyUtils.getInstance().getDownLoadPath());
Log.e(TAG, "versionIsUpdate: " + file.getAbsolutePath());
String[] fileList = file.list();
@@ -289,8 +287,7 @@ public class MainService extends BaseService implements ViewModelStoreOwner, Net
}
private void startService() {
startService(new Intent(this, GuardService.class));
startService(new Intent(this, StepService.class));
startService(new Intent(this, SocketService.class));
startService(new Intent(this, DownloadService.class));
}
@@ -27,7 +27,7 @@ import com.fuying.sn.sync.DeviceSettingsSync;
import com.fuying.sn.sync.RequestCallbacks;
import com.fuying.sn.sync.TimePolicySync;
import com.fuying.sn.utils.SPUtils;
import com.fuying.sn.utils.ServiceAliveUtils;
import com.fuying.sn.utils.SystemUtils;
import com.google.gson.JsonObject;
import com.tencent.mmkv.MMKV;
@@ -279,7 +279,7 @@ public class MainServiceModel extends BaseAndroidViewModel {
if (code == 200) {
JsonObject jsonObject = GsonUtils.getJsonObject(GsonUtils.toJSONString(baseResponse.data));
int is_screen_lock = jsonObject.get("is_screen_lock").getAsInt();
if (!ServiceAliveUtils.isServiceAlive(getApplication(), ManagerService.class.getName())) {
if (!SystemUtils.isServiceAlive(getApplication(), ManagerService.class.getName())) {
getApplication().startService(new Intent(getApplication(), ManagerService.class));
}
SPUtils.put(getApplication(), ManagerService.LOCK_STATE, is_screen_lock);
@@ -136,7 +136,6 @@ public final class AppPolicySync {
}
}
}
// ApkUtils.addShortcut(mContext);
}
//应用自启动
@@ -15,7 +15,7 @@ import com.fuying.sn.bean.browser.BrowserBean;
import com.fuying.sn.data.repository.DeviceRepository;
import com.fuying.sn.network.BackgroundRequests;
import com.fuying.sn.sync.RequestCallbacks.CompleteCallback;
import com.fuying.sn.utils.URLUtils;
import com.fuying.sn.utils.UrlUtils;
import java.util.HashSet;
import java.util.List;
@@ -102,7 +102,7 @@ public final class BrowserPolicySync {
@Override
public void onComplete() {
Log.e("setBrowserWhiteList", "onComplete: ");
new URLUtils(mContext).setBrowserList();
new UrlUtils(mContext).setBrowserList();
}
}));
}
@@ -144,7 +144,7 @@ public final class BrowserPolicySync {
if (callback != null) {
callback.onComplete();
}
new URLUtils(mContext).setBrowserList();
new UrlUtils(mContext).setBrowserList();
}
};
}
@@ -211,7 +211,7 @@ public final class BrowserPolicySync {
if (callback != null) {
callback.onComplete();
}
new URLUtils(mContext).setBrowserList();
new UrlUtils(mContext).setBrowserList();
}
};
}
@@ -0,0 +1,326 @@
package com.fuying.sn.utils;
import android.content.ContentResolver;
import android.content.Context;
import android.net.Uri;
import android.os.Bundle;
import android.os.Process;
import android.provider.Settings;
import android.text.TextUtils;
import android.util.Log;
import java.lang.reflect.Method;
import java.util.ArrayList;
import java.util.Comparator;
import java.util.List;
/**
* 以 "android" 包名记账写 Settings.System/Secure/Global(system uid + platform 签名前提),
* 模拟写入未被确认时退回直接 Settings 写。
*/
public final class AndroidSettingsWriter {
private static final String TAG = "AndroidSettingsWriter";
public static final String NAMESPACE_SYSTEM = "system";
public static final String NAMESPACE_SECURE = "secure";
public static final String NAMESPACE_GLOBAL = "global";
private static final String CALL_METHOD_USER_KEY = "_user";
private static final String SETTINGS_AUTHORITY = "settings";
private static final Uri SETTINGS_URI = Uri.parse("content://" + SETTINGS_AUTHORITY);
private static final String SETTINGS_PROVIDER_NAME =
"com.android.providers.settings/.SettingsProvider";
// settings provider 的 IContentProvider 代理缓存;binder 死亡后自动重取
private static volatile Object sSettingsProvider;
// context 兜底,由 JgyUtils 初始化时注入(对应原先的 sInstance.mContext 兜底)
private static volatile Context sAppContext;
private AndroidSettingsWriter() {
}
public static void init(Context context) {
if (context != null) {
sAppContext = context.getApplicationContext();
}
}
/**
* 兼容旧调用:等同于 {@code putString(context, NAMESPACE_SYSTEM, name, value)}。
*/
public static boolean androidSettingsPutString(Context context, String name, String value) {
return putString(context, NAMESPACE_SYSTEM, name, value);
}
public static boolean putString(Context context, String namespace, String name, String value) {
Context targetContext = context != null ? context : sAppContext;
if (targetContext == null) {
Log.e(TAG, "putString: Context is null");
return false;
}
if (TextUtils.isEmpty(name)) {
Log.e(TAG, "putString: name is empty");
return false;
}
Bundle arg = new Bundle();
arg.putString(Settings.NameValueTable.VALUE, value);
// _user 是 SettingsProvider 定位落库用户的必填项,与包名伪装无关;只管主用户
arg.putInt(CALL_METHOD_USER_KEY, 0);
// 1. 优先尝试伪装 "android" 包名调用 SettingsProvider 的 call 接口
Bundle result = callSettingsPut(targetContext, namespace, arg, name);
// 2. 直接查询 SettingsProvider 服务端数据库校验(绕过本进程 sNameValueCache 本地内存缓存)
String serverValue = callSettingsGet(targetContext, namespace, name);
boolean serverVerified = TextUtils.equals(serverValue, value);
if (serverVerified) {
Log.d(TAG, "putString succeeded via SettingsProvider for " + namespace + "/" + name
+ " (serverVerified=true)");
return true;
}
// 3. 服务端校验未通过或 result 为空时,退回 directPutString 直接写入
Log.w(TAG, "putString via provider failed for " + namespace + "/" + name
+ " (result=" + result + ", serverValue=" + serverValue + "), fallback to direct put");
boolean directOk = directPutString(targetContext.getContentResolver(), namespace, name, value);
// 4. 读取校验
String readBackDirect = readSetting(targetContext.getContentResolver(), namespace, name);
boolean directVerified = TextUtils.equals(readBackDirect, value);
Log.d(TAG, "directPutString for " + namespace + "/" + name + " (directOk=" + directOk
+ ", verified=" + directVerified + ")");
return directOk || directVerified;
}
/**
* Settings 各表内部都按字符串落库(putInt == putString(String.valueOf(int))),
* 所以类型写入与字符串写入同一条路径,直接调用兜底也落在对应表的 putString 上。
*/
public static boolean putInt(Context context, String namespace, String name, int value) {
return putString(context, namespace, name, String.valueOf(value));
}
private static String readSetting(ContentResolver cr, String namespace, String name) {
try {
switch (namespace) {
case NAMESPACE_SECURE:
return Settings.Secure.getString(cr, name);
case NAMESPACE_GLOBAL:
return Settings.Global.getString(cr, name);
default:
return Settings.System.getString(cr, name);
}
} catch (Throwable t) {
Log.w(TAG, "readSetting failed for " + namespace + "/" + name + ": " + t);
return null;
}
}
private static boolean directPutString(ContentResolver cr, String namespace, String name,
String value) {
switch (namespace) {
case NAMESPACE_SECURE:
return Settings.Secure.putString(cr, name, value);
case NAMESPACE_GLOBAL:
return Settings.Global.putString(cr, name, value);
default:
return Settings.System.putString(cr, name, value);
}
}
private static Bundle callSettingsPut(Context context, String namespace, Bundle arg, String name) {
Object provider = getSettingsProvider(context);
Bundle result = null;
if (provider != null) {
result = invokeProviderCall(provider, "PUT_" + namespace, arg, name);
if (result == null) {
// 可能 binder 已死亡,清缓存重取再试一次
sSettingsProvider = null;
provider = getSettingsProvider(context);
if (provider != null) {
result = invokeProviderCall(provider, "PUT_" + namespace, arg, name);
}
}
}
if (result == null && context != null) {
try {
result = context.getContentResolver().call(SETTINGS_URI, "PUT_" + namespace, name, arg);
} catch (Throwable t) {
Log.w(TAG, "callSettingsPut ContentResolver.call failed: " + t);
}
}
return result;
}
private static String callSettingsGet(Context context, String namespace, String name) {
Bundle arg = new Bundle();
arg.putInt(CALL_METHOD_USER_KEY, 0);
Object provider = getSettingsProvider(context);
Bundle result = null;
if (provider != null) {
result = invokeProviderCall(provider, "GET_" + namespace, arg, name);
}
if (result == null && context != null) {
try {
result = context.getContentResolver().call(SETTINGS_URI, "GET_" + namespace, name, arg);
} catch (Throwable t) {
Log.w(TAG, "callSettingsGet ContentResolver.call failed: " + t);
}
}
if (result != null) {
return result.getString(Settings.NameValueTable.VALUE);
}
return null;
}
/**
* 多版本兼容的 ContentProvider.call 调用支持:
* 针对 Android 12+(AttributionSource)、Android 11(6参)、Android 10(5参)、Android 9及更低(4参/3参)逐个适配
*/
private static Bundle invokeProviderCall(Object provider, String callMethod, Bundle arg, String name) {
Object attribution = buildAndroidAttributionSource();
for (Method m : provider.getClass().getMethods()) {
if (!"call".equals(m.getName())) {
continue;
}
Class<?>[] p = m.getParameterTypes();
try {
// 1. Android 12+ (5 params: AttributionSource, String, String, String, Bundle)
if (p.length == 5 && p[0].getName().equals("android.content.AttributionSource")
&& p[1] == String.class && p[2] == String.class && p[3] == String.class && p[4] == Bundle.class) {
if (attribution != null) {
Bundle r = (Bundle) m.invoke(provider, attribution, SETTINGS_AUTHORITY, callMethod, name, arg);
return r != null ? r : new Bundle();
}
}
// 2. Android 11 (6 params: String callingPkg, String featureId, String authority, String method, String request, Bundle extras)
else if (p.length == 6 && p[0] == String.class && p[1] == String.class && p[2] == String.class
&& p[3] == String.class && p[4] == String.class && p[5] == Bundle.class) {
Bundle r = (Bundle) m.invoke(provider, "android", null, SETTINGS_AUTHORITY, callMethod, name, arg);
return r != null ? r : new Bundle();
}
// 3. Android 10 (5 params: String callingPkg, String authority, String method, String request, Bundle extras)
else if (p.length == 5 && p[0] == String.class && p[1] == String.class && p[2] == String.class
&& p[3] == String.class && p[4] == Bundle.class) {
Bundle r = (Bundle) m.invoke(provider, "android", SETTINGS_AUTHORITY, callMethod, name, arg);
return r != null ? r : new Bundle();
}
// 4. Android 9 / earlier (4 params: String callingPkg, String method, String request, Bundle extras)
else if (p.length == 4 && p[0] == String.class && p[1] == String.class
&& p[2] == String.class && p[3] == Bundle.class) {
Bundle r = (Bundle) m.invoke(provider, "android", callMethod, name, arg);
return r != null ? r : new Bundle();
}
// 5. 3 params: String method, String request, Bundle extras
else if (p.length == 3 && p[0] == String.class && p[1] == String.class && p[2] == Bundle.class) {
Bundle r = (Bundle) m.invoke(provider, callMethod, name, arg);
return r != null ? r : new Bundle();
}
} catch (Throwable t) {
Throwable root = t instanceof java.lang.reflect.InvocationTargetException
&& t.getCause() != null ? t.getCause() : t;
Log.w(TAG, "invokeProviderCall " + callMethod + " failed via " + m.getName() + ": " + root);
}
}
Log.w(TAG, "invokeProviderCall: no matching call overload on " + provider.getClass().getName());
return null;
}
/**
* AttributionSource.Builder(uid).setPackageName("android").build(),反射构造。
*/
private static Object buildAndroidAttributionSource() {
try {
Class<?> builder = Class.forName("android.content.AttributionSource$Builder");
Object b = builder.getConstructor(int.class).newInstance(Process.myUid());
builder.getMethod("setPackageName", String.class).invoke(b, "android");
return builder.getMethod("build").invoke(b);
} catch (Throwable t) {
return null;
}
}
/**
* 反射 ContentResolver.acquireProvider / acquireExistingProvider,返回并缓存 IContentProvider 代理。
*/
private static Object getSettingsProvider(Context context) {
Object cached = sSettingsProvider;
if (cached != null) {
return cached;
}
synchronized (AndroidSettingsWriter.class) {
if (sSettingsProvider != null) {
return sSettingsProvider;
}
ContentResolver cr = context.getContentResolver();
List<Method> candidates = new ArrayList<>();
for (Method m : ContentResolver.class.getDeclaredMethods()) {
String n = m.getName();
if (("acquireProvider".equals(n) || "acquireExistingProvider".equals(n))
&& m.getReturnType().isInterface()) {
candidates.add(m);
}
}
candidates.sort(Comparator.comparingInt(Method::getParameterCount));
for (Method m : candidates) {
Object provider = tryAcquire(cr, m);
if (provider != null) {
sSettingsProvider = provider;
break;
}
}
if (sSettingsProvider == null) {
Log.e(TAG, "putString: settings provider unavailable");
}
return sSettingsProvider;
}
}
private static Object tryAcquire(ContentResolver cr, Method m) {
Class<?>[] types = m.getParameterTypes();
String[][] slotCombos = {
{SETTINGS_AUTHORITY, SETTINGS_PROVIDER_NAME}, // authority 在前
{SETTINGS_PROVIDER_NAME, SETTINGS_AUTHORITY}, // name 在前
};
for (String[] combo : slotCombos) {
try {
Object[] args = new Object[types.length];
int stringSlot = 0;
for (int i = 0; i < types.length; i++) {
Class<?> t = types[i];
if (t == String.class) {
args[i] = stringSlot < combo.length ? combo[stringSlot] : null;
stringSlot++;
} else if (t == Uri.class) {
args[i] = SETTINGS_URI;
} else if (t == boolean.class) {
args[i] = false; // stable / tryLocal:走 binder 路径
} else if (t == int.class) {
args[i] = 0; // userId / pid
}
}
m.setAccessible(true);
Object provider = m.invoke(cr, args);
if (provider != null) {
Log.d(TAG, "putString: acquired via " + m.getName()
+ java.util.Arrays.toString(types) + " slots=" + combo[0] + "/" + combo[1]);
return provider;
}
} catch (Throwable t) {
Throwable root = t instanceof java.lang.reflect.InvocationTargetException
&& t.getCause() != null ? t.getCause() : t;
Log.w(TAG, "putString: " + m.getName() + " slots=" + combo[0]
+ "/" + combo[1] + " failed: " + root);
}
}
return null;
}
}
@@ -5,6 +5,7 @@ import android.app.PendingIntent;
import android.content.Context;
import android.content.Intent;
import android.content.pm.ApplicationInfo;
import android.content.pm.IPackageDataObserver;
import android.content.pm.PackageInfo;
import android.content.pm.PackageInstaller;
import android.content.pm.PackageManager;
@@ -12,6 +13,7 @@ import android.content.pm.ResolveInfo;
import android.net.Uri;
import android.os.Binder;
import android.os.Build;
import android.os.RemoteException;
import android.provider.Settings;
import android.text.TextUtils;
import android.util.Log;
@@ -51,6 +53,143 @@ import io.reactivex.rxjava3.schedulers.Schedulers;
public class ApkUtils {
private static final String TAG = "ApkUtils";
private static final long MAX_WAIT_TIME = 60 * 1000;
private static final long WAIT_TIME_INCR = 10 * 1000;
// 按包名合并并发清理请求,避免广播风暴时重复调用系统接口
private static final HashMap<String, List<CleanCallback>> CLEAN_CALLBACKS = new HashMap<>();
private static final Object CLEAN_LOCK = new Object();
/**
* 清除应用数据
*
* @param context 上下文
* @param packageName 目标应用包名
* @return 是否清除成功
* @throws Exception 等待清除结果超时
*/
public static boolean cleanApplicationUserData(Context context, String packageName) throws Exception {
PackageDataObserver observer = new PackageDataObserver();
try {
// framework.jar 已提供该隐藏接口,直接调用系统方法即可,不再走反射
synchronized (observer) {
context.getPackageManager().clearApplicationUserData(packageName, observer);
// 只清缓存时可改用 deleteApplicationCacheFiles,这里需要清除全部用户数据
long waitTime = 0;
// 未完成且未超时才继续等待,超时后由下面的判断统一抛错
while (!observer.isDone() && waitTime < MAX_WAIT_TIME) {
observer.wait(WAIT_TIME_INCR);
waitTime += WAIT_TIME_INCR;
}
if (!observer.isDone()) {
throw new Exception("等待应用数据清除结果超时");
}
}
Log.e(TAG, "cleanApplicationUserData: " + packageName + " 清除结果 " + observer.retValue);
return observer.retValue;
} catch (InterruptedException e) {
// 恢复中断标记,避免上层线程池丢失中断状态
Thread.currentThread().interrupt();
Log.e(TAG, "cleanApplicationUserData: 等待被中断 " + e);
return false;
}
}
/**
* 清除应用数据完成回调
*/
public interface CleanCallback {
/**
* @param succeeded 系统接口返回的清除结果
*/
void onFinished(boolean succeeded);
}
/**
* 异步清除应用数据,避免广播回调或主线程被最长 60 秒的同步等待阻塞
*
* @param context 上下文
* @param packageName 目标应用包名
* @param callback 完成回调,可为 null
*/
public static void cleanApplicationUserDataAsync(Context context, String packageName, CleanCallback callback) {
if (context == null || TextUtils.isEmpty(packageName)) {
Log.e(TAG, "cleanApplicationUserDataAsync: 参数为空");
if (callback != null) {
callback.onFinished(false);
}
return;
}
boolean startTask;
synchronized (CLEAN_LOCK) {
List<CleanCallback> callbacks = CLEAN_CALLBACKS.get(packageName);
if (callbacks == null) {
callbacks = new ArrayList<>();
CLEAN_CALLBACKS.put(packageName, callbacks);
startTask = true;
} else {
// 同一个包名已有清理任务在途,把回调合并进去,由在途任务统一触发
startTask = false;
}
if (callback != null) {
callbacks.add(callback);
}
}
if (!startTask) {
Log.e(TAG, "cleanApplicationUserDataAsync: 合并重复请求 " + packageName);
return;
}
Context appContext = context.getApplicationContext();
// 一次性任务,订阅结束即释放,不需要外部持有 Disposable
Observable.fromCallable(() -> cleanApplicationUserData(appContext, packageName))
.subscribeOn(Schedulers.io())
.observeOn(AndroidSchedulers.mainThread())
.subscribe(
succeeded -> finishClean(packageName, succeeded),
throwable -> {
Log.e(TAG, "cleanApplicationUserDataAsync: " + throwable);
finishClean(packageName, false);
}
);
}
private static void finishClean(String packageName, boolean succeeded) {
List<CleanCallback> callbacks;
synchronized (CLEAN_LOCK) {
callbacks = CLEAN_CALLBACKS.remove(packageName);
}
if (callbacks == null) {
return;
}
for (CleanCallback callback : callbacks) {
try {
callback.onFinished(succeeded);
} catch (Exception e) {
Log.e(TAG, "finishClean: 回调执行异常 " + e);
}
}
}
static class PackageDataObserver extends IPackageDataObserver.Stub {
public boolean retValue = false;
private boolean doneFlag = false;
@Override
public void onRemoveCompleted(String packageName, boolean succeeded) throws RemoteException {
synchronized (this) {
retValue = succeeded;
doneFlag = true;
notifyAll();
}
}
public boolean isDone() {
return doneFlag;
}
}
/**
* 获取第三方应用
*
@@ -110,111 +249,8 @@ public class ApkUtils {
return packageNames.contains(packageName);
}
// public static void installRx(final Context context, final String packageName, final String filePath) {
//
// Observable.create(new Observable.OnSubscribe<Integer>() {
// @Override
// public void call(Subscriber<? super Integer> subscriber) {
// File file = new File(filePath);
// if (filePath == null || filePath.length() == 0 || file == null) {
// Log.e("fanhuitong", "errormesg=========" + " 空啊 ");
// subscriber.onNext(0);
// return;
// }
// // String[] args = { "pm", "install", "-r", filePath };
// String[] args = {"pm", "install", "-i", "com.colorflykids", "--user", "0", filePath};
// // String argss = "pm install -i " + "com.colorflykids" + " --user 0 " + filePath;
// Log.e("fanhuitong", "argss====" + args);
// ProcessBuilder processBuilder = new ProcessBuilder(args);
// Process process = null;
// BufferedReader successResult = null;
// BufferedReader errorResult = null;
// StringBuilder successMsg = new StringBuilder();
// StringBuilder errorMsg = new StringBuilder();
// try {
// process = processBuilder.start();
// successResult = new BufferedReader(new InputStreamReader(process.getInputStream()));
// errorResult = new BufferedReader(new InputStreamReader(process.getErrorStream()));
// String s;
// while ((s = successResult.readLine()) != null) {
// Log.e("mjhseng", "successResult----------" + s);
// successMsg.append(s);
// }
// while ((s = errorResult.readLine()) != null) {
// Log.e("mjhseng", "errorResult----------" + s);
// errorMsg.append(s);
// }
// } catch (IOException e1) {
// Log.e("fanhuitong", "IOException e1)----------" + e1.toString());
// e1.printStackTrace();
// } finally {
// try {
// if (successResult != null) {
// successResult.close();
// }
// if (errorResult != null) {
// errorResult.close();
// }
// } catch (IOException e1) {
// Log.e("fanhuitong", "IOException e11)---------" + e1.toString());
// e1.printStackTrace();
// }
// if (process != null) {
// process.destroy();
// }
// }
// if (successMsg.toString().contains("Success") || successMsg.toString().contains("success")) {
// subscriber.onNext(2);
// } else {
// Log.e("fanhuitong", "errormesg=========" + errorMsg.toString());
// subscriber.onNext(1);
// }
// }
// }).subscribeOn(Schedulers.newThread())
// .observeOn(AndroidSchedulers.mainThread())
// .subscribe(new Observer<Integer>() {
//
// @Override
// public void onNext(Integer value) {
// if (value == 2) {
// //安装成功
// ToastUtil.show("安装成功");
// Log.e("fanhuitong", "-----------安装成功-----------");
// } else {
// //安装错误
// Log.e("fanhuitong", "------------安装错误-----------");
// ToastUtil.show("安装失败");
// }
// }
//
// @Override
// public void onCompleted() {
//
// }
//
// @Override
// public void onError(Throwable e) {
// //安装错误
// }
// });
// }
// public static void installApp(final String path, final String packageNames){
// File apkFile = new File(path);
// try {
// Class<?> clazz = Class.forName("android.os.ServiceManager");
// Method method_getService = clazz.getMethod("getService", String.class);
// IBinder bind = (IBinder) method_getService.invoke(null, "package");
// IPackageManager iPm = IPackageManager.Stub.asInterface(bind);
// iPm.installPackage(Uri.fromFile(apkFile),null, 2, apkFile.getName());
// Log.e("fanhuitong", "安装成功");
// } catch (Exception e) {
// e.printStackTrace();
// Log.e("fanhuitong", "安装失败");
// }
// }
//使用系统签名
/**
* 通过路径安装APK,兼容Android 9以上
*
@@ -357,17 +393,17 @@ public class ApkUtils {
*/
public static void UninstallAPP(Context context, String pkg) {
Observable.create(new ObservableOnSubscribe<String>() {
@Override
public void subscribe(ObservableEmitter<String> emitter) throws Exception {
Log.e("UninstallAPP", "pkg: " + pkg);
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
ApkUtils.uninstall(context, pkg);
} else {
ApkUtils.deleteApkInSilence(pkg);
}
emitter.onNext(pkg);
}
}).subscribeOn(Schedulers.io())
@Override
public void subscribe(ObservableEmitter<String> emitter) throws Exception {
Log.e("UninstallAPP", "pkg: " + pkg);
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
ApkUtils.uninstall(context, pkg);
} else {
ApkUtils.deleteApkInSilence(pkg);
}
emitter.onNext(pkg);
}
}).subscribeOn(Schedulers.io())
.observeOn(AndroidSchedulers.mainThread())
.subscribe(new Observer<String>() {
@Override
@@ -451,7 +487,7 @@ public class ApkUtils {
String type = "application/vnd.android.package-archive";
Uri uri;
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
uri = FileProvider.getUriForFile(context, "com.fuying.sn.fileprovider", newApkFile);
uri = FileProvider.getUriForFile(context, BuildConfig.APPLICATION_ID + ".fileprovider", newApkFile);
intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
} else {
uri = Uri.fromFile(newApkFile);
@@ -460,52 +496,9 @@ public class ApkUtils {
context.startActivity(intent);
}
public static void hideSystemSettingAPP(Context context, String pkage) {
int hide = 0;
//后台0显示,1隐藏
try {
if ("com.mediatek.camera".equalsIgnoreCase(pkage)) {
if (Settings.System.getInt(context.getContentResolver(), "qch_app_camera") == 1) {
hide = 1;
}
} else if ("com.android.deskclock".equalsIgnoreCase(pkage)) {
if (Settings.System.getInt(context.getContentResolver(), "qch_app_deskclock") == 1) {
hide = 1;
}
} else if ("com.android.soundrecorder".equalsIgnoreCase(pkage)) {
if (Settings.System.getInt(context.getContentResolver(), "qch_app_soundrecorder") == 1) {
hide = 1;
}
} else if ("com.android.music".equalsIgnoreCase(pkage)) {
if (Settings.System.getInt(context.getContentResolver(), "qch_app_music") == 1) {
hide = 1;
}
} else if ("com.android.gallery3d".equalsIgnoreCase(pkage)) {
if (Settings.System.getInt(context.getContentResolver(), "qch_app_gallery") == 1) {
hide = 1;
}
} else if ("com.android.documentsui".equalsIgnoreCase(pkage)
|| "com.mediatek.filemanager".equalsIgnoreCase(pkage)) {
if (Settings.System.getInt(context.getContentResolver(), "qch_app_filemanager") == 1) {
hide = 1;
}
}
} catch (Settings.SettingNotFoundException e) {
e.printStackTrace();
}
// PackageManager pm = context.getPackageManager();
// if (hide == 0) {
// pm.setApplicationEnabledSetting(pkage, PackageManager.COMPONENT_ENABLED_STATE_DEFAULT, 0);
// } else {
// pm.setApplicationEnabledSetting(pkage, PackageManager.COMPONENT_ENABLED_STATE_DISABLED, 0);
// }
}
@SuppressLint("NewApi")
public static void writeAppPackageList(Context context, String result) {
Log.e(TAG, "writeAppPackageList: " + result);
// addShortcut(context);//开机之后添加图标到桌面
HashSet<String> factoryAppList = new HashSet<>();
factoryAppList.addAll(JgyUtils.getInstance().getOwnApp());
factoryAppList.addAll(JgyUtils.getInstance().getFXYApp());
@@ -637,7 +630,7 @@ public class ApkUtils {
}
}
public static String getAppLable(Context context,String pkgName){
public static String getAppLable(Context context, String pkgName) {
PackageManager pm = context.getPackageManager();
PackageInfo appInfo = null;
try {
@@ -11,10 +11,7 @@ public class AppUsedTimeUtils {
private String app_package;
private long start_time;
// private AppTimeinfo appTimeinfo;
private AppUsedTimeUtils(Context context) {
// appTimeinfo = getAppTimeinfo();
}
public static void init(Context context) {
@@ -70,75 +67,4 @@ public class AppUsedTimeUtils {
this.start_time = time;
}
// static class AppTimeinfo implements Serializable {
// private static final long serialVersionUID = 5373751133823666192L;
//
// AppTimeinfo() {
// this.appPackageName = "";
// this.endTime = 0;
// this.startTime = 0;
// }
//
// private String appPackageName;
// private long endTime;
// private long startTime;
//
// public String getAppPackageName() {
// return appPackageName;
// }
//
// public void setAppPackageName(String appPackageName) {
// this.appPackageName = appPackageName;
// }
//
// public long getEndTime() {
// return endTime;
// }
//
// public void setEndTime(long endTime) {
// this.endTime = endTime;
// }
//
// public long getStartTime() {
// return startTime;
// }
//
// public void setStartTime(long startTime) {
// this.startTime = startTime;
// }
//
// @NonNull
// @Override
// public String toString() {
// return JsonParser.parseString(new Gson().toJson(this)).getAsJsonObject().toString();
// }
// }
// synchronized public String getAppPackageName() {
// appTimeinfo = getAppTimeinfo();
// return appTimeinfo.getAppPackageName();
// }
//
// synchronized public long getStartTime() {
// appTimeinfo = getAppTimeinfo();
// return appTimeinfo.getStartTime();
// }
//
// synchronized public long getEndTime() {
// appTimeinfo = getAppTimeinfo();
// return appTimeinfo.getEndTime();
// }
//
// synchronized private AppTimeinfo getAppTimeinfo() {
// String jsonString = Settings.System.getString(mContext.getContentResolver(), "runningAppInfo");
// if (TextUtils.isEmpty(jsonString)) {
// return new AppTimeinfo();
// }
// Log.e(TAG, "getAppTimeinfo: " + jsonString);
// Type type = new TypeToken<AppTimeinfo>() {
// }.getType();
// Gson gson = new Gson();
// AppTimeinfo appTimeinfo = gson.fromJson(jsonString, type);
// return appTimeinfo;
// }
}
@@ -0,0 +1,81 @@
package com.fuying.sn.utils;
import android.graphics.Bitmap;
import android.text.TextUtils;
import android.util.Log;
import com.google.zxing.BarcodeFormat;
import com.google.zxing.EncodeHintType;
import com.google.zxing.common.BitMatrix;
import com.google.zxing.qrcode.QRCodeWriter;
import com.google.zxing.qrcode.decoder.ErrorCorrectionLevel;
import java.util.Arrays;
import java.util.EnumMap;
import java.util.Map;
/**
* 位图工具类,目前用于生成设备信息二维码。
*/
public class BitmapUtils {
private static final String TAG = "BitmapUtils";
private static final String CHARSET_UTF8 = "utf-8";
private static final int MARGIN = 1;
private static final int COLOR_FOREGROUND = 0xff0480ff;
private static final int COLOR_BACKGROUND = 0xffffffff;
// QRCodeWriter 不保存实例状态,编码只使用局部变量,因此复用同一个实例
private static final QRCodeWriter QR_CODE_WRITER = new QRCodeWriter();
private BitmapUtils() {
}
/**
* 生成二维码位图,失败时返回 null,由调用方决定是否展示占位图。
*
* @param content 二维码内容
* @param widthPix 目标宽度(像素)
* @param heightPix 目标高度(像素)
* @return ARGB_8888 位图;参数非法或生成失败时为 null
*/
public static Bitmap createQRImage(String content, int widthPix, int heightPix) {
if (TextUtils.isEmpty(content) || widthPix <= 0 || heightPix <= 0) {
Log.e(TAG, "createQRImage: 参数非法, widthPix=" + widthPix + ", heightPix=" + heightPix);
return null;
}
try {
// EncodeHintType 是枚举,用 EnumMap 比 HashMap 更省内存
Map<EncodeHintType, Object> hints = new EnumMap<>(EncodeHintType.class);
hints.put(EncodeHintType.CHARACTER_SET, CHARSET_UTF8);
hints.put(EncodeHintType.ERROR_CORRECTION, ErrorCorrectionLevel.H);
hints.put(EncodeHintType.MARGIN, MARGIN); // 默认是 4,这里收窄留白
BitMatrix bitMatrix = QR_CODE_WRITER.encode(content, BarcodeFormat.QR_CODE,
widthPix, heightPix, hints);
int[] pixels = new int[widthPix * heightPix];
Arrays.fill(pixels, COLOR_BACKGROUND);
// 逐行扫描矩阵,背景色已经铺好,只需覆盖前景色像素
for (int y = 0; y < heightPix; y++) {
int rowOffset = y * widthPix;
for (int x = 0; x < widthPix; x++) {
if (bitMatrix.get(x, y)) {
pixels[rowOffset + x] = COLOR_FOREGROUND;
}
}
}
// 早期注释要求"先 compress 到文件再读回"以省内存,但现在三个调用方都是直接把
// 位图交给 ImageView,多余的编解码只会增加 IO 和内存拷贝。这里改成由像素数组
// 一步生成 ARGB_8888 位图,省掉原来整图 setPixels 的第二次写入;位图由调用方
// 持有并负责回收。
return Bitmap.createBitmap(pixels, widthPix, heightPix, Bitmap.Config.ARGB_8888);
} catch (Exception e) {
// 编码失败、矩阵尺寸异常、位图分配失败统一在此落地日志,不能静默返回 null
Log.e(TAG, "createQRImage: 生成二维码失败 " + e.getMessage(), e);
return null;
}
}
}
@@ -1,6 +1,5 @@
package com.fuying.sn.utils;
import javax.crypto.Cipher;
import javax.crypto.spec.IvParameterSpec;
import javax.crypto.spec.SecretKeySpec;
@@ -1,74 +0,0 @@
package com.fuying.sn.utils;
import android.content.Context;
import android.content.pm.IPackageDataObserver;
import android.content.pm.PackageManager;
import android.os.RemoteException;
import android.util.Log;
import java.lang.reflect.Method;
public class CacheUtils {
private static final String TAG = "CacheUtils";
private final long MAX_WAIT_TIME = 60 * 1000;
private final long WAIT_TIME_INCR = 10 * 1000;
/**
* 清除应用数据
*
* @param context
* @param packageName
* @return
* @throws Exception
*/
public boolean cleanApplicationUserData(Context context, String packageName) throws Exception {
try {
PackageDataObserver observer = new PackageDataObserver();
// wait on observer
synchronized (observer) {
Method method = PackageManager.class.getMethod("clearApplicationUserData", new Class[] { String.class, IPackageDataObserver.class });
method.invoke(context.getPackageManager(), packageName, observer);
// getPm().deleteApplicationCacheFiles(appid, observer);
long waitTime = 0;
while (!observer.isDone() || (waitTime > MAX_WAIT_TIME)) {
observer.wait(WAIT_TIME_INCR);
waitTime += WAIT_TIME_INCR;
}
if (!observer.isDone()) {
throw new Exception("timed out waiting for PackageDataObserver.onRemoveCompleted");
}
}
Log.d(TAG, "cleanApplicationCache " + observer.retValue);
return observer.retValue;
} catch (RemoteException e) {
Log.w(TAG, "Failed to get handle for PackageManger Exception: " + e);
return false;
} catch (InterruptedException e) {
Log.w(TAG, "InterruptedException :" + e);
return false;
}
}
class PackageDataObserver extends IPackageDataObserver.Stub {
public boolean retValue = false;
private boolean doneFlag = false;
@Override
public void onRemoveCompleted(String packageName, boolean succeeded) throws RemoteException {
synchronized (this) {
retValue = succeeded;
doneFlag = true;
notifyAll();
}
}
public boolean isDone() {
return doneFlag;
}
}
}
@@ -1,94 +1,150 @@
package com.fuying.sn.utils;
import android.content.Context;
import android.os.Environment;
import android.net.Uri;
import android.text.TextUtils;
import android.util.Log;
import com.arialyy.aria.core.Aria;
import com.blankj.utilcode.util.EncryptUtils;
import com.google.gson.JsonObject;
import java.io.File;
import java.io.FileInputStream;
import java.math.BigInteger;
import java.security.MessageDigest;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class FileUtils {
public static String getFileNamefromURL(String url) {
int position = url.lastIndexOf("/");
return url.substring(position + 1);
}
private static final String TAG = "FileUtils";
private static final String CACHE_DIR_NAME = "cache";
private static final Pattern MD5_PATTERN = Pattern.compile("[0-9a-fA-F]{32}");
public static String getMD5fromFileName(String fileName) {
int position = fileName.lastIndexOf("/");
return fileName.substring(position + 9, fileName.length() - 4);
/**
* 获取可用的缓存目录,优先应用专属外部缓存,外部存储不可用时回退内部缓存
*
* @param context 上下文
* @return 已确认存在且可写的缓存目录
*/
public static File getCacheFileDir(Context context) {
File externalCacheDir = context.getExternalCacheDir();
if (isUsableCacheDir(externalCacheDir)) {
return externalCacheDir;
}
File externalFilesCacheDir = context.getExternalFilesDir(CACHE_DIR_NAME);
if (isUsableCacheDir(externalFilesCacheDir)) {
return externalFilesCacheDir;
}
Log.e(TAG, "getCacheFileDir: 外部缓存不可用,回退内部缓存");
return context.getCacheDir();
}
/**
* 获取单个文件的MD5值
* 获取缓存目录路径,保留给仍需要字符串路径的调用方
*
* @param file 文件
* @return
* @param context 上下文
* @return 缓存目录的绝对路径
*/
public static String getCacheDir(Context context) {
return getCacheFileDir(context).getAbsolutePath();
}
public static String getFileMD5s(File file) {
if (!file.isFile()) {
return null;
/**
* 目录不可用时系统会直接返回 null,因此以实际目录状态为准,不再额外判断存储挂载状态
*
* @param dir 待检查的目录
* @return 目录存在且可写时返回 true
*/
private static boolean isUsableCacheDir(File dir) {
if (dir == null) {
return false;
}
MessageDigest digest = null;
FileInputStream in = null;
byte[] buffer = new byte[1024];
int len;
try {
digest = MessageDigest.getInstance("MD5");
in = new FileInputStream(file);
while ((len = in.read(buffer, 0, 1024)) != -1) {
digest.update(buffer, 0, len);
}
in.close();
} catch (Exception e) {
e.printStackTrace();
return null;
if (!dir.exists() && !dir.mkdirs()) {
return false;
}
BigInteger bigInt = new BigInteger(1, digest.digest());
return bigInt.toString(32);
return dir.isDirectory() && dir.canWrite();
}
/**
* 从下载地址中取出文件名,自动去掉 ? 之后的查询参数
*
* @param url 下载地址
* @return 文件名,解析失败时返回空串
*/
@Deprecated
public static String getFileNamefromURL(String url) {
if (TextUtils.isEmpty(url)) {
return "";
}
String fileName = Uri.parse(url).getLastPathSegment();
if (TextUtils.isEmpty(fileName)) {
int position = url.lastIndexOf("/");
fileName = url.substring(position + 1);
}
int queryIndex = fileName.indexOf("?");
if (queryIndex >= 0) {
fileName = fileName.substring(0, queryIndex);
}
return fileName;
}
/**
* 从文件名中提取 32 位十六进制 MD5,兼容历史命名里的固定长度前缀
*
* @param fileName 文件名
* @return 提取到的 MD5,未匹配到时返回空串
*/
@Deprecated
public static String getMD5fromFileName(String fileName) {
if (TextUtils.isEmpty(fileName)) {
return "";
}
Matcher matcher = MD5_PATTERN.matcher(fileName);
if (matcher.find()) {
return matcher.group();
}
return "";
}
public static void ariaDownload(Context context, String url, JsonObject jsonObject) {
String fileName = getFileNamefromURL(url);
String urlMD5 = "";
if (jsonObject.get("MD5")!=null){
urlMD5 = jsonObject.get("MD5").getAsString();
}else if (jsonObject.get("app_md5")!=null){
urlMD5 = jsonObject.get("app_md5").getAsString();
if (TextUtils.isEmpty(fileName)) {
Log.e(TAG, "ariaDownload: 无法从下载地址解析文件名 " + url);
return;
}
Log.e("ariaDownload", "urlMD5=" + urlMD5);
File file = new File(Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS) + "/jgy/" + fileName);
if (file.exists() && !file.isDirectory()) {
String filenameMD5 = getMD5fromFileName(url);
String fileMD5 = getFileMD5s(file);
Log.e("ariaDownload", "filenameMD5=" + filenameMD5);
Log.e("ariaDownload", "fileMD5=" + fileMD5);
//后端还没有完成json字段的MD5,暂时用文件名获取
if (fileMD5.equalsIgnoreCase(filenameMD5)) {
ApkUtils.installApp(context, file.getAbsolutePath());
} else {
Aria.download(context)
.load(url) //读取下载地址
.setFilePath(JgyUtils.getInstance().getDownLoadPath() + fileName)
.ignoreFilePathOccupy()
.setExtendField(jsonObject.toString())
.create(); //启动下载}
// }
String expectedMD5 = "";
if (jsonObject != null) {
if (jsonObject.has("MD5") && !jsonObject.get("MD5").isJsonNull()) {
expectedMD5 = jsonObject.get("MD5").getAsString();
} else if (jsonObject.has("app_md5") && !jsonObject.get("app_md5").isJsonNull()) {
expectedMD5 = jsonObject.get("app_md5").getAsString();
}
} else {
Aria.download(context)
.load(url) //读取下载地址
.setFilePath(JgyUtils.getInstance().getDownLoadPath() + fileName)
.ignoreFilePathOccupy()
.setExtendField(jsonObject.toString())
.create(); //启动下载}
}
//后端还没有完成json字段的MD5,字段缺失或格式不合法时按文件名获取
if (TextUtils.isEmpty(expectedMD5) || !MD5_PATTERN.matcher(expectedMD5).matches()) {
expectedMD5 = getMD5fromFileName(fileName);
}
String extendField = "";
if (jsonObject != null) {
extendField = jsonObject.toString();
}
Log.e(TAG, "ariaDownload: fileName=" + fileName + " expectedMD5=" + expectedMD5);
// 与下载落盘路径保持一致,避免检查公共目录导致已有文件永远命中不了
String downloadPath = JgyUtils.getInstance().getDownLoadPath();
File file = new File(downloadPath, fileName);
if (file.isFile() && !TextUtils.isEmpty(expectedMD5)) {
String fileMD5 = EncryptUtils.encryptMD5File2String(file);
Log.e(TAG, "ariaDownload: fileMD5=" + fileMD5 + " expectedMD5=" + expectedMD5);
if (expectedMD5.equalsIgnoreCase(fileMD5)) {
ApkUtils.installApp(context, file.getAbsolutePath());
return;
}
}
Aria.download(context)
.load(url) //读取下载地址
.setFilePath(file.getAbsolutePath())
.ignoreFilePathOccupy()
.setExtendField(extendField)
.create(); //启动下载
}
}
@@ -16,7 +16,6 @@ import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.os.Build;
import android.os.Environment;
import android.os.PowerManager;
import android.os.Process;
import android.os.UserHandle;
import android.provider.Settings;
@@ -357,18 +356,18 @@ public class JgyUtils {
}
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());
}
if (cleaned != 0) {
return;
}
Log.e(TAG, "cleanLauncherCache: Start");
// 清理最多会等待 60 秒,交给异步任务,避免安装广播的主线程被阻塞
ApkUtils.cleanApplicationUserDataAsync(mContext, "com.android.launcher3", succeeded -> {
if (succeeded) {
SPUtils.put(mContext, "fristcleanLauncherCache", 1);
}
Log.e(TAG, "cleanLauncherCache: end " + succeeded);
});
}
public int checkAppPlatform() {
@@ -486,30 +485,6 @@ public class JgyUtils {
}
}
// 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);
// Log.e(TAG, "killBackgroundProcesses: " + packageName);
// } catch (Exception e) {
// e.printStackTrace();
// }
// }
/**
* 强行返回主桌面,优化跳转逻辑以确保回到系统默认桌面。
*/
@@ -803,13 +778,6 @@ public class JgyUtils {
mContext.sendBroadcast(intent);
}
//删除用户除了在应用市场的其他应用
public boolean isScreenOn() {
PowerManager powerManager = (PowerManager) mContext.getSystemService(Context.POWER_SERVICE);
//true为打开,false为关闭
return powerManager.isInteractive();
}
public String getInputMethodId(String pkg) {
InputMethodManager imeManager = (InputMethodManager) mContext.getSystemService(Context.INPUT_METHOD_SERVICE);
@@ -1,44 +0,0 @@
package com.fuying.sn.utils;
import android.annotation.SuppressLint;
import java.io.UnsupportedEncodingException;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
public class MD5Util {
@SuppressLint("DefaultLocale")
public static String getUpperMD5Str(String str) {
MessageDigest messageDigest = null;
try {
messageDigest = MessageDigest.getInstance("MD5");
messageDigest.reset();
messageDigest.update(str.getBytes("UTF-8"));
} catch (NoSuchAlgorithmException e) {
System.out.println("NoSuchAlgorithmException caught!");
System.exit(-1);
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
byte[] byteArray = messageDigest.digest();
StringBuffer md5StrBuff = new StringBuffer();
for (int i = 0; i < byteArray.length; i++) {
if (Integer.toHexString(0xFF & byteArray[i]).length() == 1)
md5StrBuff.append("0").append(
Integer.toHexString(0xFF & byteArray[i]));
else
md5StrBuff.append(Integer.toHexString(0xFF & byteArray[i]));
}
return md5StrBuff.toString().toUpperCase();
}
}
@@ -1,28 +0,0 @@
package com.fuying.sn.utils;
import android.content.Context;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
public class NetStateUtils {
/**
* 判断网络连接状态
*
* @param context
* @return true:网络已链接, false:网络已断开连接
*/
public static boolean isNetworkConnected(Context context) {
if (context != null) {
ConnectivityManager mConnectivityManager = (ConnectivityManager) context
.getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo mNetworkInfo = mConnectivityManager
.getActiveNetworkInfo();
if (mNetworkInfo != null) {
return mNetworkInfo.isAvailable();
}
}
return false;
}
}
@@ -0,0 +1,122 @@
package com.fuying.sn.utils;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.Build;
import android.util.Log;
/**
* 动态注册广播兼容工具。
*
* <p>Android 13(API 33)起,动态注册的接收器若包含非系统保护广播,必须显式声明导出标志;
* Android 14+ 的系统(含各厂商定制 ROM,例如本机 Android 16)会强制校验,缺失时直接抛出:
* <pre>
* java.lang.SecurityException: One of RECEIVER_EXPORTED or RECEIVER_NOT_EXPORTED
* should be specified when a receiver isn't being registered exclusively for system broadcasts
* </pre>
* 该异常会导致 Activity / Service 创建失败(启动闪退),并进一步造成前台服务
* {@code startForegroundService()} 超时 ANR。
*
* <p>说明:本工程通过 {@code app/libs/framework.jar} 提供系统隐藏 API(该 jar 为
* Android 10 / API 29 的 framework),其中已包含
* {@code registerReceiver(BroadcastReceiver, IntentFilter, int)} 等带 flags 的重载,
* 因此这里直接调用即可,无需反射;在低版本系统中未知标志位会被忽略,
* 行为与改造前的两参注册保持一致。
*
* <p>标志选择建议:
* <ul>
* <li>{@link #RECEIVER_NOT_EXPORTED}:只接收系统广播,或本应用
* (含共享 {@code android.uid.system} 的兄弟应用)发送的广播;</li>
* <li>{@link #RECEIVER_EXPORTED}:需要接收其它(不同 UID 的)应用发送的广播,
* 与改造前两参 {@code registerReceiver} 的默认行为一致。</li>
* </ul>
*
* @author LiGuangMin
*/
public final class ReceiverCompat {
private static final String TAG = "ReceiverCompat";
/**
* 对应 Context.RECEIVER_EXPORTED(API 33)。
*/
public static final int RECEIVER_EXPORTED = 0x00000002;
/**
* 对应 Context.RECEIVER_NOT_EXPORTED(API 33)。
*/
public static final int RECEIVER_NOT_EXPORTED = 0x00000004;
/**
* 带导出标志的注册重载从 API 33 开始对应用生效。
* 此处不使用 {@code Build.VERSION_CODES.TIRAMISU},因为 framework.jar 只到 API 29。
*/
private static final int FLAGS_API = 33;
private ReceiverCompat() {
}
/**
* 兼容注册,等价于 {@code registerReceiver(receiver, filter)},
* 但在 API 33+ 上显式带上导出标志。
*/
public static Intent registerReceiver(Context context, BroadcastReceiver receiver,
IntentFilter filter, int flags) {
return registerReceiver(context, receiver, filter, flags, null);
}
/**
* 安全注销广播接收器。
*
* <p>系统自带的 {@code unregisterReceiver()} 在"接收器未注册过"或"重复注销"时会抛出
* {@code IllegalArgumentException: Receiver not registered},直接导致进程崩溃;
* 而业务代码通常只能用字段是否为 null 来判断,字段非 null 并不代表注册成功
* (例如注册过程中抛异常、Service 被销毁等场景)。这里统一做容错处理。
*
* @param receiver 允许为 null
*/
public static void unregisterReceiver(Context context, BroadcastReceiver receiver) {
if (context == null || receiver == null) {
return;
}
try {
context.unregisterReceiver(receiver);
} catch (Exception e) {
Log.e(TAG, "unregisterReceiver failed: " + e);
}
}
/**
* 兼容注册,等价于
* {@code registerReceiver(receiver, filter, broadcastPermission, scheduler)}。
*
* @param receiver 可以为 null,此时用于查询粘性广播
* @param flags {@link #RECEIVER_EXPORTED} 或 {@link #RECEIVER_NOT_EXPORTED}
* @param broadcastPermission 发送方必须持有的权限,可为 null
*/
public static Intent registerReceiver(Context context, BroadcastReceiver receiver,
IntentFilter filter, int flags,
String broadcastPermission) {
if (context == null || filter == null) {
return null;
}
try {
if (Build.VERSION.SDK_INT >= FLAGS_API) {
return context.registerReceiver(receiver, filter, broadcastPermission, null, flags);
}
//Android 13 以下不支持导出标志,保持原有注册方式
return context.registerReceiver(receiver, filter, broadcastPermission, null);
} catch (Exception e) {
//兜底:极端情况下(例如厂商裁剪了重载)退回到传统注册,避免直接崩溃
Log.e(TAG, "registerReceiver failed, fallback to legacy: " + e);
try {
return context.registerReceiver(receiver, filter);
} catch (Exception inner) {
Log.e(TAG, "registerReceiver legacy failed: " + inner);
return null;
}
}
}
}
@@ -1,24 +0,0 @@
package com.fuying.sn.utils;
import android.app.ActivityManager;
import android.content.Context;
import android.util.Log;
public class ServiceAliveUtils {
public static boolean isServiceAlive(Context mContext, String serviceName) {
boolean isServiceRunning = false;
ActivityManager manager =
(ActivityManager) mContext.getSystemService(Context.ACTIVITY_SERVICE);
if (manager == null) {
return false;
}
for (ActivityManager.RunningServiceInfo service : manager.getRunningServices(Integer.MAX_VALUE)) {
if (serviceName.equals(service.service.getClassName())) {
isServiceRunning = true;
}
}
Log.i("ServiceAliveUtils", serviceName + " :isServiceAlive: " + isServiceRunning);
return isServiceRunning;
}
}
@@ -1,269 +0,0 @@
package com.fuying.sn.utils;
import android.app.Activity;
import android.content.Context;
import android.graphics.Color;
import android.os.Build;
import android.os.Environment;
import android.text.TextUtils;
import android.view.View;
import android.view.ViewGroup;
import android.view.Window;
import android.view.WindowManager;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.lang.reflect.Field;
import java.lang.reflect.Method;
import java.util.Properties;
public class StatusBarUtil {
public static int navigationHeight = 0;
public static final String SYS_EMUI = "sys_emui";
public static final String SYS_MIUI = "sys_miui";
public static final String SYS_FLYME = "sys_flyme";
private static final String KEY_MIUI_VERSION_CODE = "ro.miui.ui.version.code";
private static final String KEY_MIUI_VERSION_NAME = "ro.miui.ui.version.name";
private static final String KEY_MIUI_INTERNAL_STORAGE = "ro.miui.internal.storage";
private static final String KEY_EMUI_API_LEVEL = "ro.build.hw_emui_api_level";
private static final String KEY_EMUI_VERSION = "ro.build.version.emui";
private static final String KEY_EMUI_CONFIG_HW_SYS_VERSION = "ro.confg.hw_systemversion";
public static void init(Activity activity) {
ViewGroup contentLayout = activity.getWindow().getDecorView().findViewById(Window.ID_ANDROID_CONTENT);
StatusBarUtil.setStatusBar(activity, false, true);
StatusBarUtil.setStatusTextColor(true, activity);
StatusBarUtil.setStatusBarPadding(activity, contentLayout);
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
activity.getWindow().setStatusBarColor(activity.getResources().getColor(android.R.color.transparent));
}
}
/**
* 通过反射的方式获取状态栏高度
*
* @return
*/
public static int getStatusBarHeight(Context context) {
try {
Class<?> c = Class.forName("com.android.internal.R$dimen");
Object obj = c.newInstance();
Field field = c.getField("status_bar_height");
int x = Integer.parseInt(field.get(obj).toString());
return context.getResources().getDimensionPixelSize(x);
} catch (Exception e) {
}
return 0;
}
//获取是否存在NavigationBar
/**
* @param activity
* @param useThemestatusBarColor 是否要状态栏的颜色,不设置则为透明色
* @param withoutUseStatusBarColor 是否不需要使用状态栏为暗色调
*/
public static void setStatusBar(Activity activity, boolean useThemestatusBarColor, boolean withoutUseStatusBarColor) {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {//5.0及以上
View decorView = activity.getWindow().getDecorView();
int option = View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN
| View.SYSTEM_UI_FLAG_LAYOUT_STABLE;
decorView.setSystemUiVisibility(option);
if (useThemestatusBarColor) {
activity.getWindow().setStatusBarColor(activity.getResources().getColor(android.R.color.white));
} else {
activity.getWindow().setStatusBarColor(Color.TRANSPARENT);
}
} else if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {//4.4到5.0
WindowManager.LayoutParams localLayoutParams = activity.getWindow().getAttributes();
localLayoutParams.flags = (WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS | localLayoutParams.flags);
}
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M && !withoutUseStatusBarColor) {
activity.getWindow().getDecorView().setSystemUiVisibility(View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN | View.SYSTEM_UI_FLAG_LIGHT_STATUS_BAR);
}
}
/**
* 改变魅族的状态栏字体为黑色,要求FlyMe4以上
*/
private static void processFlyMe(boolean isLightStatusBar, Activity activity) {
WindowManager.LayoutParams lp = activity.getWindow().getAttributes();
try {
Class<?> instance = Class.forName("android.view.WindowManager$LayoutParams");
int value = instance.getDeclaredField("MEIZU_FLAG_DARK_STATUS_BAR_ICON").getInt(lp);
Field field = instance.getDeclaredField("meizuFlags");
field.setAccessible(true);
int origin = field.getInt(lp);
if (isLightStatusBar) {
field.set(lp, origin | value);
} else {
field.set(lp, (~value) & origin);
}
} catch (Exception e) {
}
}
/**
* 改变小米的状态栏字体颜色为黑色, 要求MIUI6以上 lightStatusBar为真时表示黑色字体
*/
private static void processMIUI(boolean lightStatusBar, Activity activity) {
Class<? extends Window> clazz = activity.getWindow().getClass();
try {
int darkModeFlag;
Class<?> layoutParams = Class.forName("android.view.MiuiWindowManager$LayoutParams");
Field field = layoutParams.getField("EXTRA_FLAG_STATUS_BAR_DARK_MODE");
darkModeFlag = field.getInt(layoutParams);
Method extraFlagField = clazz.getMethod("setExtraFlags", int.class, int.class);
extraFlagField.invoke(activity.getWindow(), lightStatusBar ? darkModeFlag : 0, darkModeFlag);
} catch (Exception e) {
}
}
/**
* 设置OPPO手机状态栏字体为黑色(colorOS3.0,6.0以下部分手机)
*
* @param lightStatusBar
* @param activity
*/
private static final int SYSTEM_UI_FLAG_OP_STATUS_BAR_TINT = 0x00000010;
private static void setOPPOStatusTextColor(boolean lightStatusBar, Activity activity) {
Window window = activity.getWindow();
window.addFlags(WindowManager.LayoutParams.FLAG_DRAWS_SYSTEM_BAR_BACKGROUNDS);
int vis = window.getDecorView().getSystemUiVisibility();
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
if (lightStatusBar) {
vis |= View.SYSTEM_UI_FLAG_LIGHT_STATUS_BAR;
} else {
vis &= ~View.SYSTEM_UI_FLAG_LIGHT_STATUS_BAR;
}
} else if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
if (lightStatusBar) {
vis |= SYSTEM_UI_FLAG_OP_STATUS_BAR_TINT;
} else {
vis &= ~SYSTEM_UI_FLAG_OP_STATUS_BAR_TINT;
}
}
window.getDecorView().setSystemUiVisibility(vis);
}
/**
* 判断手机是否是小米
*
* @return
*/
public static boolean isMIUI() {
return SYS_MIUI.equals(getSystem());
}
/**
* 判断手机是否是魅族
*
* @return
*/
public static boolean isFlyme() {
try {
// Invoke Build.hasSmartBar()
final Method method = Build.class.getMethod("hasSmartBar");
return method != null;
} catch (final Exception e) {
return false;
}
}
/**
* 设置状态栏文字色值为深色调
*
* @param useDart 是否使用深色调
* @param activity
*/
public static void setStatusTextColor(boolean useDart, Activity activity) {
if (isFlyme()) {
processFlyMe(useDart, activity);
} else if (isMIUI()) {
processMIUI(useDart, activity);
} else if (Build.MANUFACTURER.equalsIgnoreCase("OPPO")) {
//OPPO
setOPPOStatusTextColor(useDart, activity);
} else {
if (useDart) {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
activity.getWindow().getDecorView().setSystemUiVisibility(View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN | View.SYSTEM_UI_FLAG_LIGHT_STATUS_BAR);
}
} else {
activity.getWindow().getDecorView().setSystemUiVisibility(
View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN | View.SYSTEM_UI_FLAG_LAYOUT_STABLE);
}
activity.getWindow().getDecorView().findViewById(android.R.id.content).setPadding(0, 0, 0, navigationHeight);
}
}
public static String getSystem() {
String SYS = "";
if (Build.VERSION.SDK_INT > Build.VERSION_CODES.N_MR1) {
if (!TextUtils.isEmpty(getSystemProperty(KEY_MIUI_VERSION_CODE, ""))
|| !TextUtils.isEmpty(getSystemProperty(KEY_MIUI_VERSION_NAME, ""))
|| !TextUtils.isEmpty(getSystemProperty(KEY_MIUI_INTERNAL_STORAGE, ""))) {
SYS = SYS_MIUI;//小米
} else if (!TextUtils.isEmpty(getSystemProperty(KEY_EMUI_API_LEVEL, ""))
|| !TextUtils.isEmpty(getSystemProperty(KEY_EMUI_VERSION, ""))
|| !TextUtils.isEmpty(getSystemProperty(KEY_EMUI_CONFIG_HW_SYS_VERSION, ""))) {
SYS = SYS_EMUI;//华为
} else if (getMeizuFlymeOSFlag().toLowerCase().contains("flyme")) {
SYS = SYS_FLYME;//魅族
}
return SYS;
} else {
try {
Properties prop = new Properties();
prop.load(new FileInputStream(new File(Environment.getRootDirectory(), "build.prop")));
if (prop.getProperty(KEY_MIUI_VERSION_CODE, null) != null
|| prop.getProperty(KEY_MIUI_VERSION_NAME, null) != null
|| prop.getProperty(KEY_MIUI_INTERNAL_STORAGE, null) != null) {
SYS = SYS_MIUI;//小米
} else if (prop.getProperty(KEY_EMUI_API_LEVEL, null) != null
|| prop.getProperty(KEY_EMUI_VERSION, null) != null
|| prop.getProperty(KEY_EMUI_CONFIG_HW_SYS_VERSION, null) != null) {
SYS = SYS_EMUI;//华为
} else if (getMeizuFlymeOSFlag().toLowerCase().contains("flyme")) {
SYS = SYS_FLYME;//魅族
}
} catch (IOException e) {
e.printStackTrace();
return SYS;
} finally {
return SYS;
}
}
}
private static String getSystemProperty(String key, String defaultValue) {
try {
Class<?> clz = Class.forName("android.os.SystemProperties");
Method get = clz.getMethod("get", String.class, String.class);
return (String) get.invoke(clz, key, defaultValue);
} catch (Exception e) {
}
return defaultValue;
}
public static String getMeizuFlymeOSFlag() {
return getSystemProperty("ro.build.display.id", "");
}
/**
* 全屏模式下 针对刘海屏向下移动view
*
* @param context
* @param view 需要设置padding的view
*/
public static void setStatusBarPadding(Context context, View view) {
if (view != null) {
view.setPadding(0, getStatusBarHeight(context), 0, 0);
}
}
}
@@ -1,29 +0,0 @@
package com.fuying.sn.utils;
import android.content.Context;
import android.os.Build;
import android.os.Environment;
import java.io.File;
public class StorageUtils {
// 获取存储空间 false 内置sd卡路径,true 外置sd卡路径
public static String getFileCache(Context context, String s) {
return getExternalFilesDir(context, s).getAbsolutePath();
}
public static File getExternalFilesDir(Context context, String s) {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.FROYO) {
File path = context.getExternalFilesDir(s);
if (path != null) {
return path;
}
}
final String cacheDir = "/Android/data/" + context.getPackageName() + "/files/" + s;
return new File(Environment.getExternalStorageDirectory().getPath() + cacheDir);
}
}
@@ -2,23 +2,141 @@ package com.fuying.sn.utils;
import android.app.ActivityManager;
import android.content.Context;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.os.Build;
import android.os.PowerManager;
import android.util.Log;
import java.lang.reflect.Method;
import java.util.List;
/**
* 进程与网络状态查询工具类。
* <p>
* 应用常驻后台且大部分能力由系统签名提供,这里只放"读取系统状态"这类无副作用的方法,
* 不写入任何配置,避免与 ControlManager / JgyUtils 的写入职责混在一起。
*/
public class SystemUtils {
private static final String TAG = "SystemUtils";
/**
* 判断指定 pid 对应的是否为主进程。
* <p>
* 主进程的进程名与包名一致;推送 SDK 等会拉起独立的子进程(进程名形如 包名:子进程名),
* 子进程里不能再初始化一套单例与常驻服务,否则 MMKV、推送、保活服务会被重复初始化。
*
* @param cxt 上下文,用于取包名与 ActivityManager
* @param pid 待判断的进程 id,一般传 Process.myPid()
* @return true:该 pid 是主进程;false:是子进程,或取不到进程列表、pid 不在列表里
*/
public static boolean isMainProcessName(Context cxt, int pid) {
String packageName = cxt.getPackageName();
ActivityManager am = (ActivityManager) cxt.getSystemService(Context.ACTIVITY_SERVICE);
List<ActivityManager.RunningAppProcessInfo> runningApps = am.getRunningAppProcesses();
if (runningApps == null) {
// 部分 ROM 在后台或权限受限时会返回 null,此时按非主进程处理,宁可少初始化也不重复初始化
return false;
}
for (ActivityManager.RunningAppProcessInfo procInfo : runningApps) {
if (procInfo.pid == pid) {
// 进程名等于包名才是主进程
return procInfo.processName.equals(packageName);
}
}
return false;
}
/**
* 判断指定服务当前是否存活。
* <p>
* 主要给保活/守护逻辑用:服务被系统回收后,先确认目标服务是否真的还在跑,再决定是否重新拉起,
* 避免重复启动造成多份常驻实例。
* <p>
* 说明:{@link ActivityManager#getRunningServices(int)} 在 Android 8.0 之后对普通应用已受限,
* 只能看到自身进程内的服务;本应用是系统签名应用,才能拿到完整列表,因此这里依赖的是系统签名,
* 不要搬到普通应用里复用。
*
* @param mContext 上下文,用于取 ActivityManager
* @param serviceName 服务的完整类名,必须与 ServiceInfo#getClassName() 一致,不是进程名
* @return true:服务在运行;false:服务未运行,或取不到 ActivityManager、运行中服务列表为 null
*/
public static boolean isServiceAlive(Context mContext, String serviceName) {
boolean isServiceRunning = false;
ActivityManager manager =
(ActivityManager) mContext.getSystemService(Context.ACTIVITY_SERVICE);
if (manager == null) {
// 取不到系统服务时按"未存活"处理,把是否重新拉起的决定权交给调用方
return false;
}
List<ActivityManager.RunningServiceInfo> runningServices =
manager.getRunningServices(Integer.MAX_VALUE);
if (runningServices == null) {
// 部分 ROM 在后台或权限受限时会返回 null,此时不能直接遍历,否则会抛 NPE
Log.i("ServiceAliveUtils", serviceName + " :isServiceAlive: false, runningServices is null");
return false;
}
// 枚举全部运行中服务,只要类名命中即视为存活;命中后不提前 return,保持原有日志出口唯一
for (ActivityManager.RunningServiceInfo service : runningServices) {
if (serviceName.equals(service.service.getClassName())) {
isServiceRunning = true;
}
}
Log.i("ServiceAliveUtils", serviceName + " :isServiceAlive: " + isServiceRunning);
return isServiceRunning;
}
/**
* 判断网络连接状态。
* <p>
* 只看当前活动网络是否可用:已连接但没有实际出口(如只连上无网关的 WiFi)也会返回 true,
* 所以断网重连逻辑仍要以 MainService/ManagerService 的 onConnected 回调为准,不要只依赖本方法。
*
* @param context 上下文,用于取 ConnectivityManager;传 null 直接返回 false
* @return true:网络已连接,false:网络已断开或上下文为空
*/
public static boolean isNetworkConnected(Context context) {
if (context != null) {
ConnectivityManager mConnectivityManager = (ConnectivityManager) context
.getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo mNetworkInfo = mConnectivityManager
.getActiveNetworkInfo();
if (mNetworkInfo != null) {
return mNetworkInfo.isAvailable();
}
}
return false;
}
public static boolean isScreenOn(Context context) {
PowerManager powerManager = (PowerManager) context.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为关闭
}
public static void killBackgroundProcesses(Context context, String packageName) {
ActivityManager activityManager;
try {
activityManager = (ActivityManager) context.getSystemService(Context.ACTIVITY_SERVICE);
activityManager.killBackgroundProcesses(packageName);
Method forceStopPackage = activityManager.getClass()
.getDeclaredMethod("forceStopPackage", String.class);
Log.e(TAG, "killBackgroundProcesses: " + packageName);
forceStopPackage.setAccessible(true);
forceStopPackage.invoke(activityManager, packageName);
} catch (Exception e) {
Log.e(TAG, "killBackgroundProcesses: " + e.getMessage());
e.printStackTrace();
}
}
}
@@ -27,13 +27,13 @@ import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;
public class URLUtils {
public class UrlUtils {
private static final String TAG = "URLUtils";
private Context mContext;
private HashSet<String> baseURLList = new HashSet<>();
private HashSet<String> nohttpURLList = new HashSet<>();
public URLUtils(Context context) {
public UrlUtils(Context context) {
this.mContext = context;
}
+42 -141
View File
@@ -11,7 +11,6 @@ import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.pm.PackageManager;
import android.graphics.Bitmap;
import android.net.wifi.WifiInfo;
import android.net.wifi.WifiManager;
import android.os.BatteryManager;
@@ -28,12 +27,6 @@ import android.view.WindowManager;
import com.fuying.sn.BuildConfig;
import com.fuying.sn.config.CommonConfig;
import com.google.gson.JsonObject;
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.tencent.mmkv.MMKV;
import java.io.BufferedReader;
@@ -48,17 +41,49 @@ import java.net.NetworkInterface;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.regex.Pattern;
public class Utils {
private static final String TAG = "Utils";
/**
* 获取设备序列号
*
* @return
*/
public static String getSerial() {
if (JgyUtils.getInstance().checkAppPlatform() == JgyUtils.G13Platform
|| JgyUtils.getInstance().checkAppPlatform() == JgyUtils.iPlay50SEPlatform
) {
return getSn();
} else {
return JgyUtils.getInstance().getIMEI();
}
}
public static String getSn() {
String serial = "unknow";
try {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.P) {//9.0+
serial = Build.getSerial();
} else if (Build.VERSION.SDK_INT > Build.VERSION_CODES.N) {//8.0+
serial = Build.SERIAL;
} else {//8.0-
Class<?> c = Class.forName("android.os.SystemProperties");
Method get = c.getMethod("get", String.class);
serial = (String) get.invoke(c, "ro.serialno");
}
} catch (Exception e) {
e.printStackTrace();
Log.e("e", "读取设备序列号异常:" + e);
}
return serial;
}
// MD5 设备地址标识
public static String getMAC(Context context) {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) { // 如果当前设备系统大于等于6.0 使用下面的方法
@@ -94,7 +119,7 @@ public class Utils {
"cat /sys/class/net/wlan0/address");
InputStreamReader ir = new InputStreamReader(pp.getInputStream());
LineNumberReader input = new LineNumberReader(ir);
for (; null != str; ) {
while (null != str) {
str = input.readLine();
if (str != null) {
macSerial = str.trim();// 去空格
@@ -163,116 +188,6 @@ public class Utils {
return builder.toString();
}
// MD5 设备地址标识
// 防止连续点击
// 5分钟 = 1 转换成时间
// 根据日期取得星期几
// // 非空判断
// public static boolean isEmpty(String s) {
// if (null == s)
// return true;
// if (s.length() == 0)
// return true;
// return s.trim().length() == 0;
// }
// 手动隐藏键盘
// 接受软键盘输入
// 卸载app
// 打开app
// 设置系统亮度模式
// 更新 版本比较
/**
* 获取设备序列号
*
* @return
*/
public static String getSerial() {
if (JgyUtils.getInstance().checkAppPlatform() == JgyUtils.G13Platform
|| JgyUtils.getInstance().checkAppPlatform() == JgyUtils.iPlay50SEPlatform
) {
return getSn();
} else {
return JgyUtils.getInstance().getIMEI();
}
}
public static String getSn() {
String serial = "unknow";
try {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.P) {//9.0+
serial = Build.getSerial();
} else if (Build.VERSION.SDK_INT > Build.VERSION_CODES.N) {//8.0+
serial = Build.SERIAL;
} else {//8.0-
Class<?> c = Class.forName("android.os.SystemProperties");
Method get = c.getMethod("get", String.class);
serial = (String) get.invoke(c, "ro.serialno");
}
} catch (Exception e) {
e.printStackTrace();
Log.e("e", "读取设备序列号异常:" + e.toString());
}
return serial;
}
public static Bitmap createQRImage(String content, int widthPix, int heightPix) {
try {
// if (content == null || "".equals(content)) {
// return false;
// }
//配置参数
Map<EncodeHintType, Object> hints = new HashMap<>();
hints.put(EncodeHintType.CHARACTER_SET, "utf-8");
//容错级别
hints.put(EncodeHintType.ERROR_CORRECTION, ErrorCorrectionLevel.H);
//设置空白边距的宽度
hints.put(EncodeHintType.MARGIN, 1); //default is 4
// 图像数据转换,使用了矩阵转换
BitMatrix bitMatrix = null;
try {
bitMatrix = new QRCodeWriter().encode(content, BarcodeFormat.QR_CODE, widthPix,
heightPix, hints);
} catch (WriterException e) {
e.printStackTrace();
}
int[] pixels = new int[widthPix * heightPix];
// 下面这里按照二维码的算法,逐个生成二维码的图片,
// 两个for循环是图片横列扫描的结果
for (int y = 0; y < heightPix; y++) {
for (int x = 0; x < widthPix; x++) {
if (bitMatrix.get(x, y)) {
pixels[y * widthPix + x] = 0xff0480ff;
} 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;
}
//判断是否为系统应用
/**
* 更新应用白名单禁止升级
*
@@ -607,7 +522,7 @@ public class Utils {
// jsonObject.addProperty("wifi_signal", info.getRssi());
jsonObject.addProperty("wifi_signal", 0);
jsonObject.addProperty("bluetooth", getBluetoothList());
Log.e(TAG, "getHardware: " + jsonObject.toString());
Log.e(TAG, "getHardware: " + jsonObject);
return jsonObject.toString();
}
@@ -639,7 +554,7 @@ public class Utils {
BluetoothDevice device = iterator.next();
stringBuilder.append(device.getAlias()).append(";");
}
Log.e(TAG, "getBluetoothList: " + stringBuilder.toString());
Log.e(TAG, "getBluetoothList: " + stringBuilder);
return stringBuilder.toString();
}
}
@@ -649,7 +564,7 @@ public class Utils {
List<String> pkgList = ApkUtils.queryFilterAppList(context);
for (String pkg : pkgList) {
if (runningAppWhitelist.contains(pkg)) continue;
killBackgroundProcesses(context, pkg);
SystemUtils.killBackgroundProcesses(context, pkg);
}
}
@@ -666,21 +581,7 @@ public class Utils {
}};
public static void killBackgroundProcesses(Context context, String packageName) {
ActivityManager activityManager;
try {
activityManager = (ActivityManager) context.getSystemService(Context.ACTIVITY_SERVICE);
activityManager.killBackgroundProcesses(packageName);
Method forceStopPackage = activityManager.getClass()
.getDeclaredMethod("forceStopPackage", String.class);
// Log.e(TAG, "killBackgroundProcesses: " + packageName);
forceStopPackage.setAccessible(true);
forceStopPackage.invoke(activityManager, packageName);
} catch (Exception e) {
Log.e(TAG, "killBackgroundProcesses: " + e.getMessage());
e.printStackTrace();
}
}
public static String getWifiAlias(Context context) {
WifiManager wifiManager = (WifiManager) context.getSystemService(WIFI_SERVICE);
@@ -696,10 +597,10 @@ public class Utils {
/*重启自身*/
public static void triggerRebirth(Context context) {
PackageManager packageManager = context.getPackageManager();
Intent intent = packageManager.getLaunchIntentForPackage(context.getPackageName()); //
Intent intent = packageManager.getLaunchIntentForPackage(context.getPackageName());
ComponentName componentName = intent.getComponent();
Intent mainIntent = Intent.makeRestartActivityTask(componentName); //
Intent mainIntent = Intent.makeRestartActivityTask(componentName);
context.startActivity(mainIntent);
Runtime.getRuntime().exit(0); //
Runtime.getRuntime().exit(0);
}
}
@@ -1,36 +0,0 @@
package com.fuying.sn.websocket;
import android.util.Log;
import org.java_websocket.client.WebSocketClient;
import org.java_websocket.drafts.Draft_6455;
import org.java_websocket.handshake.ServerHandshake;
import java.net.URI;
public class JWebSocketClient extends WebSocketClient {
public JWebSocketClient(URI serverUri) {
super(serverUri, new Draft_6455());
}
@Override
public void onOpen(ServerHandshake handshakedata) {
Log.i("JWebSocketClient", "onOpen()");
}
@Override
public void onMessage(String message) {
Log.i("JWebSocketClient", "onMessage()");
}
@Override
public void onClose(int code, String reason, boolean remote) {
Log.i("JWebSocketClient", "onClose():" + reason);
}
@Override
public void onError(Exception ex) {
Log.i("JWebSocketClient", "onError():" + ex.getMessage());
}
}