version:1.6.1

fix:休息日管控完善
add:
This commit is contained in:
2021-09-02 18:29:04 +08:00
parent 93b0e35af7
commit 0fa06f8f2a
135 changed files with 10134 additions and 4595 deletions

View File

@@ -18,10 +18,10 @@ import java.util.Locale;
* @创建时间 2015年11月24日 上午11:46:50
* @项目名称 AMapLocationDemo2.x
* @author hongming.wang
* @文件名称: amapUtils.java
* @类型名称: amapUtils
* @文件名称: AmapUtils.java
* @类型名称: AmapUtils
*/
public class amapUtils {
public class AmapUtils {
/**
* 开始定位
*/

View File

@@ -1,7 +1,11 @@
package com.info.sn.utils;
import android.annotation.SuppressLint;
import android.app.Activity;
import android.app.ActivityManager;
import android.app.PendingIntent;
import android.app.usage.UsageStats;
import android.app.usage.UsageStatsManager;
import android.content.Context;
import android.content.Intent;
import android.content.pm.ApplicationInfo;
@@ -36,13 +40,17 @@ import java.lang.reflect.Method;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Enumeration;
import java.util.HashSet;
import java.util.List;
import java.util.SortedMap;
import java.util.TreeMap;
import java.util.function.Predicate;
import java.util.zip.ZipEntry;
import java.util.zip.ZipFile;
public class ApkUtils {
private static String TAG = ApkUtils.class.getSimpleName();
public static synchronized boolean getRootAhth() {
Process process = null;
@@ -534,7 +542,7 @@ public class ApkUtils {
update = versionCode > code;
} catch (PackageManager.NameNotFoundException e) {
e.printStackTrace();
// LogUtils.e("NameNotFoundException", e.getMessage());
// Log.e("NameNotFoundException", e.getMessage());
update = false;
}
return update;
@@ -602,29 +610,29 @@ public class ApkUtils {
int hide = 0;
//后台0显示1隐藏
try {
if (pkage.equalsIgnoreCase("com.mediatek.camera")) {
if (Settings.System.getInt(context.getContentResolver(), "qch_app_camera") == 1) {
if ("com.mediatek.camera".equalsIgnoreCase(pkage)) {
if (JGYUtils.getInt(context.getContentResolver(), "qch_app_camera") == 1) {
hide = 1;
}
} else if (pkage.equalsIgnoreCase("com.android.deskclock")) {
if (Settings.System.getInt(context.getContentResolver(), "qch_app_deskclock") == 1) {
} else if ("com.android.deskclock".equalsIgnoreCase(pkage)) {
if (JGYUtils.getInt(context.getContentResolver(), "qch_app_deskclock") == 1) {
hide = 1;
}
} else if (pkage.equalsIgnoreCase("com.android.soundrecorder")) {
if (Settings.System.getInt(context.getContentResolver(), "qch_app_soundrecorder") == 1) {
} else if ("com.android.soundrecorder".equalsIgnoreCase(pkage)) {
if (JGYUtils.getInt(context.getContentResolver(), "qch_app_soundrecorder") == 1) {
hide = 1;
}
} else if (pkage.equalsIgnoreCase("com.android.music")) {
if (Settings.System.getInt(context.getContentResolver(), "qch_app_music") == 1) {
} else if ("com.android.music".equalsIgnoreCase(pkage)) {
if (JGYUtils.getInt(context.getContentResolver(), "qch_app_music") == 1) {
hide = 1;
}
} else if (pkage.equalsIgnoreCase("com.android.gallery3d")) {
if (Settings.System.getInt(context.getContentResolver(), "qch_app_gallery") == 1) {
} else if ("com.android.gallery3d".equalsIgnoreCase(pkage)) {
if (JGYUtils.getInt(context.getContentResolver(), "qch_app_gallery") == 1) {
hide = 1;
}
} else if (pkage.equalsIgnoreCase("com.android.documentsui")
|| pkage.equalsIgnoreCase("com.mediatek.filemanager")) {
if (Settings.System.getInt(context.getContentResolver(), "qch_app_filemanager") == 1) {
} else if ("com.android.documentsui".equalsIgnoreCase(pkage)
|| "com.mediatek.filemanager".equalsIgnoreCase(pkage)) {
if (JGYUtils.getInt(context.getContentResolver(), "qch_app_filemanager") == 1) {
hide = 1;
}
}
@@ -661,75 +669,148 @@ public class ApkUtils {
}
}
public static void addShortcut(Context context, String packageList) {
public static void addShortcut(Context context) {
String packageList = (String) SPUtils.get(context, "only_jgy_shortcut_list", "Invalid");
if (TextUtils.isEmpty(packageList)) {
JGYUtils.putString(context.getContentResolver(), "qch_launcher_icon_app", "");
return;
}
Log.e("addShortcut", "addShortcut: " + packageList);
String[] stringList = packageList.split(",");
List<String> packages = new ArrayList<>(Arrays.asList(stringList));
String installedList = "";
HashSet<String> packages = new HashSet<>(Arrays.asList(stringList));
String romapps = JGYUtils.getString(context.getContentResolver(), "jgy_customromapp");
Log.e(TAG, "addShortcut: romapps: " + romapps);
HashSet<String> appSet = new HashSet<>();
if (!TextUtils.isEmpty(romapps)) {
appSet = new HashSet<>(Arrays.asList(romapps.split(",")));
packages.addAll(appSet);
}
packages.removeIf(new Predicate<String>() {
@Override
public boolean test(String s) {
return TextUtils.isEmpty(s);
}
});
StringBuilder installedListBuilder = new StringBuilder();
for (String s : packages) {
if (s.equals("com.jiaoguanyi.store") || s.equals("com.jiaoguanyi.appstore")) {
if ("com.jiaoguanyi.store".equals(s) || "com.jiaoguanyi.appstore".equals(s)) {
continue;
}
if (isSystemApp(context, s)) {
if (!appSet.contains(s)) {
continue;
}
}
if (!ApkUtils.isAvailable(context, s)) {
continue;
}
// ApkUtils.getStartActivityName(context, s);
if (!installedList.contains(s)) {
installedList += s + ",";
Log.e("addShortcut", s);
if (installedListBuilder.length() > 0) {
installedListBuilder.append(",");
}
installedListBuilder.append(s);
Log.e("addShortcut", "packages: " + s);
}
if (installedList.length() != 0) {
installedList = installedList.substring(0, installedList.length() - 1);
} else {
Log.e("addShortcut", installedList);
}
boolean qch_force_app = Settings.System.putString(context.getContentResolver(), "qch_launcher_icon_app", installedList);
// String old = Settings.System.getString(context.getContentResolver(), "qch_launcher_icon_app");
String installedList = installedListBuilder.toString();
boolean qch_force_app = JGYUtils.putString(context.getContentResolver(), "qch_launcher_icon_app", installedList);
// String old = JGYUtils.getString(context.getContentResolver(), "qch_launcher_icon_app");
// Log.e("addShortcut", old);
Log.e("addShortcut", "installedList:" + installedList);
Log.e("addShortcut", "putstring:" + qch_force_app);
}
@SuppressLint("NewApi")
public static void writeAppPackageList(Context context, String result) {
ApkUtils.addShortcut(context, result);//开机之后添加图标到桌面
String appstore = "com.jiaoguanyi.appstore";
String store = "com.jiaoguanyi.store";
String infosn = "com.info.sn";
String appstoreuiui = "com.appstore.uiui";
String desktop = "com.android.uiuios";
String jgy1 = "com.uiuios.jgy1";
String jgy2 = "com.uiuios.jgy2";
ApkUtils.addShortcut(context);//开机之后添加图标到桌面
List<String> factoryAppList = new ArrayList<String>() {{
this.add("com.jiaoguanyi.appstore");
this.add("com.jiaoguanyi.store");
this.add("com.info.sn");
this.add("com.appstore.uiui");
this.add("com.android.uiuios");
this.add("com.uiuios.jgy1");
this.add("com.uiuios.jgy2");
this.add("com.tt.ttutils");
this.add("com.info.chat");
this.add("com.info.learning");
}};
HashSet<String> factoryAppSet = new HashSet<>(factoryAppList);
if (!TextUtils.isEmpty(result)) {
if (!result.contains(appstore)) {
result = result + "," + appstore;
}
if (!result.contains(store)) {
result = result + "," + store;
}
if (!result.contains(jgy1)) {
result = result + "," + jgy1;
}
if (!result.contains(jgy2)) {
result = result + "," + jgy2;
}
if (!result.contains(infosn)) {
result = result + "," + infosn;
}
if (!result.contains(appstoreuiui)) {
result = result + "," + appstoreuiui;
}
if (!result.contains(desktop)) {
result = result + "," + desktop;
}
boolean qch_app_forbid = Settings.System.putString(context.getContentResolver(), "qch_app_forbid", result);
Log.e("fht", "qch_app_forbid :" + result + ":" + qch_app_forbid);
HashSet<String> writeAppSet = new HashSet<>(Arrays.asList(result.split(",")));
writeAppSet.addAll(factoryAppSet);
String pkgString = String.join(",", writeAppSet);
Log.e("fht", "qch_app_forbid :" + result);
boolean qch_app_forbid = JGYUtils.putString(context.getContentResolver(), "qch_app_forbid", pkgString);
} else {
JGYUtils.putString(context.getContentResolver(), "qch_app_forbid", String.join(",", factoryAppSet));
Log.e("fht", "writeAppPackageList is null:");
}
Utils.writeDisableUpdateList(context);
}
/**
* 判断是否为系统应用
*
* @param context 上下文
* @param pkgName 包名
* @return
*/
public static boolean isSystemApp(Context context, String pkgName) {
boolean isSystemApp = false;
PackageInfo pi = null;
try {
PackageManager pm = context.getPackageManager();
pi = pm.getPackageInfo(pkgName, 0);
} catch (PackageManager.NameNotFoundException e) {
Log.e("isSystemApp: NameNotFoundException:", e.getMessage());
}
// 是系统中已安装的应用
if (pi != null) {
boolean isSysApp = (pi.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) == 1;
boolean isSysUpd = (pi.applicationInfo.flags & ApplicationInfo.FLAG_UPDATED_SYSTEM_APP) == 1;
isSystemApp = isSysApp || isSysUpd;
}
return isSystemApp;
}
//通过包名获取版本号
public static String getAPPVersionName(Context context, String packageName) {
String versionName = "0";
if (TextUtils.isEmpty(packageName)) {
return versionName;
}
PackageManager pm = context.getPackageManager();
try {
PackageInfo packageInfo = pm.getPackageInfo(packageName, 0);
versionName = packageInfo.versionName;
} catch (PackageManager.NameNotFoundException e) {
e.printStackTrace();
}
return versionName;
}
public static String getTaskPackname(Context context) {
String currentApp = "CurrentNULL";
if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.LOLLIPOP) {
@SuppressLint("WrongConstant") UsageStatsManager usm = (UsageStatsManager) context.getSystemService("usagestats");
long time = System.currentTimeMillis();
List<UsageStats> appList = usm.queryUsageStats(UsageStatsManager.INTERVAL_DAILY, time - 1000 * 1000, time);
if (appList != null && appList.size() > 0) {
SortedMap<Long, UsageStats> mySortedMap = new TreeMap<Long, UsageStats>();
for (UsageStats usageStats : appList) {
mySortedMap.put(usageStats.getLastTimeUsed(), usageStats);
}
if (mySortedMap != null && !mySortedMap.isEmpty()) {
currentApp = mySortedMap.get(mySortedMap.lastKey()).getPackageName();
}
}
} else {
ActivityManager am = (ActivityManager) context.getSystemService(Context.ACTIVITY_SERVICE);
List<ActivityManager.RunningAppProcessInfo> tasks = am.getRunningAppProcesses();
currentApp = tasks.get(0).processName;
}
// Log.e("TAG", "Current App in foreground is: " + currentApp);
return currentApp;
}
}

View File

@@ -8,6 +8,8 @@ import android.content.pm.PackageManager;
import android.content.pm.PackageManager.NameNotFoundException;
import android.content.pm.ResolveInfo;
import com.info.sn.bean.zuoye.LocalAppInfo;
import java.io.File;
import java.util.ArrayList;
import java.util.List;

View File

@@ -0,0 +1,333 @@
package com.info.sn.utils;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.security.InvalidAlgorithmParameterException;
import java.security.InvalidKeyException;
import java.security.NoSuchAlgorithmException;
import javax.crypto.Cipher;
import javax.crypto.CipherInputStream;
import javax.crypto.CipherOutputStream;
import javax.crypto.NoSuchPaddingException;
import javax.crypto.spec.IvParameterSpec;
import javax.crypto.spec.SecretKeySpec;
public class CXAESUtil {
/**
* 加解密算法/工作模式/填充方式
*/
private static final String CIPHER_ALGORITHM = "AES/ECB/PKCS5Padding";
public final static String HEX = "0123456789ABCDEF";
private static final int keyLenght = 16;
private static final String defaultV = "0";
/**
* 加密
*
* @param key 密钥
* @param src 加密文本
* @return
* @throws Exception
*/
public static String encrypt(String key, String src) {
// /src = Base64.encodeToString(src.getBytes(), Base64.DEFAULT);
byte[] rawKey = toMakekey(key, keyLenght, defaultV).getBytes();// key.getBytes();
try {
byte[] result = encrypt(rawKey, src.getBytes("utf-8"));
// result = Base64.encode(result, Base64.DEFAULT);
return toHex(result);
} catch (Exception e) {
e.printStackTrace();
return "";
}
}
/**
* 加密
*
* @param key 密钥
* @param src 加密文本
* @return
* @throws Exception
*/
public static String encrypt2Java(String key, String src) throws Exception {
// /src = Base64.encodeToString(src.getBytes(), Base64.DEFAULT);
byte[] rawKey = toMakekey(key, keyLenght, defaultV).getBytes();// key.getBytes();
byte[] result = encrypt2Java(rawKey, src.getBytes("utf-8"));
// result = Base64.encode(result, Base64.DEFAULT);
return toHex(result);
}
/**
* 解密
*
* @param key 密钥
* @param encrypted 待揭秘文本
* @return
* @throws Exception
*/
public static String decrypt(String key, String encrypted) throws Exception {
byte[] rawKey = toMakekey(key, keyLenght, defaultV).getBytes();// key.getBytes();
byte[] enc = toByte(encrypted);
// enc = Base64.decode(enc, Base64.DEFAULT);
byte[] result = decrypt(rawKey, enc);
// /result = Base64.decode(result, Base64.DEFAULT);
return new String(result, "utf-8");
}
/**
* 密钥key ,默认补的数字补全16位数以保证安全补全至少16位长度,android和ios对接通过
*
* @param str
* @param strLength
* @param val
* @return
*/
private static String toMakekey(String str, int strLength, String val) {
int strLen = str.length();
if (strLen < strLength) {
while (strLen < strLength) {
StringBuffer buffer = new StringBuffer();
buffer.append(str).append(val);
str = buffer.toString();
strLen = str.length();
}
}
return str;
}
/**
* 真正的加密过程
* 1.通过密钥得到一个密钥专用的对象SecretKeySpec
* 2.Cipher 加密算法,加密模式和填充方式三部分或指定加密算 (可以只用写算法然后用默认的其他方式)Cipher.getInstance("AES");
*
* @param key
* @param src
* @return
* @throws Exception
*/
private static byte[] encrypt(byte[] key, byte[] src) throws Exception {
SecretKeySpec skeySpec = new SecretKeySpec(key, "AES");
Cipher cipher = Cipher.getInstance("AES");
cipher.init(Cipher.ENCRYPT_MODE, skeySpec, new IvParameterSpec(new byte[cipher.getBlockSize()]));
byte[] encrypted = cipher.doFinal(src);
return encrypted;
}
/**
* 真正的加密过程
*
* @param key
* @param src
* @return
* @throws Exception
*/
private static byte[] encrypt2Java(byte[] key, byte[] src) throws Exception {
SecretKeySpec skeySpec = new SecretKeySpec(key, "AES");
Cipher cipher = Cipher.getInstance(CIPHER_ALGORITHM);
cipher.init(Cipher.ENCRYPT_MODE, skeySpec, new IvParameterSpec(new byte[cipher.getBlockSize()]));
byte[] encrypted = cipher.doFinal(src);
return encrypted;
}
/**
* 真正的解密过程
*
* @param key
* @param encrypted
* @return
* @throws Exception
*/
private static byte[] decrypt(byte[] key, byte[] encrypted) throws Exception {
SecretKeySpec skeySpec = new SecretKeySpec(key, "AES");
Cipher cipher = Cipher.getInstance("AES");
cipher.init(Cipher.DECRYPT_MODE, skeySpec, new IvParameterSpec(new byte[cipher.getBlockSize()]));
byte[] decrypted = cipher.doFinal(encrypted);
return decrypted;
}
public static String toHex(String txt) {
return toHex(txt.getBytes());
}
public static String fromHex(String hex) {
return new String(toByte(hex));
}
/**
* 把16进制转化为字节数组
*
* @param hexString
* @return
*/
public static byte[] toByte(String hexString) {
int len = hexString.length() / 2;
byte[] result = new byte[len];
for (int i = 0; i < len; i++)
result[i] = Integer.valueOf(hexString.substring(2 * i, 2 * i + 2), 16).byteValue();
return result;
}
/**
* 二进制转字符,转成了16进制
* 0123456789abcdefg
*
* @param buf
* @return
*/
public static String toHex(byte[] buf) {
if (buf == null)
return "";
StringBuffer result = new StringBuffer(2 * buf.length);
for (int i = 0; i < buf.length; i++) {
appendHex(result, buf[i]);
}
return result.toString();
}
private static void appendHex(StringBuffer sb, byte b) {
sb.append(HEX.charAt((b >> 4) & 0x0f)).append(HEX.charAt(b & 0x0f));
}
/**
* 初始化 AES Cipher
*
* @param sKey
* @param cipherMode
* @return
*/
public static Cipher initAESCipher(String sKey, int cipherMode) {
// 创建Key gen
// KeyGenerator keyGenerator = null;
Cipher cipher = null;
try {
/*
* keyGenerator = KeyGenerator.getInstance("AES");
* keyGenerator.init(128, new SecureRandom(sKey.getBytes()));
* SecretKey secretKey = keyGenerator.generateKey(); byte[]
* codeFormat = secretKey.getEncoded(); SecretKeySpec key = new
* SecretKeySpec(codeFormat, "AES"); cipher =
* Cipher.getInstance("AES"); //初始化 cipher.init(cipherMode, key);
*/
byte[] rawKey = toMakekey(sKey, keyLenght, defaultV).getBytes();
SecretKeySpec skeySpec = new SecretKeySpec(rawKey, "AES");
cipher = Cipher.getInstance("AES");
cipher.init(cipherMode, skeySpec, new IvParameterSpec(new byte[cipher.getBlockSize()]));
} catch (NoSuchAlgorithmException e) {
e.printStackTrace(); // To change body of catch statement use File |
// Settings | File Templates.
} catch (NoSuchPaddingException e) {
e.printStackTrace(); // To change body of catch statement use File |
// Settings | File Templates.
} catch (InvalidKeyException e) {
e.printStackTrace(); // To change body of catch statement use File |
// Settings | File Templates.
} catch (InvalidAlgorithmParameterException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return cipher;
}
/**
* 对文件进行AES加密
*
* @param sourceFile
* @param fileType
* @param sKey
* @return
*/
public static File encryptFile(File sourceFile, String toFile, String dir, String sKey) {
// 新建临时加密文件
File encrypfile = null;
InputStream inputStream = null;
OutputStream outputStream = null;
try {
inputStream = new FileInputStream(sourceFile);
encrypfile = new File(dir + toFile);
outputStream = new FileOutputStream(encrypfile);
Cipher cipher = initAESCipher(sKey, Cipher.ENCRYPT_MODE);
// 以加密流写入文件
CipherInputStream cipherInputStream = new CipherInputStream(inputStream, cipher);
byte[] cache = new byte[1024];
int nRead = 0;
while ((nRead = cipherInputStream.read(cache)) != -1) {
outputStream.write(cache, 0, nRead);
outputStream.flush();
}
cipherInputStream.close();
} catch (FileNotFoundException e) {
e.printStackTrace(); // To change body of catch statement use File |
// Settings | File Templates.
} catch (IOException e) {
e.printStackTrace(); // To change body of catch statement use File |
// Settings | File Templates.
} finally {
try {
inputStream.close();
} catch (IOException e) {
e.printStackTrace(); // To change body of catch statement use
// File | Settings | File Templates.
}
try {
outputStream.close();
} catch (IOException e) {
e.printStackTrace(); // To change body of catch statement use
// File | Settings | File Templates.
}
}
return encrypfile;
}
/**
* AES方式解密文件
*
* @param sourceFile
* @return
*/
public static File decryptFile(File sourceFile, String toFile, String dir, String sKey) {
File decryptFile = null;
InputStream inputStream = null;
OutputStream outputStream = null;
try {
decryptFile = new File(dir + toFile);
Cipher cipher = initAESCipher(sKey, Cipher.DECRYPT_MODE);
inputStream = new FileInputStream(sourceFile);
outputStream = new FileOutputStream(decryptFile);
CipherOutputStream cipherOutputStream = new CipherOutputStream(outputStream, cipher);
byte[] buffer = new byte[1024];
int r;
while ((r = inputStream.read(buffer)) >= 0) {
cipherOutputStream.write(buffer, 0, r);
}
cipherOutputStream.close();
} catch (IOException e) {
e.printStackTrace(); // To change body of catch statement use File |
// Settings | File Templates.
} finally {
try {
inputStream.close();
} catch (IOException e) {
e.printStackTrace(); // To change body of catch statement use
// File | Settings | File Templates.
}
try {
outputStream.close();
} catch (IOException e) {
e.printStackTrace(); // To change body of catch statement use
// File | Settings | File Templates.
}
}
return decryptFile;
}
}

View File

@@ -0,0 +1,136 @@
package com.info.sn.utils;
import android.content.Context;
import android.content.pm.IPackageDataObserver;
import android.content.pm.IPackageManager;
import android.content.pm.IPackageStatsObserver;
import android.content.pm.PackageManager;
import android.content.pm.PackageStats;
import android.os.RemoteException;
import android.os.ServiceManager;
import android.util.Log;
import java.lang.reflect.Method;
public class CacheUtils {
private static final String TAG = CacheUtils.class.getSimpleName();
private final long MAX_WAIT_TIME = 60 * 1000;
private final long WAIT_TIME_INCR = 10 * 1000;
/**
* 获取应用数据大小 cache + data
*
* @param context
* @param packageName
* @return
* @throws Exception
*/
public long getApplicationCache(Context context, String packageName) throws Exception {
try {
PackageStatsObserver observer = new PackageStatsObserver();
// wait on observer
synchronized (observer) {
Method method = PackageManager.class.getMethod("getPackageSizeInfo", new Class[] { String.class, IPackageStatsObserver.class });
method.invoke(context.getPackageManager(), packageName, observer);
// getPm().getPackageSizeInfo(packageName, UserHandle.myUserId(), 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 PackageStatsObserver.onGetStatsCompleted");
}
}
Log.d(TAG, "toString " + observer.stats.toString());
return observer.stats.dataSize + observer.stats.cacheSize;
} catch (RemoteException e) {
Log.w(TAG, "Failed to get handle for PackageManger Exception: " + e);
return -1;
} catch (InterruptedException e) {
Log.w(TAG, "InterruptedException :" + e);
return -1;
}
}
/**
* 清除应用数据
*
* @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;
}
}
private IPackageManager getPm() {
return IPackageManager.Stub.asInterface(ServiceManager.getService("package"));
}
class PackageDataObserver extends IPackageDataObserver.Stub {
public boolean retValue = false;
private boolean doneFlag = false;
public void onRemoveCompleted(String packageName, boolean succeeded) throws RemoteException {
synchronized (this) {
retValue = succeeded;
doneFlag = true;
notifyAll();
}
}
public boolean isDone() {
return doneFlag;
}
}
class PackageStatsObserver extends IPackageStatsObserver.Stub {
public boolean retValue = false;
public PackageStats stats;
private boolean doneFlag = false;
public void onGetStatsCompleted(PackageStats pStats, boolean succeeded) throws RemoteException {
synchronized (this) {
retValue = succeeded;
stats = pStats;
doneFlag = true;
notifyAll();
}
}
public boolean isDone() {
return doneFlag;
}
}
}

View File

@@ -1,28 +0,0 @@
package com.info.sn.utils;
public class CommonData {
public static final String MAJOR_ACTION = "MAJOR_ACTION";
public static final String FLAG_FIRST_ENTER = "first_enter";
public static final String SP_USER_ID = "user_ID";
public static final String SP_USER_PHONE = "user_phone";
public static final String SP_USER_NAME = "user_name";
public static final String SP_USER_IDCARD = "user_idcard";
public static final String SP_USER_PASSWORD = "user_pass";
public static final String SP_RECOMMEND_PHONE = "recommend_phone";
public static final String SP_RECOMMEND_NAME = "sup_name";
public static final String SP_USER_LEVEL = "user_level";
public static final String SP_ISLOGINED = "user_islogined";
public static final String NEXT_PAGE = "next_page";
public static final String BANK_NAME = "bank_name";
public static final String OPERATOR_NAME = "bank_name";
public static final String PRODUCT_LINK = "product_link";
public static final String PRODUCT_NAME = "product_name";
}

View File

@@ -0,0 +1,31 @@
package com.info.sn.utils;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
public class Hash {
private static final char[] hexCode = "0123456789ABCDEF".toCharArray();
public static String md5(String input) {
byte[] bytes = new byte[0];
try {
bytes = MessageDigest.getInstance("MD5").digest(input.getBytes());
return printHexBinary(bytes);
} catch (NoSuchAlgorithmException e) {
e.printStackTrace();
return "";
}
}
public static String printHexBinary(byte[] data) {
StringBuilder r = new StringBuilder(data.length * 2);
for (byte b : data) {
r.append(hexCode[(b >> 4) & 0xF]);
r.append(hexCode[(b & 0xF)]);
}
return r.toString();
}
}

View File

@@ -5,14 +5,16 @@ import android.app.ActivityManager;
import android.app.ActivityManagerNative;
import android.app.ActivityTaskManager;
import android.content.ComponentName;
import android.content.ContentResolver;
import android.content.Context;
import android.content.ContextWrapper;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.pm.ApplicationInfo;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.content.pm.UserInfo;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.net.Uri;
import android.os.BatteryManager;
import android.os.Build;
@@ -22,20 +24,12 @@ import android.provider.Settings;
import android.text.TextUtils;
import android.util.Log;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.google.gson.JsonObject;
import com.info.sn.BuildConfig;
import com.info.sn.service.RemoteService;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.lang.reflect.Constructor;
import java.lang.reflect.Field;
import java.lang.reflect.Method;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
@@ -48,6 +42,7 @@ import static android.app.ActivityManager.RECENT_IGNORE_UNAVAILABLE;
public class JGYUtils {
private static final String TAG = JGYUtils.class.getSimpleName();
@SuppressLint("StaticFieldLeak")
private static JGYUtils sInstance;
private Context mContext;
public static int MTKPlatform = 1;
@@ -90,7 +85,6 @@ public class JGYUtils {
}
private int getBatteryLevel() {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
BatteryManager batteryManager = (BatteryManager) mContext.getSystemService(Context.BATTERY_SERVICE);
@@ -162,23 +156,21 @@ public class JGYUtils {
}
String olddeselectViewArray = Settings.System.getString(mContext.getContentResolver(), "qch_app_forbid_id");
String olddeselectViewArray = JGYUtils.getString(mContext.getContentResolver(), "qch_app_forbid_id");
Log.e("writeDeselectIDtoSystem", "olddeselectViewArray: " + olddeselectViewArray);
Settings.System.putString(mContext.getContentResolver(), "qch_app_forbid_id", packageStringBuilder.toString());
Settings.System.putString(mContext.getContentResolver(), "DeselectViewArray", idStringBuilder.toString());
JGYUtils.putString(mContext.getContentResolver(), "qch_app_forbid_id", packageStringBuilder.toString());
JGYUtils.putString(mContext.getContentResolver(), "DeselectViewArray", idStringBuilder.toString());
Log.e("writeDeselectIDtoSystem", "qch_app_forbid_id: " + packageStringBuilder.toString());
Log.e("writeDeselectIDtoSystem", "deselectViewArray: " + idStringBuilder.toString());
} else {
Log.e("writeDeselectIDtoSystem", "writeDeselectIDtoSystem is null:");
Settings.System.putString(mContext.getContentResolver(), "qch_app_forbid_id", "");
Settings.System.putString(mContext.getContentResolver(), "DeselectViewArray", "");
JGYUtils.putString(mContext.getContentResolver(), "qch_app_forbid_id", " ");
JGYUtils.putString(mContext.getContentResolver(), "DeselectViewArray", " ");
}
}
private static void sendAllweb(Context context) {
Intent intent = new Intent("qch_app_website")
.setPackage("com.android.settings");
@@ -211,7 +203,10 @@ public class JGYUtils {
return value;
}
public void hookWebView() {
/**
* 系统应用hook使用webview
*/
public static void hookWebView() {
int sdkInt = Build.VERSION.SDK_INT;
try {
Class<?> factoryClass = Class.forName("android.webkit.WebViewFactory");
@@ -287,6 +282,12 @@ public class JGYUtils {
}
}
public void killPackage(String pkg) {
ActivityManager manager = (ActivityManager) mContext.getSystemService(Context.ACTIVITY_SERVICE);
manager.killBackgroundProcesses(pkg);
CmdUtil.execute("am force-stop " + pkg);
}
public void KillOTA() {
ActivityManager manager = (ActivityManager) mContext.getSystemService(Context.ACTIVITY_SERVICE);
manager.killBackgroundProcesses("com.adups.fota");
@@ -301,6 +302,32 @@ public class JGYUtils {
mContext.startActivity(intent);
}
public void openLauncher() {
Log.e(TAG, "openLauncher: ");
killPackage("com.android.launcher3");
Intent intent = new Intent();
// 为Intent设置Action、Category属性
intent.setAction(Intent.ACTION_MAIN);// "android.intent.action.MAIN"
intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
intent.addCategory(Intent.CATEGORY_HOME); //"android.intent.category.HOME"
mContext.startActivity(intent);
}
public void cleanLauncherCache() {
Log.e(TAG, "cleanLauncherCache: Start");
int cleaned = (int) SPUtils.get(mContext, "fristcleanLauncherCache", 0);
if (cleaned == 0) {
try {
new CacheUtils().cleanApplicationUserData(mContext, "com.android.launcher3");
SPUtils.put(mContext, "fristcleanLauncherCache", 1);
Log.e(TAG, "cleanLauncherCache: end");
} catch (Exception e) {
e.printStackTrace();
Log.e(TAG, "cleanLauncherCache: " + e.getMessage());
}
}
}
public int checkSNPlatform(String sn) {
String secondChars = sn.substring(1, 2);
if ("N".equalsIgnoreCase(secondChars)) {//MTK平台
@@ -351,6 +378,22 @@ public class JGYUtils {
}
}
public static String getCustomVersion() {
if (JGYUtils.getInstance().checkAppPlatform() == JGYUtils.ZhanruiPlatform) {
return Utils.getProperty("ro.build.display.id", "获取失败");
} else {
return Utils.getProperty("ro.custom.build.version", "获取失败");
}
}
public static String getRomVersion() {
if (JGYUtils.getInstance().checkAppPlatform() == JGYUtils.ZhanruiPlatform) {
return Utils.getProperty("ro.build.id", "获取失败");
} else {
return Utils.getProperty("ro.build.display.id", "获取失败");
}
}
public void killBackgroundProcesses(Context context, String processName) {
gotoLauncher();
// mIsScanning = true;
@@ -452,4 +495,119 @@ public class JGYUtils {
}
}
public static int isWifiConnect(Context context) {
// 网络管理对象
ConnectivityManager cm = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
// 获取所有类型的链接管理对象
NetworkInfo info = cm.getNetworkInfo(ConnectivityManager.TYPE_WIFI);
NetworkInfo.State state = info.getState();
if (NetworkInfo.State.CONNECTED == state) {
return 1;
}
return 0;
}
synchronized public static int getInt(ContentResolver cr, String name, int def) {
Log.i(TAG, "getInt: " + name);
return Settings.System.getInt(cr, name, def);
}
synchronized public static int getInt(ContentResolver cr, String name) throws Settings.SettingNotFoundException {
Log.i(TAG, "getInt: " + name);
return Settings.System.getInt(cr, name);
}
synchronized public static String getString(ContentResolver cr, String name) {
Log.i(TAG, "getString: " + name);
return Settings.System.getString(cr, name);
}
synchronized public static boolean putInt(ContentResolver cr, String name, int value) {
Log.i(TAG, "putInt: " + "name = " + name + ", value = " + value);
return Settings.System.putInt(cr, name, value);
}
synchronized public static boolean putString(ContentResolver cr, String name, String value) {
Log.i(TAG, "putString: " + "name = " + name + ", value = " + value);
return Settings.System.putString(cr, name, value);
}
/**
* 获取当前进程名
*/
public static String getCurrentProcessName(Context context) {
int pid = android.os.Process.myPid();
String processName = "";
ActivityManager manager = (ActivityManager) context.getSystemService
(Context.ACTIVITY_SERVICE);
for (ActivityManager.RunningAppProcessInfo process : manager.getRunningAppProcesses()) {
if (process.pid == pid) {
processName = process.processName;
}
}
return processName;
}
public void setDefaultDesktop(Context context, String pkg, String className) {
Intent intent = new Intent("setDefaultLauncher");
intent.putExtra("package", pkg);
intent.putExtra("className", className);
intent.setPackage("com.android.settings");
context.sendBroadcast(intent);
}
public static ArrayList<String> getForbidList(Context context) {
ArrayList<String> disableApp = new ArrayList<>();
if ((int) SPUtils.get(context, "search_topic", 0) == 0) {
disableApp.add("拍照搜题");
}
if (JGYUtils.getInt(context.getContentResolver(), "qch_app_camera", 0) == 1) {
disableApp.add("com.mediatek.camera");
}
if (JGYUtils.getInt(context.getContentResolver(), "qch_app_filemanager", 0) == 1) {
disableApp.add("com.android.documentsui");
disableApp.add("com.mediatek.filemanager");
}
if (JGYUtils.getInt(context.getContentResolver(), "qch_app_soundrecorder", 0) == 1) {
disableApp.add("com.android.soundrecorder");
}
if (JGYUtils.getInt(context.getContentResolver(), "qch_app_gallery", 0) == 1) {
disableApp.add("com.android.gallery3d");
}
if (JGYUtils.getInt(context.getContentResolver(), "qch_app_music", 0) == 1) {
disableApp.add("com.android.music");
}
Log.e(TAG, "getForbidAPP: " + disableApp);
return disableApp;
}
private static final String UPDATE_FORBID_APP = "UPDATE_FORBID_APP";
public static void updateForbidList(Context context) {
Intent intent = new Intent(UPDATE_FORBID_APP);
intent.putStringArrayListExtra("forbid_app_list", getForbidList(context));
intent.setPackage("com.jiaoguanyi.os");
intent.setPackage("com.tt.ttutils");
context.sendBroadcast(intent);
}
public static ArrayList<String> getHideList(Context context) {
String appString = (String) SPUtils.get(context, "Hide_APP_List", "");
Log.e(TAG, "Hide_APP_List: " + appString);
if (TextUtils.isEmpty(appString)) {
return new ArrayList<>();
} else {
return new ArrayList<>(Arrays.asList(appString.split(",")));
}
}
private static final String UPDATE_HIDE_APP = "UPDATE_HIDE_APP";
public static void updateHideList(Context context) {
Intent intent = new Intent(UPDATE_HIDE_APP);
intent.putStringArrayListExtra("hide_app_list", getHideList(context));
intent.setPackage("com.jiaoguanyi.os");
intent.setPackage("com.tt.ttutils");
context.sendBroadcast(intent);
}
}

View File

@@ -0,0 +1,205 @@
package com.info.sn.utils;
import android.annotation.SuppressLint;
import android.content.ActivityNotFoundException;
import android.content.Context;
import android.content.Intent;
import android.net.Uri;
import android.net.wifi.WifiInfo;
import android.net.wifi.WifiManager;
import android.os.Build;
import android.text.TextUtils;
import android.util.Log;
import com.info.sn.config.Scheme;
import java.net.NetworkInterface;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
public class LaunchTools {
private static String TAG = LaunchTools.class.getSimpleName();
public static void goGankao(Context mContext, String scheme, String str) {
try {
String _str = to(mContext, scheme, str);
android.util.Log.d("wlDebug", _str);
Uri uri = Uri.parse(_str);
Intent intent = new Intent(Intent.ACTION_VIEW, uri);
intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
mContext.startActivity(intent);
} catch (ActivityNotFoundException e) {
}
}
/**
* https://gankao.yuque.com/docs/share/69e3a9b3-8a13-429c-9af2-fa7d29c46b5f#mTy5k
*
* @param mContext
* @param schemeHead
* @param str
* @return
*/
public static String to(Context mContext, String schemeHead, String str) {
Map<String, String> keys = new HashMap<>();//参数集合
String publicSecret = Scheme.getPublicSecret();//公共密钥赶考提供
String partner_id = Scheme.partner_id;//合作渠道号赶考提供
String device_id = getLocalMacAddress(mContext);//设备mac地址-这里自己获取mac地址即可或者是自己的账号
// device_id = "00:08:22:ae:70:59";
String page = Uri.encode(str);//传入指定页面的scheme地址-需编码
keys.put("device_id", Uri.encode(device_id));//需编码
keys.put("partner_id", partner_id);
keys.put("page", page);
StringBuilder st = new StringBuilder("");
List<Map.Entry<String, String>> list = new ArrayList<Map.Entry<String, String>>(keys.entrySet());
// 通过比较器来实现参数首字母的升序排列
Collections.sort(list, new Comparator<Map.Entry<String, String>>() {
@Override
public int compare(Map.Entry<String, String> o1, Map.Entry<String, String> o2) {
//进行key比较
return o1.getKey().compareTo(o2.getKey());
}
});
//排序后的参数并且
for (Map.Entry<String, String> key : list) {
st = st.append(key.getKey() + "=" + key.getValue() + "&");
}
//得到md5签名
String sign = md5(st.toString().substring(0, st.toString().length() - 1) + publicSecret);
String _result = schemeHead + "://loginFromPartner?device_id=" + device_id + "&partner_id=" + partner_id + "&page=" + page + "&sign=" + sign;
return _result;
}
public static String toUserCenter(Context mContext, Map<String, String> keys, String str) {
String publicSecret = Scheme.getPublicSecret();//公共密钥赶考提供
String partner_id = Scheme.partner_id;//合作渠道号赶考提供
String device_id = getLocalMacAddress(mContext);//设备mac地址-这里自己获取mac地址即可或者是自己的账号
// device_id = "00:08:22:ae:70:59";
// String page = Uri.encode(str);//传入指定页面的scheme地址-需编码
// keys.put("device_id", Uri.encode(device_id));//需编码
// keys.put("partner_id", partner_id);
keys.put("page", str);
StringBuilder st = new StringBuilder("");
List<Map.Entry<String, String>> list = new ArrayList<Map.Entry<String, String>>(keys.entrySet());
// 通过比较器来实现参数首字母的升序排列
Collections.sort(list, new Comparator<Map.Entry<String, String>>() {
@Override
public int compare(Map.Entry<String, String> o1, Map.Entry<String, String> o2) {
//进行key比较
return o1.getKey().compareTo(o2.getKey());
}
});
//排序后的参数并且
for (Map.Entry<String, String> key : list) {
st = st.append(key.getKey() + "=" + key.getValue() + "&");
}
Log.e("toUserCenter", "st: " + st);
//得到md5签名
String sign = md5(st.toString().substring(0, st.toString().length() - 1) + publicSecret);
String _result = "gankao://loginFromPartner?" + st + "sign=" + sign;
Log.e("toUserCenter", "_result: " + _result);
return _result;
}
/**
* https://gankao.yuque.com/docs/share/007ac4bd-7442-46a0-976b-9ad09b22d3c8#PXO8t
*
* @param params
* @return
*/
public static String getToken(HashMap<String, String> params) {
List<Map.Entry<String, String>> list = new ArrayList<Map.Entry<String, String>>(params.entrySet());
// 通过比较器来实现参数首字母的升序排列
Collections.sort(list, new Comparator<Map.Entry<String, String>>() {
@Override
public int compare(Map.Entry<String, String> o1, Map.Entry<String, String> o2) {
//进行key比较
return o1.getKey().compareTo(o2.getKey());
}
});
//排序后的参数并且
StringBuilder st = new StringBuilder("");
for (Map.Entry<String, String> key : list) {
st = st.append(key.getValue());
}
//得到md5签名
String token = md5(st.toString() + Scheme.getPublicSecret());
return token;
}
public static String md5(String string) {
if (TextUtils.isEmpty(string)) {
return "";
}
MessageDigest md5 = null;
try {
md5 = MessageDigest.getInstance("MD5");
byte[] bytes = md5.digest(string.getBytes());
StringBuilder result = new StringBuilder();
for (byte b : bytes) {
String temp = Integer.toHexString(b & 0xff);
if (temp.length() == 1) {
temp = "0" + temp;
}
result.append(temp);
}
return result.toString();
} catch (NoSuchAlgorithmException e) {
e.printStackTrace();
}
return "";
}
@SuppressLint("ObsoleteSdkInt")
public static String getLocalMacAddress(Context context) {
String mac;
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP_MR1) {
mac = getNewMac();
} else {
WifiManager wifi = (WifiManager) context
.getSystemService(Context.WIFI_SERVICE);
WifiInfo info = wifi.getConnectionInfo();
mac = info.getMacAddress().replace(":", "");
}
if (mac != null) {
mac = mac.toLowerCase();
}
return mac;
}
private static String getNewMac() {
try {
List<NetworkInterface> all = Collections.list(NetworkInterface.getNetworkInterfaces());
for (NetworkInterface nif : all) {
if (!nif.getName().equalsIgnoreCase("wlan0")) continue;
byte[] macBytes = nif.getHardwareAddress();
if (macBytes == null) {
return null;
}
StringBuilder res1 = new StringBuilder();
for (byte b : macBytes) {
res1.append(String.format("%02X:", b));
}
if (res1.length() > 0) {
res1.deleteCharAt(res1.length() - 1);
}
return res1.toString();
}
} catch (Exception ex) {
ex.printStackTrace();
}
return null;
}
}

View File

@@ -1,144 +0,0 @@
package com.info.sn.utils;
import android.graphics.drawable.Drawable;
public class LocalAppInfo {
public static final int DOWNLOAD_STATUS_NORMAL = 0;
public static final int DOWNLOAD_STATUS_DOWNLOADING = 1;
public static final int DOWNLOAD_STATUS_PAUSE = 2;
private Drawable icon;
private String iconUrl = "";
private String appName;
private String packageName;
private String version;
private String latestVersion = "";
private int size;
private String latestSize;
private String downLoadUrl;
private int dowloadStatus = DOWNLOAD_STATUS_NORMAL;
private String tip;
private int id;
public Drawable getIcon() {
return icon;
}
public void setIcon(Drawable icon) {
this.icon = icon;
}
public String getIconUrl() {
return iconUrl;
}
public void setIconUrl(String iconUrl) {
this.iconUrl = iconUrl;
}
public String getAppName() {
return appName;
}
public void setAppName(String appName) {
this.appName = appName;
}
public String getPackageName() {
return packageName;
}
public void setPackageName(String packageName) {
this.packageName = packageName;
}
public String getVersion() {
return version;
}
public void setVersion(String version) {
this.version = version;
}
public int getSize() {
return size;
}
public void setSize(int size) {
this.size = size;
}
public String getLatestVersion() {
return latestVersion;
}
public void setLatestVersion(String latestVersion) {
this.latestVersion = latestVersion;
}
public String getLatestSize() {
return latestSize;
}
public void setLatestSize(String latestSize) {
this.latestSize = latestSize;
}
public String getDownLoadUrl() {
return downLoadUrl;
}
public void setDownLoadUrl(String downLoadUrl) {
this.downLoadUrl = downLoadUrl;
}
public int getDowloadStatus() {
return dowloadStatus;
}
public void setDowloadStatus(int dowloadStatus) {
this.dowloadStatus = dowloadStatus;
}
public String getTip() {
return tip;
}
public void setTip(String tip) {
this.tip = tip;
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
@Override
public String toString() {
return "AppUpdateInfo{" +
"packageName='" + packageName + '\'' +
", version='" + version + '\'' +
'}';
}
public boolean equals(Object obj) {
if (this == obj) //传入的对象就是它自己如s.equals(s);肯定是相等的;
return true;
if (obj == null) //如果传入的对象是空,肯定不相等
return false;
if (getClass() != obj.getClass()) //如果不是同一个类型的如Studnet类和Animal类
//也不用比较了,肯定是不相等的
return false;
LocalAppInfo other = (LocalAppInfo) obj;
if (packageName == null) {
if (other.packageName != null)
return false;
} else if (!packageName.equals(other.packageName)) //如果name属性相等则相等
return false;
return true;
}
}

View File

@@ -1,42 +0,0 @@
package com.info.sn.utils;
import android.util.Log;
import com.info.sn.BuildConfig;
/**
* @author Administrator
*/
public class LogUtils {
static boolean isDebug = BuildConfig.DEBUG;
public static void v(String tag, String msg) {
if (isDebug) {
Log.v(tag, msg);
}
}
public static void d(String tag, String msg) {
if (isDebug) {
Log.d(tag, msg);
}
}
public static void i(String tag, String msg) {
if (isDebug) {
Log.i(tag, msg);
}
}
public static void w(String tag, String msg) {
if (isDebug) {
Log.w(tag, msg);
}
}
public static void e(String tag, String msg) {
if (isDebug) {
Log.e(tag, msg);
}
}
}

View File

@@ -4,13 +4,12 @@ import android.app.ActivityManager;
import android.content.Context;
import android.util.Log;
import com.info.sn.base.MyApplication;
public class ServiceAliveUtils {
public static boolean isServiceAlice(String className) {
public static boolean isServiceAlice(Context context,String className) {
boolean isServiceRunning = false;
ActivityManager manager =
(ActivityManager) MyApplication.getAppContext().getSystemService(Context.ACTIVITY_SERVICE);
(ActivityManager) context.getSystemService(Context.ACTIVITY_SERVICE);
if (manager == null) {
return false;
}

View File

@@ -0,0 +1,124 @@
package com.info.sn.utils;
import android.content.Context;
import android.os.Build;
import android.os.Environment;
import android.os.storage.StorageManager;
import java.io.File;
import java.lang.reflect.Array;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.text.DecimalFormat;
public class StorageUtils {
// 获取存储空间 false 内置sd卡路径true 外置sd卡路径
public static File getStoragePath(Context mContext, boolean isSDcard) {
StorageManager mStorageManager = (StorageManager) mContext.getSystemService(Context.STORAGE_SERVICE);
Class<?> storageVolumeClazz = null;
try {
storageVolumeClazz = Class.forName("android.os.storage.StorageVolume");
Method getVolumeList = mStorageManager.getClass().getMethod("getVolumeList");
Method getPath = storageVolumeClazz.getMethod("getPath");
Method isRemovable = storageVolumeClazz.getMethod("isRemovable");
Object result = getVolumeList.invoke(mStorageManager);
final int length = Array.getLength(result);
for (int i = 0; i < length; i++) {
Object storageVolumeElement = Array.get(result, i);
String path = (String) getPath.invoke(storageVolumeElement);
boolean removable = (Boolean) isRemovable.invoke(storageVolumeElement);
if (isSDcard == removable) {
File file = new File(path);
if (file.exists()) {
return file;
}else {
if (!isSDcard) {
return Environment.getExternalStorageDirectory();
} else {
File file1 = new File("root/storage/sdcard1");
if (file1.exists()){
return file1;
}else {
File file2 = new File("storage/sdcard1");
if (file2.exists()){
return file2;
}else {
File file3 = new File("/storage/emulated/0");
if (file3.exists()){
return file3;
}else {
return null;
}
}
}
}
}
}
}
} catch (ClassNotFoundException e) {
e.printStackTrace();
} catch (InvocationTargetException e) {
e.printStackTrace();
} catch (NoSuchMethodException e) {
e.printStackTrace();
} catch (IllegalAccessException e) {
e.printStackTrace();
}
return null;
}
public static String getFileCache(Context context, String s) {
return getExternalFilesDir(context, s).getAbsolutePath();
}
public static String getFileRoot(Context context) {
return getExternalFilesDir(context, "Download").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);
}
// 检测文件是否存在
public static boolean isFileIsExists(String filePath){
try{
File f=new File(filePath);
if(!f.exists()){
return false;
}
}catch (Exception e) {
return false;
}
return true;
}
public static String size(long size) {
if (size / (1024 * 1024) > 0) {
float tmpSize = (float) (size) / (float) (1024 * 1024 );
DecimalFormat df = new DecimalFormat("#.##");
return "" + df.format(tmpSize) + "GB";
} else if (size / 1024 > 0) {
float tmpSize = (float) (size) / (float) 1024 ;
DecimalFormat df = new DecimalFormat("#.##");
return "" + df.format(tmpSize) + "MB";
} else if (size > 0) {
return "" + (size ) + "KB";
} else {
return "" + (size) + "KB";
}
}
}

View File

@@ -2,22 +2,32 @@ package com.info.sn.utils;
import android.content.Context;
import android.content.Intent;
import android.nfc.Tag;
import android.os.SystemClock;
import android.text.TextUtils;
import android.util.Log;
import androidx.annotation.NonNull;
import com.info.sn.service.InitJpushServer;
import com.info.sn.service.ManagerService;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.InetAddress;
import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Arrays;
import java.util.Calendar;
import java.util.Date;
public class TimeUtils {
private static final String TAG = TimeUtils.class.getSimpleName();
private static DateFormat df = new SimpleDateFormat("HH:mm");
public static final String START_TIME_KEY = "START_TIME";
public static final String END_TIME_KEY = "END_TIME";
public static final String WEEK_START_TIME_KEY = "WEEK_START_TIME";
public static final String WEEK_END_TIME_KEY = "WEEK_END_TIME";
public static long dayTime = 60 * 60 * 24 * 1000;
public static String getNowTime() {
@@ -33,11 +43,12 @@ public class TimeUtils {
//
// }
public static ContralTime String2ContralTime(Context context, @NonNull String timeText) {
public static ContralTime String2WorkingTime(Context context, @NonNull String timeText) {
DateFormat df = ContralTime.getDf();
String[] time = timeText.trim().split("-");
if (time.length != 2) {
throw new RuntimeException("Time format error!");
// return null;
throw new RuntimeException("Time format error!" + Arrays.toString(time));
}
try {
SPUtils.put(context, START_TIME_KEY, time[0].trim());
@@ -59,10 +70,63 @@ public class TimeUtils {
}
}
public static ContralTime getDefaltContralTime(Context context) {
public static ContralTime String2WeekTime(Context context, @NonNull String timeText) {
DateFormat df = ContralTime.getDf();
String[] time = timeText.trim().split("-");
if (time.length != 2) {
// return null;
throw new RuntimeException("Time format error!" + Arrays.toString(time));
}
try {
SPUtils.put(context, WEEK_START_TIME_KEY, time[0].trim());
SPUtils.put(context, WEEK_END_TIME_KEY, time[1].trim());
Date startDate = df.parse(time[0].trim());
Date endDate = df.parse(time[1].trim());
ContralTime contralTime = new ContralTime();
// if (date1.getTime() < date2.getTime()) {
contralTime.setStartTime(df.format(startDate));
contralTime.setEndTime(df.format(endDate));
// } else {
// contralTime.setStartTime(df.format(date2));
// contralTime.setEndTime(df.format(date1));
// }
return contralTime;
} catch (ParseException e) {
e.printStackTrace();
return null;
}
}
public static ContralTime getWorkingDayContralTime(Context context) {
String startTime = (String) SPUtils.get(context, START_TIME_KEY, "00:00");
String endTime = (String) SPUtils.get(context, END_TIME_KEY, "00:00");
if (null == startTime || null == endTime || (startTime.equals("00:00") && endTime.equals("00:00"))) {
return getContralTime(context, startTime, endTime);
}
public static ContralTime getWeekDayContralTime(Context context) {
String startTime = (String) SPUtils.get(context, WEEK_START_TIME_KEY, "00:00");
String endTime = (String) SPUtils.get(context, WEEK_END_TIME_KEY, "00:00");
return getContralTime(context, startTime, endTime);
}
public static boolean inContralTime(ContralTime workingTime, ContralTime weekTime) {
if (inWeekDay()) {
if (weekTime == null) {
return false;
} else {
return weekTime.inControlTime();
}
} else {
if (workingTime == null) {
return false;
} else {
return workingTime.inControlTime();
}
}
}
public static ContralTime getContralTime(Context context, String startTime, String endTime) {
if (null == startTime || null == endTime || ("00:00".equals(startTime) && "00:00".equals(endTime))) {
return null;
} else {
try {
@@ -79,28 +143,139 @@ public class TimeUtils {
}
}
public static String getNowTimeString(Context context) {
ContralTime work = getWorkingDayContralTime(context);
ContralTime week = getWeekDayContralTime(context);
StringBuilder stringBuilder = new StringBuilder();
if (work != null) {
stringBuilder.append("周一至周五:").append(work).append("\n");
}
if (week != null) {
stringBuilder.append("周末:").append(week);
}
return stringBuilder.toString();
}
public static void setEmpty(Context context) {
SPUtils.put(context, START_TIME_KEY, "00:00");
SPUtils.put(context, END_TIME_KEY, "00:00");
SPUtils.put(context, WEEK_START_TIME_KEY, "00:00");
SPUtils.put(context, WEEK_END_TIME_KEY, "00:00");
Intent intent = new Intent();
intent.setAction(InitJpushServer.TimeChangedReceiver.ACTION_UPDATE);
intent.setAction(ManagerService.ACTION_UPDATE);
context.sendBroadcast(intent);
}
/**
* 获取格式化后的时间
*
* @param time 时间戳
* @return 时间戳格式化文本
*/
public static String getDate(long time) {
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss");
String finaWayDate = sdf.format(time);
Log.e(TAG, "getDate: " + finaWayDate);
return finaWayDate;
}
/**
* 获取周几
*
* @return 周几的数字
*/
public static int getWeekDay() {
long time = System.currentTimeMillis();
Log.e(TAG, "getWeekDay: " + time);
return getWeekDay(time);
}
/**
* 获取周几
*
* @param time 时间戳
* @return 周几的数字 1-7
*/
public static int getWeekDay(long time) {
getDate(time);
Calendar now = Calendar.getInstance();
now.setTimeInMillis(time);
//一周第一天是否为星期天
boolean isFirstSunday = (now.getFirstDayOfWeek() == Calendar.SUNDAY);
//获取周几
int weekDay = now.get(Calendar.DAY_OF_WEEK);
//若一周第一天为星期天,则-1
if (isFirstSunday) {
weekDay = weekDay - 1;
if (weekDay == 0) {
weekDay = 7;
}
}
return weekDay;
}
private String[] weekDays = {"星期一", "星期二", "星期三", "星期四", "星期五", "星期六", "星期日"};
/**
* 获取星期几
*
* @return 星期的文本
*/
public String getWeekDayString() {
return weekDays[getWeekDay() - 1];
}
/**
* 获取星期几
*
* @param time 时间戳
* @return 星期的文本
*/
public String getWeekDayString(long time) {
return weekDays[getWeekDay(time) - 1];
}
/**
* 是否未周末
*
* @return 周末返回ture 工作日返回false
*/
public static boolean inWeekDay() {
long time = System.currentTimeMillis();
return inWeekDay(time);
}
/**
* 是否未周末
*
* @param time 时间戳
* @return 周末返回ture 工作日返回false
*/
public static boolean inWeekDay(long time) {
int weekDay = getWeekDay(time);
if (weekDay > 5) {
return true;
} else {
return false;
}
}
public static void setSystemTime(long time) {
SystemClock.setCurrentTimeMillis(time);
}
public static class ContralTime {
//format HH:mm
static String startTime;
static String endTime;
String startTime;
String endTime;
public ContralTime() {
}
public ContralTime(String startT, String endT) {
startTime = startT;
endTime = endT;
this.startTime = startT;
this.endTime = endT;
}
public String getStartTime() {
@@ -109,7 +284,7 @@ public class TimeUtils {
public void setStartTime(String startT) {
startTime = startT;
this.startTime = startT;
}
public String getEndTime() {
@@ -117,7 +292,7 @@ public class TimeUtils {
}
public void setEndTime(String endT) {
endTime = endT;
this.endTime = endT;
}
public static DateFormat getDf() {
@@ -132,6 +307,11 @@ public class TimeUtils {
return df.format(new Date(time));
}
public boolean inControlTime() {
long time = System.currentTimeMillis();
return inControlTime(time);
}
public boolean inControlTime(long time) {
return inControlTime(df.format(new Date(time)));
}
@@ -169,4 +349,218 @@ public class TimeUtils {
return startTime + "\t-\t" + endTime;
}
}
private static SntpClient mNtpClient;
public static long getTimeFromNtpServer(String hostAddress) {
Log.d(TAG, "getTimeFromNtpServer()");
if (TextUtils.isEmpty(hostAddress)) {
Log.e(TAG, "Ntp host is null.");
return -1;
}
if (mNtpClient == null) {
mNtpClient = new SntpClient();
}
boolean isSuccessful = mNtpClient.requestTime(hostAddress, 20000);
Log.e(TAG, "requestTime:" + isSuccessful);
if (isSuccessful) {
long now = mNtpClient.getNtpTime();//now就是获取的时间
return now;
} else {
}
return -1;
}
public static class SntpClient {
private static final String TAG = "SntpClient";
private static final int REFERENCE_TIME_OFFSET = 16;
private static final int ORIGINATE_TIME_OFFSET = 24;
private static final int RECEIVE_TIME_OFFSET = 32;
private static final int TRANSMIT_TIME_OFFSET = 40;
private static final int NTP_PACKET_SIZE = 48;
private static final int NTP_PORT = 123;
private static final int NTP_MODE_CLIENT = 3;
private static final int NTP_VERSION = 3;
// Number of seconds between Jan 1, 1900 and Jan 1, 1970
// 70 years plus 17 leap days
private static final long OFFSET_1900_TO_1970 = ((365L * 70L) + 17L) * 24L * 60L * 60L;
// system time computed from NTP server response
private long mNtpTime;
// value of SystemClock.elapsedRealtime() corresponding to mNtpTime
private long mNtpTimeReference;
// round trip time in milliseconds
private long mRoundTripTime;
/**
* Sends an SNTP request to the given host and processes the response.
*
* @param host host name of the server.
* @param timeout network timeout in milliseconds.
* @return true if the transaction was successful.
*/
public boolean requestTime(String host, int timeout) {
DatagramSocket socket = null;
try {
socket = new DatagramSocket();
socket.setSoTimeout(timeout);
InetAddress address = InetAddress.getByName(host);
byte[] buffer = new byte[NTP_PACKET_SIZE];
DatagramPacket request = new DatagramPacket(buffer,
buffer.length, address, NTP_PORT);
// set mode = 3 (client) and version = 3
// mode is in low 3 bits of first byte
// version is in bits 3-5 of first byte
buffer[0] = NTP_MODE_CLIENT | (NTP_VERSION << 3);
// get current time and write it to the request packet
long requestTime = System.currentTimeMillis();
Log.d(TAG, "RequestTime:" + new Date(requestTime));
long requestTicks = SystemClock.elapsedRealtime();
writeTimeStamp(buffer, TRANSMIT_TIME_OFFSET, requestTime);
socket.send(request);
// read the response
DatagramPacket response = new DatagramPacket(buffer,
buffer.length);
socket.receive(response);
long responseTicks = SystemClock.elapsedRealtime();
long responseTime = requestTime
+ (responseTicks - requestTicks);
// extract the results
long originateTime = readTimeStamp(buffer,
ORIGINATE_TIME_OFFSET);
long receiveTime = readTimeStamp(buffer, RECEIVE_TIME_OFFSET);
long transmitTime = readTimeStamp(buffer, TRANSMIT_TIME_OFFSET);
long roundTripTime = responseTicks - requestTicks
- (transmitTime - receiveTime);
// receiveTime = originateTime + transit + skew
// responseTime = transmitTime + transit - skew
// clockOffset = ((receiveTime - originateTime) + (transmitTime
// - responseTime))/2
// = ((originateTime + transit + skew - originateTime) +
// (transmitTime - (transmitTime + transit - skew)))/2
// = ((transit + skew) + (transmitTime - transmitTime - transit
// + skew))/2
// = (transit + skew - transit + skew)/2
// = (2 * skew)/2 = skew
long clockOffset = ((receiveTime - requestTime) + (transmitTime - System.currentTimeMillis())) / 2;
// if (false) Log.d(TAG, "round trip: " + roundTripTime +
// " ms");
// if (false) Log.d(TAG, "clock offset: " + clockOffset +
// " ms");
// save our results - use the times on this side of the network
// latency
// (response rather than request time)
mNtpTime = System.currentTimeMillis() + clockOffset;
// mNtpTime = transmitTime;
mNtpTimeReference = responseTicks;
mRoundTripTime = roundTripTime;
} catch (Exception e) {
if (false)
Log.e(TAG, "request time failed:" + e);
e.printStackTrace();
return false;
} finally {
if (socket != null) {
socket.close();
}
}
return true;
}
/**
* Returns the time computed from the NTP transaction.
*
* @return time value computed from NTP server response.
*/
public long getNtpTime() {
return mNtpTime;
}
/**
* Returns the reference clock value (value of
* SystemClock.elapsedRealtime()) corresponding to the NTP time.
*
* @return reference clock corresponding to the NTP time.
*/
public long getNtpTimeReference() {
return mNtpTimeReference;
}
/**
* Returns the round trip time of the NTP transaction
*
* @return round trip time in milliseconds.
*/
public long getRoundTripTime() {
return mRoundTripTime;
}
/**
* Reads an unsigned 32 bit big endian number from the given offset in
* the buffer.
*/
private long read32(byte[] buffer, int offset) {
byte b0 = buffer[offset];
byte b1 = buffer[offset + 1];
byte b2 = buffer[offset + 2];
byte b3 = buffer[offset + 3];
// convert signed bytes to unsigned values
int i0 = ((b0 & 0x80) == 0x80 ? (b0 & 0x7F) + 0x80 : b0);
int i1 = ((b1 & 0x80) == 0x80 ? (b1 & 0x7F) + 0x80 : b1);
int i2 = ((b2 & 0x80) == 0x80 ? (b2 & 0x7F) + 0x80 : b2);
int i3 = ((b3 & 0x80) == 0x80 ? (b3 & 0x7F) + 0x80 : b3);
return ((long) i0 << 24) + ((long) i1 << 16) + ((long) i2 << 8)
+ (long) i3;
}
/**
* Reads the NTP time stamp at the given offset in the buffer and
* returns it as a system time (milliseconds since January 1, 1970).
*/
private long readTimeStamp(byte[] buffer, int offset) {
long seconds = read32(buffer, offset);
long fraction = read32(buffer, offset + 4);
return ((seconds - OFFSET_1900_TO_1970) * 1000)
+ ((fraction * 1000L) / 0x100000000L);
}
/**
* Writes system time (milliseconds since January 1, 1970) as an NTP
* time stamp at the given offset in the buffer.
*/
private void writeTimeStamp(byte[] buffer, int offset, long time) {
long seconds = time / 1000L;
long milliseconds = time - seconds * 1000L;
seconds += OFFSET_1900_TO_1970;
// write seconds in big endian format
buffer[offset++] = (byte) (seconds >> 24);
buffer[offset++] = (byte) (seconds >> 16);
buffer[offset++] = (byte) (seconds >> 8);
buffer[offset++] = (byte) (seconds >> 0);
long fraction = milliseconds * 0x100000000L / 1000L;
// write fraction in big endian format
buffer[offset++] = (byte) (fraction >> 24);
buffer[offset++] = (byte) (fraction >> 16);
buffer[offset++] = (byte) (fraction >> 8);
// low order bits should be random data
buffer[offset++] = (byte) (Math.random() * 255.0);
}
}
}

View File

@@ -1,65 +1,38 @@
package com.info.sn.utils;
import android.annotation.SuppressLint;
import android.content.Context;
import android.os.Handler;
import android.os.Looper;
import android.widget.Toast;
import android.graphics.Color;
import android.util.Log;
import android.view.Gravity;
import com.info.sn.BuildConfig;
/**
* Created by haoge on 2017/3/2.
*/
import com.blankj.utilcode.util.ColorUtils;
import com.blankj.utilcode.util.ToastUtils;
import com.info.sn.R;
import com.info.sn.manager.DeviceManager;
public class ToastUtil {
static Handler mainHandler = new Handler(Looper.getMainLooper());
static Toast toast;
@SuppressLint("ShowToast")
public static void init(Context context) {
toast = Toast.makeText(context, "", Toast.LENGTH_SHORT);
debugToast = Toast.makeText(context, "", Toast.LENGTH_SHORT);
}
private static String TAG = ToastUtil.class.getSimpleName();
public static void show(final String msg) {
mainHandler.post(new Runnable() {
@Override
public void run() {
if (toast != null) {
toast.setText(msg);
toast.show();
}
}
});
ToastUtils.make()
.setBgColor(ColorUtils.getColor(R.color.toast_color))
.setTextColor(Color.WHITE)
.setGravity(Gravity.CENTER, 0, 0)
.setNotUseSystemToast()
.show(msg);
}
// public static void showInCenter(String msg) {
// mainHandler.post(() -> {
// if (toast != null) {
// toast.setGravity(Gravity.CENTER, 0, 0);
// toast.setText(msg);
// toast.show();
// }
// });
// }
static Handler debugHandler = new Handler(Looper.getMainLooper());
static Toast debugToast;
public static void debugShow(final String msg) {
debugHandler.post(new Runnable() {
@Override
public void run() {
if (BuildConfig.DEBUG) {
if (debugToast != null) {
debugToast.setText(msg);
debugToast.show();
}
}
}
});
if (DeviceManager.isDebugMode()) {
ToastUtils.make()
.setBgColor(ColorUtils.getColor(R.color.toast_color))
.setTextColor(Color.RED)
.setGravity(Gravity.CENTER, 0, 0)
.setNotUseSystemToast()
.setDurationIsLong(true)
.show(msg);
} else {
Log.e(TAG, "debugShow: " + msg);
}
}
}

View File

@@ -2,17 +2,16 @@ package com.info.sn.utils;
import android.content.Context;
import android.os.Build;
import android.provider.Settings;
import android.text.TextUtils;
import android.util.Log;
import android.webkit.WebSettings;
import java.io.IOException;
import java.net.URI;
import java.net.URL;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.HashSet;
import java.util.function.Predicate;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
@@ -31,106 +30,116 @@ import okhttp3.Response;
public class URLUtils {
private static String TAG = URLUtils.class.getSimpleName();
private Context mContext;
private List<String> baseURLList = new ArrayList<>();
private HashSet<String> baseURLList = new HashSet<>();
public URLUtils(Context context) {
this.mContext = context;
}
public void setBrowserList() {
String whiteList = Settings.System.getString(mContext.getContentResolver(), "DeselectBrowserArray");
String homePage = Settings.System.getString(mContext.getContentResolver(), "homepagURL");
String whiteList = JGYUtils.getString(mContext.getContentResolver(), "DeselectBrowserArray");
String homePage = JGYUtils.getString(mContext.getContentResolver(), "homepagURL");
if (TextUtils.isEmpty(whiteList)) {
Log.e(TAG, "getBrowserWhiteList: " + "whiteList is empty");
} else {
List<String> URLList = new ArrayList<>(Arrays.asList(whiteList.split(",")));
if (!TextUtils.isEmpty(homePage)) {
if (URLList != null && !URLList.contains(homePage)) {
URLList.add(homePage);
}
HashSet<String> URLList = new HashSet<>();
if (!TextUtils.isEmpty(whiteList)){
URLList.addAll(Arrays.asList(whiteList.split(",")));
}
URLList.add("https://xdf.gankao.com");
URLList.add("https://www.gankao.com");
if (!TextUtils.isEmpty(homePage)) {
if (!URLList.contains(homePage)) {
URLList.add(homePage);
}
Observable.create(new ObservableOnSubscribe<String>() {
@Override
public void subscribe(ObservableEmitter<String> emitter) throws Exception {
baseURLList.clear();
baseURLList.addAll(URLList);
for (String url : URLList) {
if (url.startsWith("http://")) {
String noHttp = url.substring(7);
}
URLList.removeIf(new Predicate<String>() {
@Override
public boolean test(String s) {
return TextUtils.isEmpty(s.trim());
}
});
Log.e(TAG, "setBrowserList: " + URLList);
Observable.create(new ObservableOnSubscribe<String>() {
@Override
public void subscribe(ObservableEmitter<String> emitter) throws Exception {
baseURLList.clear();
baseURLList.addAll(URLList);
for (String url : URLList) {
if (TextUtils.isEmpty(url.trim())){
continue;
}
if (url.startsWith("http://")) {
String noHttp = url.substring(7);
if (!baseURLList.contains(noHttp)) {
baseURLList.add(noHttp);
}
emitter.onNext(getOkHttpURL(url));
} else if (url.startsWith("https://")) {
String noHttps = url.substring(8);
if (!baseURLList.contains(noHttps)) {
baseURLList.add(noHttps);
}
emitter.onNext(getOkHttpURL(url));
} else {
baseURLList.add("http://" + url);
emitter.onNext(getOkHttpURL("http://" + url));
baseURLList.add("https://" + url);
emitter.onNext(getOkHttpURL("https://" + url));
}
Log.e(TAG, "subscribe: " + url);
}
emitter.onComplete();
}
}).subscribeOn(Schedulers.io())
.observeOn(AndroidSchedulers.mainThread())
.subscribe(new Observer<String>() {
@Override
public void onSubscribe(Disposable d) {
}
@Override
public void onNext(String s) {
Log.e(TAG, "onNext: " + s);
if (!baseURLList.contains(s)) {
baseURLList.add(s);
}
if (s.startsWith("http://")) {
String noHttp = s.substring(7);
Log.e(TAG, "onNext: noHttp: " + noHttp);
if (!baseURLList.contains(noHttp)) {
baseURLList.add(noHttp);
}
emitter.onNext(getOkHttpURL(url));
} else if (url.startsWith("https://")) {
String noHttps = url.substring(8);
}
if (s.startsWith("https://")) {
String noHttps = s.substring(8);
Log.e(TAG, "onNext: noHttps: " + noHttps);
if (!baseURLList.contains(noHttps)) {
baseURLList.add(noHttps);
}
emitter.onNext(getOkHttpURL(url));
} else {
baseURLList.add("http://" + url);
emitter.onNext(getOkHttpURL("http://" + url));
baseURLList.add("https://" + url);
emitter.onNext(getOkHttpURL("https://" + url));
}
Log.e(TAG, "subscribe: " + url);
}
emitter.onComplete();
}
}).subscribeOn(Schedulers.io())
.observeOn(AndroidSchedulers.mainThread())
.subscribe(new Observer<String>() {
@Override
public void onSubscribe(Disposable d) {
}
@Override
public void onError(Throwable e) {
Log.e(TAG, "onError: " + e.getMessage());
}
@Override
public void onNext(String s) {
Log.e(TAG, "onNext: " + s);
if (!baseURLList.contains(s)) {
baseURLList.add(s);
}
if (s.startsWith("http://")) {
String noHttp = s.substring(7);
Log.e(TAG, "onNext: noHttp: " + noHttp);
if (!baseURLList.contains(noHttp)) {
baseURLList.add(noHttp);
}
}
if (s.startsWith("https://")) {
String noHttps = s.substring(8);
Log.e(TAG, "onNext: noHttps: " + noHttps);
if (!baseURLList.contains(noHttps)) {
baseURLList.add(noHttps);
}
@Override
public void onComplete() {
Log.e(TAG, "onComplete: ");
StringBuilder stringBuilder = new StringBuilder();
for (String s : baseURLList) {
if (stringBuilder.length() > 0) {
stringBuilder.append(",");
}
stringBuilder.append(s);
}
@Override
public void onError(Throwable e) {
Log.e(TAG, "onError: " + e.getMessage());
}
@Override
public void onComplete() {
Log.e(TAG, "onComplete: ");
StringBuilder stringBuilder = new StringBuilder();
for (String s : baseURLList) {
if (stringBuilder.length() > 0) {
stringBuilder.append(",");
}
stringBuilder.append(s);
}
String DeselectBrowserArray = stringBuilder.toString();
boolean write = Settings.System.putString(mContext.getContentResolver(), "DeselectBrowserArray", DeselectBrowserArray);
Log.e(TAG, "onComplete: " + "white list: " + DeselectBrowserArray);
Log.e(TAG, "onComplete: " + "write :" + write);
}
});
}
String DeselectBrowserArray = stringBuilder.toString();
boolean write = JGYUtils.putString(mContext.getContentResolver(), "DeselectBrowserArray", DeselectBrowserArray);
Log.e(TAG, "onComplete: " + "white list: " + DeselectBrowserArray);
Log.e(TAG, "onComplete: " + "write :" + write);
}
});
}
private String getOkHttpURL(String URL) {
@@ -236,7 +245,7 @@ public class URLUtils {
sb.append(c);
}
}
Log.e(TAG, "getUserAgent: " + sb.toString());
// Log.e(TAG, "getUserAgent: " + sb.toString());
return sb.toString();
}
}

View File

@@ -31,6 +31,7 @@ import android.net.wifi.WifiManager;
import android.os.BatteryManager;
import android.os.Build;
import android.os.StatFs;
import android.os.SystemClock;
import android.provider.Settings;
import android.telephony.TelephonyManager;
import android.text.TextUtils;
@@ -44,8 +45,9 @@ import android.view.inputmethod.InputMethodManager;
import android.widget.EditText;
import android.widget.Toast;
import androidx.annotation.VisibleForTesting;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.google.zxing.BarcodeFormat;
import com.google.zxing.EncodeHintType;
@@ -53,14 +55,19 @@ 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.info.sn.BuildConfig;
import com.info.sn.R;
import com.info.sn.bean.SystemSettings;
import com.info.sn.Statistics.AppInformation;
import com.info.sn.Statistics.StatisticsInfo;
import com.info.sn.bean.zuoye.AppUsed;
import com.info.sn.bean.zuoye.SystemSettings;
import com.info.sn.manager.DeviceManager;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileFilter;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.LineNumberReader;
import java.io.Reader;
@@ -76,23 +83,16 @@ import java.util.Calendar;
import java.util.Collections;
import java.util.Date;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.function.Predicate;
import java.util.regex.Pattern;
import static android.content.Context.WIFI_SERVICE;
public class Utils {
private static final String TAG = "Utils";
protected static Toast toast = null;
private static String oldMsg;
private static long oneTime = 0;
private static long twoTime = 0;
// 积分记录 达人标准次数记录
private static final String TAG = Utils.class.getSimpleName();
// MD5 设备地址标识
public static String getMAC(Context context) {
@@ -198,7 +198,6 @@ public class Utils {
return builder.toString();
}
// MD5 设备地址标识
public static String getMD5(Context context) {
String WLANMAC = getMAC(context);
@@ -239,7 +238,6 @@ public class Utils {
return simSerialNumber;
}
private static String getPesudoUniqueID() {
String m_szDevIDShort = "35" + //we make this look like a valid IMEI
Build.BOARD.length() % 10 +
@@ -258,7 +256,6 @@ public class Utils {
return m_szDevIDShort;
}
// 防止连续点击
private static long lastClickTime;
@@ -292,7 +289,6 @@ public class Utils {
return sBuffer.toString();
}
// 根据日期取得星期几
public static String getWeek(Date date) {
String[] weeks = {"星期日", "星期一", "星期二", "星期三", "星期四", "星期五", "星期六"};
@@ -305,7 +301,6 @@ public class Utils {
return weeks[week_index];
}
// 非空判断
public static boolean isEmpty(String s) {
if (null == s)
@@ -354,12 +349,9 @@ public class Utils {
}
// 打开app
public static void startApp(Context context, String packageName,
String activityName) {
public static void startApp(Context context, String packageName, String activityName) {
if (TextUtils.isEmpty(packageName))
return;
try {
Intent intent = null;
if (TextUtils.isEmpty(activityName)) {
@@ -381,10 +373,8 @@ public class Utils {
}
}
public static Intent getLaunchIntentForNoCategory(Context context,
String packageName) {
public static Intent getLaunchIntentForNoCategory(Context context, String packageName) {
Intent intent = null;
PackageManager packageManager = context.getPackageManager();
PackageInfo packageinfo = null;
try {
@@ -397,9 +387,7 @@ public class Utils {
}
Intent resolveIntent = new Intent(Intent.ACTION_MAIN, null);
resolveIntent.setPackage(packageinfo.packageName);
List<ResolveInfo> resolveinfoList = packageManager
.queryIntentActivities(resolveIntent, 0);
List<ResolveInfo> resolveinfoList = packageManager.queryIntentActivities(resolveIntent, 0);
ResolveInfo resolveinfo = resolveinfoList.iterator().next();
if (resolveinfo != null) {
String className = resolveinfo.activityInfo.name;
@@ -419,9 +407,8 @@ public class Utils {
if (initSetting) {
mPrefs.edit().putBoolean("init_setting", false).commit();
}
Settings.System.putInt(context.getContentResolver(), Settings.System.SCREEN_BRIGHTNESS_MODE, 0);
JGYUtils.putInt(context.getContentResolver(), Settings.System.SCREEN_BRIGHTNESS_MODE, 0);
mPrefs.edit().putBoolean("first_init", false).commit();
} catch (Exception err) {
err.printStackTrace();
}
@@ -476,6 +463,12 @@ public class Utils {
return new String(c);
}
protected static Toast toast = null;
private static String oldMsg;
private static long oneTime = 0;
private static long twoTime = 0;
public static void showToast(Context context, String s) {
if (toast == null) {
toast = Toast.makeText(context, s, Toast.LENGTH_SHORT);
@@ -555,7 +548,6 @@ public class Utils {
return timeClick.toString();
}
public static String getVersionName(Context context) {
// 获取packagemanager的实例
PackageManager packageManager = context.getPackageManager();
@@ -573,7 +565,6 @@ public class Utils {
return "";
}
/**
* 根据手机的分辨率从 dp 的单位 转成为 px(像素)
*/
@@ -590,7 +581,6 @@ public class Utils {
return (int) (pxValue / scale + 0.5f);
}
public static float dp2px(Resources resources, float dp) {
final float scale = resources.getDisplayMetrics().density;
return dp * scale + 0.5f;
@@ -609,7 +599,6 @@ public class Utils {
return t1;
}
private static void getAdmin(Context context, ComponentName componentName) {
Intent intent = new Intent(DevicePolicyManager.ACTION_ADD_DEVICE_ADMIN);
intent.putExtra(DevicePolicyManager.EXTRA_DEVICE_ADMIN, componentName);
@@ -642,6 +631,75 @@ public class Utils {
return serial;
}
/**
* @param context 获取真实的MAC地址
* @return
*/
public static String getAndroid10MAC(Context context) {
if (Build.VERSION.SDK_INT > Build.VERSION_CODES.N_MR1) {
return getMacAddress(context);
} else {
return getAndroid7MAC();
}
}
@SuppressLint("HardwareIds")
@VisibleForTesting
public static String getMacAddress(Context mContext) {
WifiManager mWifiManager = (WifiManager) mContext.getSystemService(WIFI_SERVICE);
final String[] macAddresses = mWifiManager.getFactoryMacAddresses();
String macAddress = null;
if (macAddresses != null && macAddresses.length > 0) {
macAddress = macAddresses[0];
}
if (TextUtils.isEmpty(macAddress)) {
String mac = getMacFromFile();
// Add for CTCC Feature:WIFI MAC should be gotten while wifi disabled.
// Get Wifi MAC from file since we can not get it with WifiManager.
if (!TextUtils.isEmpty(mac)) {
macAddress = mac;
} else {
macAddress = "未能获取到MAC地址";
}
}
return macAddress.toUpperCase();
}
/**
* Add for CTCC Feature:WIFI MAC should be gotten while wifi disabled.
* get Wifi MAC from /mnt/vendor/wifimac.txt
*
* @{
*/
private static String MACID_FILE_PATH = "/mnt/vendor/wifimac.txt";
private static String getMacFromFile() {
File file = new File(MACID_FILE_PATH);
BufferedReader reader = null;
String macAddress = null;
try {
reader = new BufferedReader(new FileReader(file));
String line;
while ((line = reader.readLine()) != null) {
macAddress = line;
break;
}
} catch (FileNotFoundException e) {
Log.w(TAG, "Mac file not exist", e);
} catch (Exception e) {
Log.w(TAG, "get mac from file caught exception", e);
} finally {
try {
if (reader != null)
reader.close();
} catch (IOException e) {
Log.w(TAG, "reader close exception");
}
}
return macAddress;
}
public static final long A_GB = 1073741824;
public static final long A_MB = 1048576;
public static final int A_KB = 1024;
@@ -665,7 +723,6 @@ public class Utils {
}
}
public static String transferLongToDate(Long millSec) {
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
@@ -676,10 +733,6 @@ public class Utils {
}
// public static String getSn() {
// return Build.SERIAL;
// }
public static Bitmap createQRImage(String content, int widthPix, int heightPix) {
try {
// if (content == null || "".equals(content)) {
@@ -730,7 +783,6 @@ public class Utils {
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
@@ -746,7 +798,6 @@ public class Utils {
Log.e("isSystemApp", e.getMessage(), e);
}
// 是系统中已安装的应用
if (pi != null) {
boolean isSysApp = (pi.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) == 1;
@@ -759,7 +810,6 @@ public class Utils {
public static Bitmap getRoundedBitmap(Bitmap mBitmap, Context context) {
Bitmap bgBitmap = Bitmap.createBitmap(mBitmap.getWidth(), mBitmap.getHeight(), Bitmap.Config.ARGB_8888);
Bitmap mask = BitmapFactory.decodeResource(context.getResources(), R.drawable.mask);
int width = mask.getWidth();
int height = mask.getHeight();
@@ -789,7 +839,6 @@ public class Utils {
canvas2.drawBitmap(result, 0, 0, paint2);
return result2;
// Canvas mCanvas = new Canvas();
// mCanvas.setBitmap(bgBitmap);
// Paint mPaint = new Paint();
@@ -806,338 +855,77 @@ public class Utils {
// return bgBitmap;
}
private static int changeNum(int status) {
return status == 0 ? 1 : 0;
}
public static void setSystemSetting(Context context, String data) {
if (TextUtils.isEmpty(data)) {
return;
}
SystemSettings settings = JSON.parseObject(data, SystemSettings.class);
if (null != settings) {
setPhoneList(context, settings);
setUSBstate(context, settings);
setBluetooth(context, settings);
setHotspot(context, settings);
setBar(context, settings);
setCamera(context, settings);
setTF(context, settings);
setIcon(context, settings);
}
}
private static void setPhoneList(Context mContext, SystemSettings settings) {
//设置电话功能,电话白名单
int setting_call = changeNum(settings.getSetting_call());
boolean qch_call_forbid = Settings.System.putInt(mContext.getContentResolver(), "qch_call_forbid", setting_call);
Log.e("SystemSetting", "qch_call_forbid:" + qch_call_forbid);
int setting_phone = changeNum(settings.getSetting_phone());
boolean qch_white_list_on = Settings.System.putInt(mContext.getContentResolver(), "qch_white_list_on", setting_phone);
Log.e("SystemSetting", "qch_white_list_on:" + qch_white_list_on);
String setting_phones = settings.getSetting_phones();
boolean qch_white_list_Array = Settings.System.putString(mContext.getContentResolver(), "qch_white_list_Array", setting_phones);
Log.e("SystemSetting", "qch_white_list_Array:" + qch_white_list_Array + "=" + setting_phones);
int setting_memory = changeNum(settings.getSetting_memory());
boolean qch_sdcard_forbid_on = Settings.System.putInt(mContext.getContentResolver(), "qch_sdcard_forbid_on", setting_memory);
Log.e("SystemSetting", "qch_sdcard_forbid_on:" + qch_sdcard_forbid_on);
}
private static void setUSBstate(Context mContext, SystemSettings settings) {
//USB数据功能管控
//仅充电usb_charge
//MTP模式usb_mtp
//Midi模式usb_midi
String setting_usb = settings.getSetting_usb();
Log.e("SystemSetting", "setting_usb:" + setting_usb);
if (!BuildConfig.DEBUG) {
try {
boolean qch_usb_choose = Settings.System.putString(mContext.getContentResolver(), "qch_usb_choose", setting_usb);
Log.e("SystemSetting", "qch_usb_choose:" + qch_usb_choose);
String usbStatus = "";
switch (setting_usb) {
case "usb_charge":
usbStatus = "qch_action_usb_usb_charge";
break;
case "usb_mtp":
usbStatus = "qch_action_usb_usb_mtp";
break;
case "usb_midi":
usbStatus = "qch_action_usb_usb_midi";
break;
}
Intent usbIntent = new Intent(usbStatus).setPackage("com.android.settings");
mContext.sendBroadcast(usbIntent);
} catch (Exception e) {
Log.e(TAG, "setUSBstate: " + e.getMessage());
}
}
}
private static void setBluetooth(Context mContext, SystemSettings settings) {
try {
//蓝牙开关
int setting_bht = changeNum(settings.getSetting_bht());
//总开关
int setting_bhtvideo = changeNum(settings.getSetting_bhtvideo());
//蓝牙音频开关
int setting_bluetooth = changeNum(settings.getSetting_bluetooth());
//蓝牙传输开关
boolean qch_bht_forbid_on = Settings.System.putInt(mContext.getContentResolver(), "qch_bht_forbid_on", setting_bht);
//写入系统数据库
Log.e("SystemSetting", "qch_bht_forbid_on:" + qch_bht_forbid_on);
BluetoothAdapter mBluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
if (qch_bht_forbid_on) {
//成功
if (null == mBluetoothAdapter) {
mBluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
//获取默认蓝牙适配器
}
if (setting_bht == 0) {
//蓝牙总开关开启
String setting_context = settings.getSetting_context();
if (setting_bhtvideo == 0) {
if (null != setting_context && !setting_context.equals("") && !setting_context.equals(" ") && !setting_context.equals("null")) {
Log.e("SystemSetting", "setting_context:" + setting_context);
Settings.System.putString(mContext.getContentResolver(), "qch_bhtvideo_forbid_on", setting_context);
} else {
Settings.System.putString(mContext.getContentResolver(), "qch_bhtvideo_forbid_on", "Empty");
}
} else if (setting_bhtvideo == 1) {
Settings.System.putString(mContext.getContentResolver(), "qch_bhtvideo_forbid_on", "Empty");
}
Settings.System.putInt(mContext.getContentResolver(), "qch_bt_forbid_on", setting_bluetooth);
} else {
mBluetoothAdapter.disable();
//设置关闭时关闭蓝牙
}
}
} catch (Exception e) {
Log.e(TAG, "setBluetooth: " + e.getMessage());
}
}
private static void setHotspot(Context mContext, SystemSettings settings) {
try {
int setting_hotspot = changeNum(settings.getSetting_hotspot());//热点
if (setting_hotspot == 1) {
Intent intent = new Intent();
intent.setAction("qch_hotspot_close");
intent.setPackage("com.android.settings");
mContext.sendStickyBroadcast(intent);
}
boolean qch_hotspot_forbid_on = Settings.System.putInt(mContext.getContentResolver(), "qch_hotspot_forbid_on", setting_hotspot);//写入系统数据库
Log.e("SystemSetting", "qch_hotspot_forbid_on:" + setting_hotspot);
Log.e("SystemSetting", "qch_hotspot_forbid_on:" + qch_hotspot_forbid_on);
} catch (Exception e) {
Log.e(TAG, "setHotspot: " + e.getMessage());
}
}
private static void setBar(Context mContext, SystemSettings settings) {
//系统导航条显示开关
int setting_navigation = changeNum(settings.getSetting_navigation());
boolean qch_hide_navigationBar = Settings.System.putInt(mContext.getContentResolver(), "qch_hide_NavigationBar", setting_navigation);
Log.e("SystemSetting", "qch_hide_navigationBar:" + qch_hide_navigationBar);
String navigationStatus = "";
switch (setting_navigation) {
case 0:
navigationStatus = "qch_show_NavigationBar";
break;
case 1:
navigationStatus = "qch_hide_NavigationBar";
break;
}
Intent navIntent = new Intent(navigationStatus).setPackage("com.android.systemui");
mContext.sendBroadcast(navIntent);
//状态栏显示开关
int setting_statusbar = changeNum(settings.getSetting_statusbar());
int oldNum = Settings.System.getInt(mContext.getContentResolver(), "qch_hide_statusBar", 0);
if (oldNum != setting_statusbar) {
boolean qch_hide_statusBar = Settings.System.putInt(mContext.getContentResolver(), "qch_hide_statusBar", setting_statusbar);
Log.e("SystemSetting", "qch_hide_statusBar:" + qch_hide_statusBar);
String statusbarStatus = "";
switch (setting_statusbar) {
case 0:
statusbarStatus = "qch_show_statusBar";
break;
case 1:
statusbarStatus = "qch_hide_statusBar";
break;
}
Intent statusIntent = new Intent(statusbarStatus).setPackage("com.android.systemui");
mContext.sendBroadcast(statusIntent);
}
}
private static void setCamera(Context mContext, SystemSettings settings) {
try {
//摄像头开关
int setting_camera = changeNum(settings.getSetting_camera());
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) {
case 0:
cameraStatus = "qch_camera_open";
break;
case 1:
cameraStatus = "qch_camera_forbid";
break;
}
Intent cameraIntent = new Intent(cameraStatus).setPackage("com.android.settings");
mContext.sendBroadcast(cameraIntent);
} catch (Exception e) {
Log.e(TAG, "setCamera: " + e.getMessage());
}
}
private static void setTF(Context mContext, SystemSettings settings) {
try {
//tfmedia开关
int setting_tfmedia = changeNum(settings.getSetting_tfmedia());
boolean qch_tfmedia_forbid = Settings.System.putInt(mContext.getContentResolver(),
"qch_tfmedia_forbid", setting_tfmedia);
Log.e("SystemSetting", "setting_tfmedia:" + qch_tfmedia_forbid);
String tfmediaStatus = "";
switch (setting_tfmedia) {
case 0:
tfmediaStatus = "qch_tfmedia_open";
break;
case 1:
tfmediaStatus = "qch_tfmedia_forbid";
break;
}
Intent tfmediaIntent = new Intent(tfmediaStatus).setPackage("com.android.settings");
mContext.sendBroadcast(tfmediaIntent);
if (setting_tfmedia == 1) {
JSONArray jSONArray = null;
jSONArray = JSON.parseArray(settings.getSetting_tfmedia_format());
int i = 0;
StringBuffer stringBuffer = new StringBuffer();
while (!jSONArray.isEmpty()) {
stringBuffer.append(jSONArray.getString(i));
stringBuffer.append(",");
i++;
}
stringBuffer.deleteCharAt(stringBuffer.length() - 1);
Settings.System.putString(mContext.getContentResolver(), "qch_tfmedia_filetypes", stringBuffer.toString());//影音管控
Log.e("SystemSetting", "qch_tfmedia_filetypes---------" + stringBuffer.toString());
} else {
Settings.System.putInt(mContext.getContentResolver(), "qch_tfmedia_forbid", 0);
}
} catch (Exception e) {
Log.e(TAG, "setTF: " + e.getMessage());
}
}
private static void setIcon(Context mContext, SystemSettings settings) {
try {
//added:2019.12.6
//设置5个app的开关
//时钟
int deskclock = changeNum(settings.getSetting_clock());
Settings.System.putInt(mContext.getContentResolver(), "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(mContext.getContentResolver(), "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(mContext.getContentResolver(), "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(mContext.getContentResolver(), "qch_app_gallery", gallery);
ApkUtils.hideSystemSettingAPP(mContext, "com.android.gallery3d");
Log.e("SystemSetting", "qch_app_gallery:" + gallery);
//壁纸
int wallpaper = changeNum(settings.getSetting_wallpaper());
Settings.System.putInt(mContext.getContentResolver(), "qch_app_wallpaper", wallpaper);
Log.e("SystemSetting", "qch_app_wallpaper:" + wallpaper);
//文件管理器
int filemanager = changeNum(settings.getSetting_file());
Settings.System.putInt(mContext.getContentResolver(), "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);
} catch (Exception e) {
Log.e(TAG, "setIcon: " + e.getMessage());
}
}
/**
* 更新应用白名单禁止升级
*
* @param context
* @param notList 禁止列表
* @param allowList 允许列表
* @return
*/
static synchronized public boolean writeDisableUpdateList(Context context, String[] notList, String[] allowList) {
String now = Settings.System.getString(context.getContentResolver(), "qch_app_forbid");
String[] nowList;
List<String> allList;
if (now == null || now.equalsIgnoreCase("")) {
allList = new ArrayList<>();
} else {
nowList = now.split(",");
allList = new ArrayList<>(Arrays.asList(nowList));//已经写入的列表
@SuppressLint("NewApi")
static synchronized public boolean writeDisableUpdateList(Context context) {
//允许安装的app
String now = JGYUtils.getString(context.getContentResolver(), "qch_app_forbid");
//禁止升级的app
String upgrade_disallow = Settings.System.getString(context.getContentResolver(), "upgrade_disallow");
//所有app
String only_jgy_shortcut_list = Settings.System.getString(context.getContentResolver(), "only_jgy_shortcut_list");
Log.e("writeDisableUpdateList", now);
List<String> nowList = new ArrayList<>();
List<String> disallowList = new ArrayList<>();
List<String> allList = new ArrayList<>();
if (!TextUtils.isEmpty(now)) {
nowList = new ArrayList<>(new HashSet<>(Arrays.asList(now.trim().replaceAll(" ", "").split(","))));
}
boolean writeSucceed = false;
if (notList != null && notList.length > 0) {
for (String s : notList) {
if (ApkUtils.isAvailable(context, s)) {
allList.remove(s);
//去掉已经安装的
} else {
if (allList.indexOf(s) == -1) {
allList.add(s);
}
//没有安装就加入进去
//没有加入会导致安装后卸载不能再安装的情况
if (!TextUtils.isEmpty(upgrade_disallow)) {
disallowList = new ArrayList<>(new HashSet<>(Arrays.asList(upgrade_disallow.trim().replaceAll(" ", "").split(","))));
}
if (!TextUtils.isEmpty(only_jgy_shortcut_list)) {
allList = new ArrayList<>(new HashSet<>(Arrays.asList(only_jgy_shortcut_list.trim().replaceAll(" ", "").split(","))));
}
Log.e("writeDisableUpdateList", "nowList: " + nowList);
Log.e("writeDisableUpdateList", "upgrade_disallow: " + disallowList);
Log.e("writeDisableUpdateList", "only_jgy_shortcut_list: " + allList);
if (allList.size() != 0) {
List<String> finalAllList = allList;
nowList.removeIf(new Predicate<String>() {
@Override
public boolean test(String s) {
return !finalAllList.contains(s);
}
}
});
}
for (String s : allowList) {
if (allList.indexOf(s) == -1) {
boolean writeSucceed = false;
for (String s : disallowList) {
if (ApkUtils.isAvailable(context, s)) {
if (nowList.remove(s)) {
Log.e("writeDisableUpdateList", "remove :" + s);
} else {
Log.e("writeDisableUpdateList", "remove failed:" + s);
}
//去掉已经安装的
} else {
if (!nowList.contains(s)) {
nowList.add(s);
}
//没有安装就加入进去
//没有加入会导致安装后卸载不能再安装的情况
}
Log.e("writeDisableUpdateList", "nowList:" + nowList);
}
for (String s : nowList) {
if (!allList.contains(s)) {
allList.add(s);
//没找到元素添加到白名单
}
}
if (allList.size() > 0) {
String list = "";
for (String str : allList) {
list += str + ",";
}
list = list.substring(0, list.length() - 1);
Log.e("fht", list);
writeSucceed = Settings.System.putString(context.getContentResolver(), "qch_app_forbid", list);
Log.e("fht", "qch_app_forbid:" + list);
String list = String.join(",", allList);
writeSucceed = JGYUtils.putString(context.getContentResolver(), "qch_app_forbid", list);
Log.e("writeDisableUpdateList", "qch_app_forbid:" + list);
} else {
writeSucceed = Settings.System.putString(context.getContentResolver(), "qch_app_forbid", "Invalid");
writeSucceed = JGYUtils.putString(context.getContentResolver(), "qch_app_forbid", "Invalid");
}
return writeSucceed;
/*功能和应用安装白名单一样首先会写入所有的app名单。
*如果已经安装就从白名单删除,没有安装的不用删除
@@ -1165,15 +953,14 @@ public class Utils {
// IMEI = TelephonyMgr.getDeviceId();
// } else {//9.0到10.0获取
IMEI = Settings.System.getString(context.getContentResolver(), Settings.Secure.ANDROID_ID);
IMEI = JGYUtils.getString(context.getContentResolver(), Settings.Secure.ANDROID_ID);
}
Log.e("IMEI:", "IMEI: " + IMEI);
// Log.e("IMEI:", "IMEI: " + IMEI);
if (null == IMEI) {
return "-";
} else {
return IMEI.toUpperCase();
}
}
public static String getAndroiodScreenProperty(Context context) {
@@ -1260,6 +1047,19 @@ public class Utils {
}
}
/**
* @param context
* @return 已经使用
*/
public static long getUsedMemory(Context context) {
ActivityManager activityManager = (ActivityManager) context.getSystemService(Context.ACTIVITY_SERVICE);
ActivityManager.MemoryInfo memoryInfo = new ActivityManager.MemoryInfo();
activityManager.getMemoryInfo(memoryInfo);
long freeMem = memoryInfo.totalMem - memoryInfo.availMem;
// Log.e("getHardware", "getFreeMemory: " + freeMem);
return freeMem;
}
/**
* 描述:获取可用内存.
*
@@ -1309,12 +1109,31 @@ public class Utils {
return memory * 1024;
}
public static float getUse_space(Context context) {
StatFs sf = new StatFs(context.getCacheDir().getAbsolutePath());
long availableSize = sf.getAvailableBytes();
Log.e(TAG, "getUse_space: availableSize = " + availableSize);
long blockSize = sf.getBlockSize();
Log.e(TAG, "getUse_space: blockSize = " + blockSize);
long totalBlocks = sf.getBlockCount();
Log.e(TAG, "getUse_space: totalBlocks = " + totalBlocks);
return (float) 1.0 * availableSize / (blockSize * totalBlocks);
}
public static String getRemnantSize(Context context) {
StatFs sf = new StatFs(context.getCacheDir().getAbsolutePath());
long availableSize = sf.getAvailableBytes();
return Formatter.formatFileSize(context, availableSize);
}
public static String getUsedSize(Context context) {
StatFs sf = new StatFs(context.getCacheDir().getAbsolutePath());
long availableSize = sf.getAvailableBytes();
long blockSize = sf.getBlockSize();
long totalBlocks = sf.getBlockCount();
return Formatter.formatFileSize(context, blockSize * totalBlocks - availableSize);
}
public static String getDataTotalSize(Context context) {
StatFs sf = new StatFs(context.getCacheDir().getAbsolutePath());
long blockSize = sf.getBlockSize();
@@ -1348,24 +1167,12 @@ public class Utils {
}
}
public static String getMachine(Context context) {
String device = Build.MODEL;//机型
String imei = getIMEI(context);
String system_version = Build.VERSION.RELEASE;
String firmware_version = getProperty("ro.build.display.id", "获取失败");
String rom = getProperty("ro.custom.build.version", "获取失败");
String screen_rate = getAndroiodScreenProperty(context);
JSONObject jsonObject = new JSONObject();
jsonObject.put("device", device);
jsonObject.put("imei", imei);
jsonObject.put("system_version", system_version);
jsonObject.put("firmware_version", firmware_version);
jsonObject.put("rom", rom);
jsonObject.put("screen_rate", screen_rate);
return jsonObject.toJSONString();
}
/**
* 获取系统配置信息
* @param key
* @param defaultValue
* @return
*/
public static String getProperty(String key, String defaultValue) {
String value = defaultValue;
try {
@@ -1379,54 +1186,87 @@ public class Utils {
}
}
public static String getMachine(Context context) {
String device = Build.MODEL;//机型
String imei = getIMEI(context);
Log.e(TAG, "getMachine: " + imei);
String system_version = Build.VERSION.RELEASE;
String firmware_version = JGYUtils.getRomVersion();
String rom = JGYUtils.getCustomVersion();
String screen_rate = getAndroiodScreenProperty(context);
JSONObject jsonObject = new JSONObject();
jsonObject.put("device", device);
jsonObject.put("imei", imei);
jsonObject.put("system_version", system_version);
jsonObject.put("firmware_version", firmware_version);
jsonObject.put("rom", rom);
jsonObject.put("screen_rate", screen_rate);
return jsonObject.toJSONString();
}
public static String getHardware(Context context) {
int electric = getBattery(context);
int charging = getIsCharging(context);
String memory = Formatter.formatFileSize(context, getAvailMemory(context)) + "\t 已用" + "/" + "" + Formatter.formatFileSize(context, getTotalMemory(context));
String storage = getRemnantSize(context) + "/" + getDataTotalSize(context);
String memory = Formatter.formatFileSize(context, getUsedMemory(context)) + "\t 已用" + "/" + "" + Formatter.formatFileSize(context, getTotalMemory(context));
Log.e(TAG, "getHardware: memory = " + memory);
int use_ram = (int) ((float) (1.0 * getUsedMemory(context)) / (1.0 * getTotalMemory(context)) * 100);
Log.e(TAG, "getHardware: use_ram = " + use_ram);
String storage = getUsedSize(context) + "/" + getDataTotalSize(context);
Log.e(TAG, "getHardware: storage = " + storage);
double use_space = getUse_space(context);
Log.e(TAG, "getHardware: use_space = " + use_space);
long wifi_time = (long) com.info.sn.utils.SPUtils.get(context, "wifi_last_connect_time", 0L)/1000;
Log.e(TAG, "getHardware: wifi_time" + wifi_time);
int CPU = getNumCores();
JSONObject jsonObject = new JSONObject();
jsonObject.put("electric", electric);
jsonObject.put("charging", charging);
jsonObject.put("memory", memory);
jsonObject.put("storage", storage);
jsonObject.put("is_wifi", JGYUtils.isWifiConnect(context));
jsonObject.put("CPU", CPU + "");
jsonObject.put("use_space", use_space);
jsonObject.put("use_ram", use_ram);
jsonObject.put("wifi_ssid", getWifiSSID(context));
jsonObject.put("wifi_time", wifi_time);
jsonObject.put("boot_time", SystemClock.elapsedRealtime());
Log.e(TAG, "getHardware: " + jsonObject.toJSONString());
return jsonObject.toJSONString();
}
public static void rebootDevices(Context context) {
if (BuildConfig.DEBUG) {
ToastUtil.show("收到重启设备推送消息");
return;
public static String getWifiSSID(Context context) {
WifiManager wifiManager = (WifiManager) context.getSystemService(Context.WIFI_SERVICE);
WifiInfo wifiInfo = wifiManager.getConnectionInfo();
if (wifiInfo != null) {
return wifiInfo.getSSID();
} else {
return "";
}
Intent iReboot = new Intent(Intent.ACTION_REBOOT);
iReboot.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
context.startActivity(iReboot);
}
synchronized public static void doMasterClear(Context context) {
if (BuildConfig.DEBUG) {
ToastUtil.show("收到重置设备推送消息");
return;
}
if (Build.VERSION.SDK_INT > Build.VERSION_CODES.N_MR1) {
Intent intent = new Intent("android.intent.action.FACTORY_RESET");
intent.setPackage("android");
intent.addFlags(Intent.FLAG_RECEIVER_FOREGROUND);
intent.putExtra("android.intent.extra.REASON", "MasterClearConfirm");
intent.putExtra("android.intent.extra.WIPE_EXTERNAL_STORAGE", false);
intent.putExtra("com.android.internal.intent.extra.WIPE_ESIMS", false);
context.sendBroadcast(intent);
} else {
//10.0的不需要最小电量
// if (getBatteryLevel(context) >= CommonDatas.MIN_POWER) {
Intent intent = new Intent("android.intent.action.MASTER_CLEAR");
// intent.setPackage("com.android.settings");
context.sendBroadcast(intent);
// } else {
// MySQLData.SetBooleanData(context, CommonDatas.IS_RESET, true);
// }
public static String getAppUsedStatistics(Context context) {
StatisticsInfo statisticsInfo = new StatisticsInfo(context, 3);
long totalTime = statisticsInfo.getTotalTime();
int totalTimes = statisticsInfo.getTotalTimes();
List<AppInformation> datalist = statisticsInfo.getShowList();
List<AppUsed> appUsedList = new ArrayList<>();
for (AppInformation information : datalist) {
AppUsed used = new AppUsed();
used.setPackages(information.getPackageName());
used.setUseTime(information.getUsedTimebyDay() / 1000);
used.setApp_name(information.getLabel());
appUsedList.add(used);
}
appUsedList.removeIf(new Predicate<AppUsed>() {
@Override
public boolean test(AppUsed appUsed) {
return appUsed.getUseTime() == 0;
}
});
String jsonString = JSON.toJSONString(appUsedList);
return jsonString;
}
}