当前位置:   article > 正文

android系统api工具类_android systemapi

android systemapi
  1. package com.boeyu.systemmanagerlib;
  2. import android.accessibilityservice.AccessibilityService;
  3. import android.annotation.SuppressLint;
  4. import android.app.ActivityManager;
  5. import android.app.AlarmManager;
  6. import android.app.AppOpsManager;
  7. import android.app.PendingIntent;
  8. import android.app.Service;
  9. import android.app.admin.DeviceAdminReceiver;
  10. import android.app.admin.DevicePolicyManager;
  11. import android.content.BroadcastReceiver;
  12. import android.content.ComponentName;
  13. import android.content.Context;
  14. import android.content.Intent;
  15. import android.content.pm.ApplicationInfo;
  16. import android.content.pm.IPackageDataObserver;
  17. import android.content.pm.IPackageDeleteObserver;
  18. import android.content.pm.IPackageInstallObserver;
  19. import android.content.pm.PackageInfo;
  20. import android.content.pm.PackageInstaller;
  21. import android.content.pm.PackageManager;
  22. import android.content.pm.ResolveInfo;
  23. import android.graphics.Bitmap;
  24. import android.graphics.PixelFormat;
  25. import android.graphics.Point;
  26. import android.graphics.Rect;
  27. import android.hardware.display.DisplayManager;
  28. import android.hardware.display.VirtualDisplay;
  29. import android.hardware.usb.UsbManager;
  30. import android.media.Image;
  31. import android.media.ImageReader;
  32. import android.net.Uri;
  33. import android.net.wifi.WifiManager;
  34. import android.os.Build;
  35. import android.os.Handler;
  36. import android.os.IBinder;
  37. import android.os.IInterface;
  38. import android.os.Looper;
  39. import android.os.PowerManager;
  40. import android.os.RecoverySystem;
  41. import android.os.RemoteException;
  42. import android.os.SystemClock;
  43. import android.os.UserHandle;
  44. import android.os.UserManager;
  45. import android.os.storage.StorageManager;
  46. import android.os.storage.StorageVolume;
  47. import android.provider.Settings;
  48. import android.util.DisplayMetrics;
  49. import android.util.Log;
  50. import android.view.View;
  51. import android.view.WindowManager;
  52. import android.widget.Toast;
  53. import java.io.File;
  54. import java.io.FileInputStream;
  55. import java.io.IOException;
  56. import java.io.InputStream;
  57. import java.io.OutputStream;
  58. import java.lang.reflect.Constructor;
  59. import java.lang.reflect.Field;
  60. import java.lang.reflect.Method;
  61. import java.nio.ByteBuffer;
  62. import java.util.ArrayList;
  63. import java.util.Collection;
  64. import java.util.HashSet;
  65. import java.util.List;
  66. import java.util.Map;
  67. import java.util.Set;
  68. import java.util.regex.Pattern;
  69. /**
  70. * Created by yuanfang235 on 2019-12-26.
  71. */
  72. public class SystemApi {
  73. private static final String TAG = "WALX";
  74. /**
  75. * op值,参考AppOpsManager类的声明
  76. */
  77. public static final int OP_NONE = -1;
  78. public static final int OP_COARSE_LOCATION = 0;
  79. public static final int OP_FINE_LOCATION = 1;
  80. public static final int OP_GPS = 2;
  81. public static final int OP_VIBRATE = 3;
  82. public static final int OP_READ_CONTACTS = 4;
  83. public static final int OP_WRITE_CONTACTS = 5;
  84. public static final int OP_READ_CALL_LOG = 6;
  85. public static final int OP_WRITE_CALL_LOG = 7;
  86. public static final int OP_READ_CALENDAR = 8;
  87. public static final int OP_WRITE_CALENDAR = 9;
  88. public static final int OP_WIFI_SCAN = 10;
  89. public static final int OP_POST_NOTIFICATION = 11;
  90. public static final int OP_NEIGHBORING_CELLS = 12;
  91. public static final int OP_CALL_PHONE = 13;
  92. public static final int OP_READ_SMS = 14;
  93. public static final int OP_WRITE_SMS = 15;
  94. public static final int OP_RECEIVE_SMS = 16;
  95. public static final int OP_RECEIVE_EMERGECY_SMS = 17;
  96. public static final int OP_RECEIVE_MMS = 18;
  97. public static final int OP_RECEIVE_WAP_PUSH = 19;
  98. public static final int OP_SEND_SMS = 20;
  99. public static final int OP_READ_ICC_SMS = 21;
  100. public static final int OP_WRITE_ICC_SMS = 22;
  101. public static final int OP_WRITE_SETTINGS = 23;
  102. public static final int OP_SYSTEM_ALERT_WINDOW = 24;
  103. public static final int OP_ACCESS_NOTIFICATIONS = 25;
  104. public static final int OP_CAMERA = 26;
  105. public static final int OP_RECORD_AUDIO = 27;
  106. public static final int OP_PLAY_AUDIO = 28;
  107. public static final int OP_READ_CLIPBOARD = 29;
  108. public static final int OP_WRITE_CLIPBOARD = 30;
  109. public static final int OP_TAKE_MEDIA_BUTTONS = 31;
  110. public static final int OP_TAKE_AUDIO_FOCUS = 32;
  111. public static final int OP_AUDIO_MASTER_VOLUME = 33;
  112. public static final int OP_AUDIO_VOICE_VOLUME = 34;
  113. public static final int OP_AUDIO_RING_VOLUME = 35;
  114. public static final int OP_AUDIO_MEDIA_VOLUME = 36;
  115. public static final int OP_AUDIO_ALARM_VOLUME = 37;
  116. public static final int OP_AUDIO_NOTIFICATION_VOLUME = 38;
  117. public static final int OP_AUDIO_BLUETOOTH_VOLUME = 39;
  118. public static final int OP_WAKE_LOCK = 40;
  119. public static final int OP_MONITOR_LOCATION = 41;
  120. public static final int OP_MONITOR_HIGH_POWER_LOCATION = 42;
  121. public static final int OP_GET_USAGE_STATS = 43;
  122. public static final int OP_MUTE_MICROPHONE = 44;
  123. public static final int OP_TOAST_WINDOW = 45;
  124. public static final int OP_PROJECT_MEDIA = 46;
  125. public static final int OP_ACTIVATE_VPN = 47;
  126. public static final int OP_WRITE_WALLPAPER = 48;
  127. public static final int OP_ASSIST_STRUCTURE = 49;
  128. public static final int OP_ASSIST_SCREENSHOT = 50;
  129. public static final int OP_READ_PHONE_STATE = 51;
  130. public static final int OP_ADD_VOICEMAIL = 52;
  131. public static final int OP_USE_SIP = 53;
  132. public static final int OP_PROCESS_OUTGOING_CALLS = 54;
  133. public static final int OP_USE_FINGERPRINT = 55;
  134. public static final int OP_BODY_SENSORS = 56;
  135. public static final int OP_READ_CELL_BROADCASTS = 57;
  136. public static final int OP_MOCK_LOCATION = 58;
  137. public static final int OP_READ_EXTERNAL_STORAGE = 59;
  138. public static final int OP_WRITE_EXTERNAL_STORAGE = 60;
  139. public static final int OP_TURN_SCREEN_ON = 61;
  140. public static final int OP_GET_ACCOUNTS = 62;
  141. public static final int OP_RUN_IN_BACKGROUND = 63;
  142. public static final int OP_AUDIO_ACCESSIBILITY_VOLUME = 64;
  143. public static final int OP_READ_PHONE_NUMBERS = 65;
  144. public static final int OP_REQUEST_INSTALL_PACKAGES = 66;
  145. public static final int OP_PICTURE_IN_PICTURE = 67;
  146. public static final int OP_INSTANT_APP_START_FOREGROUND = 68;
  147. public static final int OP_ANSWER_PHONE_CALLS = 69;
  148. public static final String OPSTR_PROJECT_MEDIA = "android:project_media";
  149. public static final int STATUS_SUCCESS = 0;
  150. public static final int STATUS_FAILURE = 1;
  151. public static final String USB_FUNCTION_NONE = "none";
  152. public static final String USB_FUNCTION_ADB = "adb";
  153. public static final String USB_FUNCTION_RNDIS = "rndis";
  154. public static final String USB_FUNCTION_MTP = "mtp";
  155. public static final String USB_FUNCTION_PTP = "ptp";
  156. public static final int ERROR_COMPONENT_STATE = -1;
  157. /* 权限标志 */
  158. public static final int FLAG_PERMISSION_ERROR = 0;
  159. public static final int FLAG_PERMISSION_USER_SET = 1 << 0;
  160. public static final int FLAG_PERMISSION_USER_FIXED = 1 << 1;
  161. public static final int FLAG_PERMISSION_POLICY_FIXED = 1 << 2;
  162. public static final int FLAG_PERMISSION_REVOKE_ON_UPGRADE = 1 << 3;
  163. public static final int FLAG_PERMISSION_SYSTEM_FIXED = 1 << 4;
  164. public static final int FLAG_PERMISSION_GRANTED_BY_DEFAULT = 1 << 5;
  165. public static final int FLAG_PERMISSION_REVIEW_REQUIRED = 1 << 6;
  166. public static final int MASK_PERMISSION_FLAGS = 0xFF;
  167. /*************************************************/
  168. private static final int INSTALL_SUCCEEDED = 1;
  169. private static final int DELETE_SUCCEEDED = 1;
  170. private static final int INSTALL_REPLACE_EXISTING = 0x00000002;
  171. private static final int DELETE_SYSTEM_APP = 0x00000004;
  172. private static final int OP_MODE_INVALID = -1;
  173. private static final String ACTION_MASTER_CLEAR = "android.intent.action.MASTER_CLEAR";
  174. private static final String EXTRA_REASON = "android.intent.extra.REASON";
  175. private static final String EXTRA_WIPE_EXTERNAL_STORAGE = "android.intent.extra.WIPE_EXTERNAL_STORAGE";
  176. private static final String ACTION_FACTORY_RESET = "android.intent.action.FACTORY_RESET"; //8.0
  177. private static final int STATUS_BAR_DISABLE_EXPAND = 0x00010000;
  178. private static final int DISABLE2_QUICK_SETTINGS = 1;
  179. private static final int DISABLE2_SYSTEM_ICONS = 1 << 1;
  180. private static final int DISABLE2_NOTIFICATION_SHADE = 1 << 2;
  181. private static final int DISABLE2_GLOBAL_ACTIONS = 1 << 3;
  182. private static final int DISABLE2_ROTATE_SUGGESTIONS = 1 << 4;
  183. private static final int DISABLE2_NONE = 0x00000000;
  184. private static final int DISABLE2_MASK = DISABLE2_QUICK_SETTINGS | DISABLE2_SYSTEM_ICONS
  185. | DISABLE2_NOTIFICATION_SHADE | DISABLE2_ROTATE_SUGGESTIONS;
  186. private static final int FIREWALL_RULE_DEFAULT = 0;
  187. private static final int FIREWALL_RULE_ALLOW = 1;
  188. private static final int FIREWALL_RULE_DENY = 2;
  189. private Context mContext;
  190. private Handler mHandler = new Handler(Looper.getMainLooper());
  191. private boolean mDebug;
  192. private boolean mLoggerEnabled;
  193. public SystemApi(Context context) {
  194. this.mContext = context;
  195. mDebug = (mContext.getApplicationInfo().flags & ApplicationInfo.FLAG_DEBUGGABLE) != 0;
  196. }
  197. /**
  198. * 允许运行时权限
  199. *
  200. * @param packageName
  201. * @param permissions
  202. * @return
  203. */
  204. public SystemApi allowPermission(String packageName, String... permissions) {
  205. if (permissions == null || permissions.length == 0) return this;
  206. if (!needRuntimePermission()) return this;
  207. for (String permission : permissions) {
  208. if (!grantRuntimePermission(packageName, permission)) {
  209. setUidMode(packageName, AppOpsManager.permissionToOp(permission), AppOpsManager.MODE_ALLOWED);
  210. }
  211. if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
  212. setUidMode(packageName, AppOpsManager.permissionToOp(permission), AppOpsManager.MODE_ALLOWED);
  213. }
  214. }
  215. return this;
  216. }
  217. public SystemApi allowPermission(String packageName, Collection<String> permissions) {
  218. if (permissions == null || permissions.isEmpty()) return this;
  219. String[] array = new String[permissions.size()];
  220. permissions.toArray(array);
  221. return allowPermission(packageName, array);
  222. }
  223. /**
  224. * 禁止运行时权限
  225. *
  226. * @param packageName
  227. * @param permissions
  228. * @return
  229. */
  230. public SystemApi denyPermission(String packageName, String... permissions) {
  231. if (permissions == null || permissions.length == 0) return this;
  232. if (!needRuntimePermission()) return this;
  233. for (String permission : permissions) {
  234. revokeRuntimePermission(packageName, permission);
  235. if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
  236. setUidMode(packageName, AppOpsManager.permissionToOp(permission), AppOpsManager.MODE_IGNORED);
  237. }
  238. }
  239. return this;
  240. }
  241. public SystemApi denyPermission(String packageName, Collection<String> permissions) {
  242. if (permissions == null || permissions.isEmpty()) return this;
  243. String[] array = new String[permissions.size()];
  244. permissions.toArray(array);
  245. return denyPermission(packageName, array);
  246. }
  247. /**
  248. * 固定权限
  249. *
  250. * @param packageName
  251. * @param permissions
  252. * @return
  253. */
  254. public SystemApi fixedPermission(String packageName, String... permissions) {
  255. if (permissions == null || permissions.length == 0) return this;
  256. if (!needRuntimePermission()) return this;
  257. for (String permission : permissions) {
  258. fixedPermissionInner(packageName, permission);
  259. }
  260. return this;
  261. }
  262. /**
  263. * 不固定权限
  264. *
  265. * @param packageName
  266. * @param permissions
  267. * @return
  268. */
  269. public SystemApi unfixedPermission(String packageName, String... permissions) {
  270. if (permissions == null || permissions.length == 0) return this;
  271. if (!needRuntimePermission()) return this;
  272. for (String permission : permissions) {
  273. unfixedPermissionInner(packageName, permission);
  274. }
  275. return this;
  276. }
  277. /**
  278. * 获取权限标志
  279. *
  280. * @param packageName
  281. * @param permission
  282. * @return
  283. */
  284. public int getPermissionFlags(String packageName, String permission) {
  285. try {
  286. Method method = PackageManager.class.getMethod("getPermissionFlags", String.class, String.class, UserHandle.class);
  287. UserHandle userHandle = (UserHandle) newInstance(UserHandle.class, new Class[]{int.class}, 0);
  288. return (int) method.invoke(mContext.getPackageManager(), permission, packageName, userHandle);
  289. } catch (Exception e) {
  290. printError(e);
  291. }
  292. return FLAG_PERMISSION_ERROR;
  293. }
  294. /**
  295. * 更新权限标志
  296. *
  297. * @param packageName
  298. * @param permission
  299. * @param flagMask
  300. * @param flagValues
  301. */
  302. public void updatePermissionFlags(String packageName, String permission, int flagMask, int flagValues) {
  303. try {
  304. Method method = PackageManager.class.getMethod("updatePermissionFlags", String.class, String.class, int.class, int.class, UserHandle.class);
  305. UserHandle userHandle = (UserHandle) newInstance(UserHandle.class, new Class[]{int.class}, 0);
  306. method.invoke(mContext.getPackageManager(), permission, packageName, flagMask, flagValues, userHandle);
  307. } catch (Exception e) {
  308. printError(e);
  309. }
  310. }
  311. /**
  312. * 是否获取权限
  313. *
  314. * @param packageName
  315. * @param permissions
  316. * @return
  317. */
  318. public boolean isPermissionAllowed(String packageName, String... permissions) {
  319. if (permissions == null || permissions.length == 0) return true;
  320. if (!needRuntimePermission()) return true;
  321. Set<String> mDeniedPermissionList = getDeniedPermissionList(packageName, permissions);
  322. return mDeniedPermissionList.isEmpty();
  323. }
  324. /**
  325. * 是否是固定权限
  326. *
  327. * @param packageName
  328. * @param permission
  329. * @return
  330. */
  331. public boolean isFixedPermission(String packageName, String permission) {
  332. int flags = getPermissionFlags(packageName, permission);
  333. return (flags & FLAG_PERMISSION_SYSTEM_FIXED) == FLAG_PERMISSION_SYSTEM_FIXED
  334. || (flags & FLAG_PERMISSION_POLICY_FIXED) == FLAG_PERMISSION_POLICY_FIXED;
  335. }
  336. /**
  337. * 设置OP模式
  338. *
  339. * @param packageName
  340. * @param opCode
  341. * @param mode
  342. * @return
  343. */
  344. public SystemApi setOpMode(String packageName, int opCode, int mode) {
  345. try {
  346. Method method = AppOpsManager.class.getMethod("setMode", int.class, int.class, String.class, int.class);
  347. AppOpsManager mAppOps = (AppOpsManager) mContext.getSystemService(Service.APP_OPS_SERVICE);
  348. method.invoke(mAppOps, opCode, getPackageUid(packageName), packageName, mode);
  349. } catch (Exception e) {
  350. printError(e);
  351. }
  352. return this;
  353. }
  354. /**
  355. * 设置Uid模式
  356. *
  357. * @param packageName
  358. * @param opCode
  359. * @param mode
  360. */
  361. public void setUidMode(String packageName, int opCode, int mode) {
  362. try {
  363. Method method = AppOpsManager.class.getMethod("setUidMode", int.class, int.class, int.class);
  364. AppOpsManager mAppOps = (AppOpsManager) mContext.getSystemService(Service.APP_OPS_SERVICE);
  365. method.invoke(mAppOps, opCode, getPackageUid(packageName), mode);
  366. } catch (Exception e) {
  367. printError(e);
  368. }
  369. }
  370. /**
  371. * 设置Uid模式
  372. *
  373. * @param packageName
  374. * @param appOp
  375. * @param mode
  376. */
  377. public void setUidMode(String packageName, String appOp, int mode) {
  378. try {
  379. Method method = AppOpsManager.class.getMethod("setUidMode", String.class, int.class, int.class);
  380. AppOpsManager mAppOps = (AppOpsManager) mContext.getSystemService(Service.APP_OPS_SERVICE);
  381. method.invoke(mAppOps, appOp, getPackageUid(packageName), mode);
  382. } catch (Exception e) {
  383. printError(e);
  384. }
  385. }
  386. /**
  387. * 允许OP权限
  388. *
  389. * @param packageName
  390. * @param opCode
  391. * @return
  392. */
  393. public SystemApi allowOp(String packageName, int opCode) {
  394. setOpMode(packageName, opCode, AppOpsManager.MODE_ALLOWED);
  395. return this;
  396. }
  397. /**
  398. * 禁止OP权限
  399. *
  400. * @param packageName
  401. * @param opCode
  402. * @return
  403. */
  404. public SystemApi denyOp(String packageName, int opCode) {
  405. setOpMode(packageName, opCode, AppOpsManager.MODE_IGNORED);
  406. return this;
  407. }
  408. public SystemApi allowOp(String packageName, int opCode, boolean isAllow) {
  409. if (isAllow) {
  410. allowOp(packageName, opCode);
  411. } else {
  412. denyOp(packageName, opCode);
  413. }
  414. return this;
  415. }
  416. /**
  417. * 是否允许OP
  418. *
  419. * @param packageName
  420. * @param opCode
  421. * @return
  422. */
  423. public boolean isOpAllowed(String packageName, int opCode) {
  424. return getOpMode(packageName, opCode) == AppOpsManager.MODE_ALLOWED;
  425. }
  426. /**
  427. * 获取OP模式
  428. *
  429. * @param packageName
  430. * @param opCode
  431. * @return
  432. */
  433. public int getOpMode(String packageName, int opCode) {
  434. try {
  435. Object object = mContext.getSystemService(Context.APP_OPS_SERVICE);
  436. if (object == null) {
  437. return AppOpsManager.MODE_ALLOWED;
  438. }
  439. Class localClass = object.getClass();
  440. Class[] arrayOfClass = new Class[3];
  441. arrayOfClass[0] = Integer.TYPE;
  442. arrayOfClass[1] = Integer.TYPE;
  443. arrayOfClass[2] = String.class;
  444. Method method = localClass.getMethod("checkOpNoThrow", arrayOfClass);
  445. if (method == null) {
  446. return OP_MODE_INVALID;
  447. }
  448. Object[] arrayOfObject = new Object[3];
  449. arrayOfObject[0] = Integer.valueOf(opCode);
  450. arrayOfObject[1] = Integer.valueOf(getPackageUid(packageName));
  451. arrayOfObject[2] = packageName;
  452. int m = ((Integer) method.invoke(object, arrayOfObject)).intValue();
  453. return m;
  454. } catch (Exception e) {
  455. printError(e);
  456. }
  457. return OP_MODE_INVALID;
  458. }
  459. /**
  460. * 允许禁止悬浮窗权限
  461. *
  462. * @param packageName
  463. * @return
  464. */
  465. public SystemApi allowDrawOverlays(String packageName, boolean isAllow) {
  466. if (needRuntimePermission()) {
  467. setOpState(packageName, OP_SYSTEM_ALERT_WINDOW, isAllow);
  468. }
  469. return this;
  470. }
  471. /**
  472. * 是否允许悬浮窗
  473. *
  474. * @param packageName
  475. * @return
  476. */
  477. public boolean isDrawOverlaysAllowed(String packageName) {
  478. return isOpAllowed(packageName, OP_SYSTEM_ALERT_WINDOW);
  479. }
  480. /**
  481. * 允许禁止修改设置权限
  482. *
  483. * @param packageName
  484. * @return
  485. */
  486. public SystemApi allowWriteSettings(String packageName, boolean isAllow) {
  487. if (needRuntimePermission()) {
  488. setOpState(packageName, OP_WRITE_SETTINGS, isAllow);
  489. }
  490. return this;
  491. }
  492. /**
  493. * 是否允许修改设置
  494. *
  495. * @param packageName
  496. * @return
  497. */
  498. public boolean isWriteSettingsAllowed(String packageName) {
  499. return isOpAllowed(packageName, OP_WRITE_SETTINGS);
  500. }
  501. /**
  502. * 允许禁止查看应用统计
  503. *
  504. * @param packageName
  505. * @return
  506. */
  507. public SystemApi allowUsageStats(String packageName, boolean isAllow) {
  508. setOpState(packageName, OP_GET_USAGE_STATS, isAllow);
  509. return this;
  510. }
  511. /**
  512. * 是否允许查看应用统计
  513. *
  514. * @param packageName
  515. * @return
  516. */
  517. public boolean isUsageStatsAllowed(String packageName) {
  518. return isOpAllowed(packageName, OP_GET_USAGE_STATS);
  519. }
  520. /**
  521. * 允许禁止投屏
  522. *
  523. * @param packageName
  524. * @return
  525. */
  526. public SystemApi allowProjectMedia(String packageName, boolean isAllow) {
  527. setOpState(packageName, OP_PROJECT_MEDIA, isAllow);
  528. return this;
  529. }
  530. /**
  531. * 是否允许投屏
  532. *
  533. * @param packageName
  534. * @return
  535. */
  536. public boolean isProjectMediaAllowed(String packageName) {
  537. return isOpAllowed(packageName, OP_PROJECT_MEDIA);
  538. }
  539. /**
  540. * 允许安装包,android11会被系统杀死
  541. *
  542. * @param packageName
  543. * @param isAllow
  544. * @return
  545. */
  546. public SystemApi allowInstallPackage(String packageName, boolean isAllow) {
  547. if (Build.VERSION.SDK_INT < 30) {
  548. //android10及以下
  549. setOpState(packageName, OP_REQUEST_INSTALL_PACKAGES, isAllow);
  550. }
  551. return this;
  552. }
  553. /**
  554. * 是否允许安装包
  555. *
  556. * @param packageName
  557. * @return
  558. */
  559. public boolean isInstallPackageAllowed(String packageName) {
  560. return isOpAllowed(packageName, OP_REQUEST_INSTALL_PACKAGES);
  561. }
  562. /**
  563. * 允许禁止无障碍
  564. *
  565. * @param packageName
  566. * @param className
  567. * @param allow
  568. * @return
  569. */
  570. public SystemApi allowAccessibility(String packageName, String className, boolean allow) {
  571. if (!isSupportAccessibility()) return this;
  572. boolean hasService = isAccessibilityServiceEnabled(packageName, className);
  573. String srcServiceName = Settings.Secure.getString(mContext.getContentResolver(), Settings.Secure.ENABLED_ACCESSIBILITY_SERVICES);
  574. String myServiceName = packageName + "/" + className;
  575. if (allow) {
  576. if (!hasService) {
  577. int enabled = 0;
  578. try {
  579. enabled = Settings.Secure.getInt(mContext.getContentResolver(), Settings.Secure.ACCESSIBILITY_ENABLED);
  580. } catch (Throwable e) {
  581. printError(e);
  582. }
  583. if (enabled == 0) {
  584. try {
  585. Settings.Secure.putInt(mContext.getContentResolver(), Settings.Secure.ACCESSIBILITY_ENABLED, 1);
  586. } catch (Throwable e) {
  587. printError(e);
  588. }
  589. }
  590. if (srcServiceName == null || srcServiceName.trim().isEmpty()) {
  591. srcServiceName = myServiceName;
  592. } else {
  593. srcServiceName = srcServiceName + ":" + myServiceName;
  594. }
  595. try {
  596. Settings.Secure.putString(mContext.getContentResolver(), Settings.Secure.ENABLED_ACCESSIBILITY_SERVICES, makeSettingsValue(srcServiceName));
  597. } catch (Throwable e) {
  598. e.printStackTrace();
  599. }
  600. }
  601. } else {
  602. if (hasService) {
  603. if (srcServiceName.equals(myServiceName)) {
  604. srcServiceName = "";
  605. } else {
  606. if (srcServiceName.endsWith(myServiceName)) {
  607. srcServiceName = srcServiceName.replace(":" + myServiceName, "");
  608. } else {
  609. srcServiceName = srcServiceName.replace(myServiceName + ":", "");
  610. }
  611. }
  612. if (srcServiceName.isEmpty()) {
  613. srcServiceName = "\"\"";
  614. }
  615. try {
  616. Settings.Secure.putString(mContext.getContentResolver(), Settings.Secure.ENABLED_ACCESSIBILITY_SERVICES, makeSettingsValue(srcServiceName));
  617. } catch (Throwable e) {
  618. printError(e);
  619. }
  620. }
  621. }
  622. return this;
  623. }
  624. /**
  625. * 允许禁止无障碍
  626. *
  627. * @param service
  628. * @param allow
  629. * @return
  630. */
  631. public SystemApi allowAccessibility(Class<? extends AccessibilityService> service, boolean allow) {
  632. allowAccessibility(mContext.getPackageName(), service.getName(), allow);
  633. return this;
  634. }
  635. /**
  636. * 允许禁止无障碍
  637. *
  638. * @param service
  639. * @param allow
  640. * @return
  641. */
  642. public SystemApi allowAccessibility(ComponentName service, boolean allow) {
  643. allowAccessibility(service.getPackageName(), service.getClassName(), allow);
  644. return this;
  645. }
  646. /**
  647. * 允许禁止设备管理器
  648. *
  649. * @param packageName
  650. * @param className
  651. * @param allow
  652. * @return
  653. */
  654. public SystemApi allowDeviceAdmin(String packageName, String className, boolean allow) {
  655. allowDeviceAdmin(new ComponentName(packageName, className), allow);
  656. return this;
  657. }
  658. public SystemApi allowDeviceAdmin(String componentName, boolean allow) {
  659. allowDeviceAdmin(parse(componentName), allow);
  660. return this;
  661. }
  662. /**
  663. * 允许禁止设备管理器
  664. *
  665. * @param activeAdmin
  666. * @param allow
  667. * @return
  668. */
  669. public SystemApi allowDeviceAdmin(Class<? extends DeviceAdminReceiver> activeAdmin, boolean allow) {
  670. allowDeviceAdmin(new ComponentName(mContext, activeAdmin), allow);
  671. return this;
  672. }
  673. /**
  674. * 允许禁止设备管理器
  675. *
  676. * @param activeAdmin
  677. * @param allow
  678. * @return
  679. */
  680. public SystemApi allowDeviceAdmin(ComponentName activeAdmin, boolean allow) {
  681. if (activeAdmin == null) return this;
  682. if (!isSupportDeviceAdmin()) return this;
  683. if (allow) {
  684. try {
  685. Method method = DevicePolicyManager.class.getMethod("setActiveAdmin", ComponentName.class, boolean.class);
  686. DevicePolicyManager dpm = (DevicePolicyManager) mContext.getSystemService(Service.DEVICE_POLICY_SERVICE);
  687. method.invoke(dpm, activeAdmin, true);
  688. } catch (Exception e) {
  689. printError(e);
  690. }
  691. } else {
  692. try {
  693. DevicePolicyManager dpm = (DevicePolicyManager) mContext.getSystemService(Service.DEVICE_POLICY_SERVICE);
  694. dpm.removeActiveAdmin(activeAdmin);
  695. } catch (Exception e) {
  696. printError(e);
  697. }
  698. }
  699. return this;
  700. }
  701. /**
  702. * 是否支持设备管理器
  703. *
  704. * @return
  705. */
  706. public static boolean isSupportDeviceAdmin() {
  707. return Build.VERSION.SDK_INT >= Build.VERSION_CODES.FROYO;
  708. }
  709. /**
  710. * 是否支持无障碍
  711. *
  712. * @return
  713. */
  714. public static boolean isSupportAccessibility() {
  715. return Build.VERSION.SDK_INT >= Build.VERSION_CODES.DONUT;
  716. }
  717. /**
  718. * 是否需要请求权限
  719. *
  720. * @return
  721. */
  722. public static boolean needRuntimePermission() {
  723. return Build.VERSION.SDK_INT >= Build.VERSION_CODES.M;
  724. }
  725. /**
  726. * 是否启用无障碍
  727. *
  728. * @param pkgName
  729. * @param className
  730. * @return
  731. */
  732. public boolean isAccessibilityServiceEnabled(String pkgName, String className) {
  733. if (!isSupportAccessibility()) {
  734. return false;
  735. }
  736. if (isEmpty(pkgName) || isEmpty(className)) {
  737. return false;
  738. }
  739. try {
  740. int enabled = Settings.Secure.getInt(mContext.getContentResolver(), Settings.Secure.ACCESSIBILITY_ENABLED);
  741. if (enabled == 1) {
  742. String service = Settings.Secure.getString(mContext.getContentResolver(), Settings.Secure.ENABLED_ACCESSIBILITY_SERVICES);
  743. if (className.startsWith(".")) {
  744. className = pkgName + className;
  745. }
  746. String myServiceName = pkgName + "/" + className;
  747. boolean hasService = service != null && service.contains(myServiceName);
  748. return hasService;
  749. }
  750. } catch (Exception e) {
  751. e.printStackTrace();
  752. }
  753. return false;
  754. }
  755. /**
  756. * 是否启用无障碍
  757. *
  758. * @param serviceClass
  759. * @return
  760. */
  761. public boolean isAccessibilityServiceEnabled(Class<? extends AccessibilityService> serviceClass) {
  762. return isAccessibilityServiceEnabled(mContext.getPackageName(), serviceClass.getCanonicalName());
  763. }
  764. /**
  765. * 是否启用无障碍
  766. *
  767. * @param service
  768. * @return
  769. */
  770. public boolean isAccessibilityServiceEnabled(ComponentName service) {
  771. return isAccessibilityServiceEnabled(service.getPackageName(), service.getClassName());
  772. }
  773. /**
  774. * 是否是设备管理器
  775. *
  776. * @param admin
  777. * @return
  778. */
  779. public boolean isDeviceAdmin(ComponentName admin) {
  780. if (!isSupportDeviceAdmin()) {
  781. return false;
  782. }
  783. DevicePolicyManager dpm = (DevicePolicyManager) mContext.getSystemService(Service.DEVICE_POLICY_SERVICE);
  784. return dpm.isAdminActive(admin);
  785. }
  786. /**
  787. * 是否是设备管理器
  788. *
  789. * @param pkgName
  790. * @param className
  791. * @return
  792. */
  793. public boolean isDeviceAdmin(String pkgName, String className) {
  794. return isDeviceAdmin(new ComponentName(pkgName, className));
  795. }
  796. /**
  797. * 是否是设备管理器
  798. *
  799. * @param receiverClass
  800. * @return
  801. */
  802. public boolean isDeviceAdmin(Class<? extends DeviceAdminReceiver> receiverClass) {
  803. return isDeviceAdmin(new ComponentName(mContext, receiverClass));
  804. }
  805. /**
  806. * 设置设备所有者
  807. *
  808. * @param pkgName
  809. * @return
  810. */
  811. public boolean setDeviceOwner(String pkgName) {
  812. if (!isSupportDeviceAdmin()) {
  813. return false;
  814. }
  815. ComponentName admin = getDeviceAdminClass(mContext, pkgName);
  816. if (admin == null) {
  817. return false;
  818. }
  819. DevicePolicyManager dpm = (DevicePolicyManager) mContext.getSystemService(Service.DEVICE_POLICY_SERVICE);
  820. try {
  821. Method method = dpm.getClass().getMethod("setDeviceOwner", ComponentName.class);
  822. return (boolean) method.invoke(dpm, admin);
  823. } catch (Exception e) {
  824. printError("setDeviceOwner", e);
  825. }
  826. return false;
  827. }
  828. /**
  829. * 移除设备所有者
  830. *
  831. * @param pkgName
  832. */
  833. public void removeDeviceOwner(String pkgName) {
  834. DevicePolicyManager dpm = (DevicePolicyManager) mContext.getSystemService(Service.DEVICE_POLICY_SERVICE);
  835. try {
  836. if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
  837. dpm.clearDeviceOwnerApp(pkgName);
  838. }
  839. } catch (Exception e) {
  840. printError(e);
  841. }
  842. }
  843. /**
  844. * 是否设备所有者
  845. *
  846. * @param pkgName
  847. * @return
  848. */
  849. public boolean isDeviceOwner(String pkgName) {
  850. if (!isSupportDeviceAdmin()) {
  851. return false;
  852. }
  853. DevicePolicyManager dpm = (DevicePolicyManager) mContext.getSystemService(Service.DEVICE_POLICY_SERVICE);
  854. if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN_MR2) {
  855. return dpm.isDeviceOwnerApp(pkgName);
  856. }
  857. return false;
  858. }
  859. /**
  860. * 设置包状态
  861. *
  862. * @param packageName
  863. * @param state PackageManager.COMPONENT_
  864. */
  865. public boolean setPackageState(String packageName, int state) {
  866. try {
  867. Log.d(TAG, "setPackageState: " + packageName + ", state=" + state);
  868. mContext.getPackageManager().setApplicationEnabledSetting(packageName, state, 0);
  869. return true;
  870. } catch (Exception e) {
  871. printError(e);
  872. }
  873. return false;
  874. }
  875. /**
  876. * 获取包状态
  877. *
  878. * @param packageName
  879. * @return
  880. */
  881. public int getPackageState(String packageName) {
  882. try {
  883. return mContext.getPackageManager().getApplicationEnabledSetting(packageName);
  884. } catch (Exception e) {
  885. printError(e);
  886. }
  887. return ERROR_COMPONENT_STATE;
  888. }
  889. /**
  890. * 设置组件状态
  891. *
  892. * @param componentName
  893. * @param state:PackageManager.COMPONENT_
  894. */
  895. public boolean setComponentState(ComponentName componentName, int state) {
  896. try {
  897. Log.d(TAG, "setComponentEnabledSetting: " + componentName.toShortString() + ", state=" + state);
  898. mContext.getPackageManager().setComponentEnabledSetting(componentName, state, 0);
  899. return true;
  900. } catch (Exception e) {
  901. printError("setComponentState", e);
  902. }
  903. return false;
  904. }
  905. /**
  906. * 获取组件状态
  907. *
  908. * @param componentName
  909. * @return
  910. */
  911. public int getComponentState(ComponentName componentName) {
  912. try {
  913. return mContext.getPackageManager().getComponentEnabledSetting(componentName);
  914. } catch (Exception e) {
  915. printError(e);
  916. }
  917. return ERROR_COMPONENT_STATE;
  918. }
  919. /**
  920. * 设置组件状态
  921. *
  922. * @param packageName
  923. * @param className
  924. * @param state:PackageManager.COMPONENT_
  925. */
  926. public boolean setComponentState(String packageName, String className, int state) {
  927. return setComponentState(new ComponentName(packageName, className), state);
  928. }
  929. /**
  930. * 禁止包
  931. *
  932. * @param packageName
  933. * @param disable true:禁止,false:恢复默认
  934. */
  935. public boolean disablePackage(String packageName, boolean disable) {
  936. return setPackageState(packageName, disable ? PackageManager.COMPONENT_ENABLED_STATE_DISABLED : PackageManager.COMPONENT_ENABLED_STATE_DEFAULT);
  937. }
  938. /**
  939. * 判断包是否禁止
  940. *
  941. * @param packageName
  942. * @return
  943. */
  944. public boolean isPackageDisabled(String packageName) {
  945. int state = getPackageState(packageName);
  946. return state == PackageManager.COMPONENT_ENABLED_STATE_DISABLED
  947. || state == PackageManager.COMPONENT_ENABLED_STATE_DISABLED_USER
  948. || state == PackageManager.COMPONENT_ENABLED_STATE_DISABLED_UNTIL_USED;
  949. }
  950. /**
  951. * 启用包
  952. *
  953. * @param packageName
  954. * @return
  955. */
  956. public boolean enablePackage(String packageName) {
  957. return setPackageState(packageName, PackageManager.COMPONENT_ENABLED_STATE_ENABLED);
  958. }
  959. /**
  960. * 禁止组件
  961. *
  962. * @param componentName
  963. * @param disable
  964. */
  965. public boolean disableComponent(ComponentName componentName, boolean disable) {
  966. return setComponentState(componentName, disable ? PackageManager.COMPONENT_ENABLED_STATE_DISABLED : PackageManager.COMPONENT_ENABLED_STATE_DEFAULT);
  967. }
  968. /**
  969. * 禁止组件
  970. *
  971. * @param packageName
  972. * @param className
  973. * @param disable true:禁止,false:恢复默认
  974. */
  975. public boolean disableComponent(String packageName, String className, boolean disable) {
  976. if (className != null && className.startsWith(".")) {
  977. className = packageName + className;
  978. }
  979. return disableComponent(new ComponentName(packageName, className), disable);
  980. }
  981. /**
  982. * 禁止组件
  983. *
  984. * @param componentName
  985. * @param disable
  986. */
  987. public void disableComponent(String componentName, boolean disable) {
  988. int start = componentName.indexOf('/');
  989. if (start != -1) {
  990. disableComponent(componentName.substring(0, start), componentName.substring(start + 1), disable);
  991. }
  992. }
  993. /**
  994. * 启用组件
  995. *
  996. * @param componentName
  997. * @return
  998. */
  999. public boolean enableComponent(ComponentName componentName) {
  1000. return setComponentState(componentName, PackageManager.COMPONENT_ENABLED_STATE_ENABLED);
  1001. }
  1002. /**
  1003. * 启用组件
  1004. *
  1005. * @param packageName
  1006. * @param className
  1007. * @return
  1008. */
  1009. public boolean enableComponent(String packageName, String className) {
  1010. return enableComponent(new ComponentName(packageName, className));
  1011. }
  1012. /**
  1013. * 判断组件是否禁止
  1014. *
  1015. * @param componentName
  1016. * @return
  1017. */
  1018. public boolean isComponentDisabled(ComponentName componentName) {
  1019. int state = getComponentState(componentName);
  1020. return state == PackageManager.COMPONENT_ENABLED_STATE_DISABLED
  1021. || state == PackageManager.COMPONENT_ENABLED_STATE_DISABLED_USER
  1022. || state == PackageManager.COMPONENT_ENABLED_STATE_DISABLED_UNTIL_USED;
  1023. }
  1024. /**
  1025. * 判断组件是否禁止
  1026. *
  1027. * @param packageName
  1028. * @param className
  1029. * @return
  1030. */
  1031. public boolean isComponentDisabled(String packageName, String className) {
  1032. return isComponentDisabled(new ComponentName(packageName, className));
  1033. }
  1034. /**
  1035. * 隐藏包
  1036. *
  1037. * @param packageName
  1038. * @param hidden
  1039. */
  1040. public void hideApplication(String packageName, boolean hidden) {
  1041. try {
  1042. Method method = PackageManager.class.getMethod("setApplicationHiddenSettingAsUser", String.class, boolean.class, UserHandle.class);
  1043. PackageManager pm = mContext.getPackageManager();
  1044. method.invoke(pm, packageName, hidden, newUserHandler(0));
  1045. } catch (Exception e) {
  1046. printError(e);
  1047. }
  1048. }
  1049. /**
  1050. * 判断包是否隐藏
  1051. *
  1052. * @param packageName
  1053. * @return
  1054. */
  1055. public boolean isApplicationHidden(String packageName) {
  1056. try {
  1057. Method method = PackageManager.class.getMethod("getApplicationHiddenSettingAsUser", String.class, UserHandle.class);
  1058. PackageManager pm = mContext.getPackageManager();
  1059. return (boolean) method.invoke(pm, packageName, newUserHandler(0));
  1060. } catch (Exception e) {
  1061. printError(e);
  1062. }
  1063. return false;
  1064. }
  1065. /*public String[] suspendPackage(String[] packageNames, boolean suspended) {
  1066. try {
  1067. Method method = PackageManager.class.getMethod("setPackagesSuspendedAsUser", String[].class, boolean.class, int.class);
  1068. PackageManager pm = mContext.getPackageManager();
  1069. return (String[]) method.invoke(pm, packageNames, suspended, 0);
  1070. } catch (Exception e) {
  1071. printError(e);
  1072. }
  1073. return null;
  1074. }*/
  1075. /**
  1076. * 杀死应用
  1077. *
  1078. * @param packageName
  1079. */
  1080. public void forceStopPackage(String packageName) {
  1081. try {
  1082. Method method = ActivityManager.class.getMethod("forceStopPackage", String.class);
  1083. ActivityManager am = (ActivityManager) mContext.getSystemService(Service.ACTIVITY_SERVICE);
  1084. method.invoke(am, packageName);
  1085. } catch (Exception e) {
  1086. printError(e);
  1087. }
  1088. }
  1089. /**
  1090. * 清除应用数据
  1091. *
  1092. * @param packageName
  1093. * @return
  1094. */
  1095. public boolean clearApplicationData(String packageName) {
  1096. boolean isSuccess = false;
  1097. IPackageDataObserver.Stub mStub = new IPackageDataObserver.Stub() {
  1098. public void onRemoveCompleted(String paramAnonymousString, boolean paramAnonymousBoolean) {
  1099. }
  1100. };
  1101. try {
  1102. Method method = ActivityManager.class.getMethod("clearApplicationUserData", String.class, IPackageDataObserver.class);
  1103. ActivityManager am = (ActivityManager) mContext.getSystemService(Service.ACTIVITY_SERVICE);
  1104. isSuccess = (boolean) method.invoke(am, packageName, mStub);
  1105. } catch (Exception e) {
  1106. printError(e);
  1107. }
  1108. return isSuccess;
  1109. }
  1110. /**
  1111. * 清除应用缓存
  1112. *
  1113. * @param packageName
  1114. */
  1115. public void clearApplicationCache(String packageName) {
  1116. IPackageDataObserver.Stub mStub = new IPackageDataObserver.Stub() {
  1117. public void onRemoveCompleted(String paramAnonymousString, boolean paramAnonymousBoolean) {
  1118. }
  1119. };
  1120. try {
  1121. Method method = PackageManager.class.getMethod("deleteApplicationCacheFiles", String.class, IPackageDataObserver.class);
  1122. PackageManager pm = mContext.getPackageManager();
  1123. method.invoke(pm, packageName, mStub);
  1124. } catch (Exception e) {
  1125. printError(e);
  1126. }
  1127. }
  1128. /**
  1129. * 安装应用
  1130. *
  1131. * @param path
  1132. */
  1133. public void installPackage(final String path, final OnPackageInstallListener listener) {
  1134. // Toast.makeText(mContext, "path="+ path, Toast.LENGTH_SHORT).show();
  1135. if (Build.VERSION.SDK_INT < 28) {
  1136. IPackageInstallObserver.Stub mStub = new IPackageInstallObserver.Stub() {
  1137. @Override
  1138. public void packageInstalled(String packageName, int returnCode) throws RemoteException {
  1139. if (listener != null)
  1140. listener.onPackageInstalled(packageName, returnCode == INSTALL_SUCCEEDED ? STATUS_SUCCESS : STATUS_FAILURE);
  1141. }
  1142. };
  1143. try {
  1144. Method method = PackageManager.class.getMethod("installPackage", Uri.class, IPackageInstallObserver.class, int.class, String.class);
  1145. PackageManager pm = mContext.getPackageManager();
  1146. Uri uri = Uri.fromFile(new File(path));
  1147. method.invoke(pm, uri, mStub, INSTALL_REPLACE_EXISTING, null);
  1148. } catch (Exception e) {
  1149. printError(e);
  1150. if (listener != null) {
  1151. listener.onPackageInstalled(null, STATUS_FAILURE);
  1152. }
  1153. }
  1154. } else {
  1155. installPackageFromQ(path, listener);
  1156. }
  1157. }
  1158. public int installExistingPackage(String packageName) {
  1159. try {
  1160. Method method = PackageManager.class.getMethod("installExistingPackage", String.class);
  1161. PackageManager pm = mContext.getPackageManager();
  1162. return (int) method.invoke(pm, packageName);
  1163. } catch (Exception e) {
  1164. printError(e);
  1165. }
  1166. return -1;
  1167. }
  1168. /**
  1169. * 安装应用
  1170. *
  1171. * @param path
  1172. */
  1173. public void installPackage(String path) {
  1174. installPackage(path, null);
  1175. }
  1176. public boolean launchApplication(String packageName) {
  1177. try {
  1178. Intent intent = mContext.getPackageManager().getLaunchIntentForPackage(packageName);
  1179. if (intent != null) {
  1180. intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
  1181. mContext.startActivity(intent);
  1182. return true;
  1183. }
  1184. } catch (Exception e) {
  1185. e.printStackTrace();
  1186. }
  1187. return false;
  1188. }
  1189. /**
  1190. * 卸载应用
  1191. *
  1192. * @param packageName
  1193. */
  1194. public void deletePackage(String packageName, boolean isDeleteSystemApp, final OnPackageDeleteListener listener) {
  1195. IPackageDeleteObserver.Stub mStub = new IPackageDeleteObserver.Stub() {
  1196. @Override
  1197. public void packageDeleted(String packageName, int returnCode) throws RemoteException {
  1198. if (listener != null) {
  1199. listener.onPackageDeleted(packageName, returnCode == DELETE_SUCCEEDED ? STATUS_SUCCESS : STATUS_FAILURE);
  1200. }
  1201. }
  1202. };
  1203. try {
  1204. Method method = PackageManager.class.getMethod("deletePackage", String.class, IPackageDeleteObserver.class, int.class);
  1205. PackageManager pm = mContext.getPackageManager();
  1206. method.invoke(pm, packageName, mStub, isDeleteSystemApp ? DELETE_SYSTEM_APP : 0);
  1207. } catch (Exception e) {
  1208. printError(e);
  1209. }
  1210. }
  1211. /**
  1212. * 卸载应用
  1213. *
  1214. * @param packageName
  1215. */
  1216. public void deletePackage(String packageName, final OnPackageDeleteListener listener) {
  1217. deletePackage(packageName, false, listener);
  1218. }
  1219. /**
  1220. * 卸载应用
  1221. *
  1222. * @param packageName
  1223. */
  1224. public void deletePackage(String packageName) {
  1225. deletePackage(packageName, null);
  1226. }
  1227. /**
  1228. * 卸载应用
  1229. *
  1230. * @param packageName
  1231. */
  1232. public void deletePackage(String packageName, boolean isDeleteSystemApp) {
  1233. deletePackage(packageName, isDeleteSystemApp, null);
  1234. }
  1235. /**
  1236. * 重启
  1237. */
  1238. public void reboot() {
  1239. PowerManager pm = (PowerManager) mContext.getSystemService(Service.POWER_SERVICE);
  1240. try {
  1241. pm.reboot("");
  1242. } catch (Exception e) {
  1243. printError(e);
  1244. }
  1245. }
  1246. /**
  1247. * 关机
  1248. */
  1249. public void shutdown() {
  1250. try {
  1251. Method method = PowerManager.class.getMethod("shutdown", boolean.class, String.class, boolean.class);
  1252. PowerManager pm = (PowerManager) mContext.getSystemService(Service.POWER_SERVICE);
  1253. method.invoke(pm, false, "", false);
  1254. } catch (Exception e) {
  1255. printError(e);
  1256. }
  1257. }
  1258. /**
  1259. * 恢复出厂设置
  1260. */
  1261. public void wipeData() {
  1262. if (Build.VERSION.SDK_INT >= 26) {
  1263. //8.0以上
  1264. Intent intent = new Intent(ACTION_FACTORY_RESET);
  1265. intent.setPackage("android");
  1266. intent.addFlags(Intent.FLAG_RECEIVER_FOREGROUND);
  1267. intent.putExtra(EXTRA_REASON, "MasterClearConfirm");
  1268. intent.putExtra(EXTRA_WIPE_EXTERNAL_STORAGE, true);
  1269. mContext.sendBroadcast(intent);
  1270. } else {
  1271. Intent intent = new Intent(ACTION_MASTER_CLEAR);
  1272. intent.addFlags(Intent.FLAG_RECEIVER_FOREGROUND);
  1273. intent.putExtra(EXTRA_REASON, "MasterClearConfirm");
  1274. intent.putExtra(EXTRA_WIPE_EXTERNAL_STORAGE, true);
  1275. mContext.sendBroadcast(intent);
  1276. }
  1277. // try {
  1278. // RecoverySystem.rebootWipeUserData(mContext);
  1279. // } catch (IOException e) {
  1280. // e.printStackTrace();
  1281. // }
  1282. }
  1283. /**
  1284. * 设置系统时间
  1285. *
  1286. * @param time
  1287. */
  1288. public void setSystemTime(long time) {
  1289. try {
  1290. AlarmManager am = (AlarmManager) mContext.getSystemService(Service.ALARM_SERVICE);
  1291. am.setTime(time);
  1292. } catch (Throwable e) {
  1293. printError(e);
  1294. }
  1295. }
  1296. /**
  1297. * 执行shell命令
  1298. *
  1299. * @param command
  1300. */
  1301. public void execSync(String command) {
  1302. Process process = null;
  1303. try {
  1304. process = Runtime.getRuntime().exec(command);
  1305. process.waitFor();
  1306. } catch (Exception e) {
  1307. e.printStackTrace();
  1308. } finally {
  1309. try {
  1310. if (process != null) {
  1311. process.destroy();
  1312. }
  1313. } catch (Exception e) {
  1314. e.printStackTrace();
  1315. }
  1316. }
  1317. }
  1318. /**
  1319. * 执行shell命令
  1320. *
  1321. * @param command
  1322. */
  1323. public void exec(final String command) {
  1324. new Thread() {
  1325. @Override
  1326. public void run() {
  1327. super.run();
  1328. execSync(command);
  1329. }
  1330. }.start();
  1331. }
  1332. /**
  1333. * 设置主线程处理
  1334. *
  1335. * @param mHandler
  1336. */
  1337. public void setUiHandler(Handler mHandler) {
  1338. this.mHandler = mHandler;
  1339. }
  1340. /**
  1341. * 禁止状态栏展开
  1342. *
  1343. * @param disable
  1344. */
  1345. public void disableStatusBarExpand(boolean disable) {
  1346. try {
  1347. @SuppressLint("WrongConstant") Object service = mContext.getSystemService("statusbar");
  1348. Class<?> c = Class.forName("android.app.StatusBarManager");
  1349. Method method = c.getMethod("disable2", int.class);
  1350. method.invoke(service, disable ? DISABLE2_MASK : 0);
  1351. } catch (Exception e) {
  1352. printError(e);
  1353. }
  1354. }
  1355. /**
  1356. * 禁止系统界面
  1357. *
  1358. * @param statusbar
  1359. * @param notificationBar
  1360. * @param home
  1361. * @param back
  1362. * @param recent
  1363. */
  1364. public void disableSystemUI(boolean statusbar, boolean notificationBar, boolean home, boolean back, boolean recent) {
  1365. int value = 0;
  1366. if (statusbar) value |= 0x00010000;
  1367. if (notificationBar) value |= (0x00020000 | 0x00040000 | 0x00080000);
  1368. if (home) value |= 0x00200000;
  1369. if (back) value |= 0x00400000;
  1370. if (recent) value |= 0x01000000;
  1371. disableSystemUI(value);
  1372. }
  1373. public void disableSystemUI(int state) {
  1374. try {
  1375. @SuppressLint("WrongConstant") Object service = mContext.getSystemService("statusbar");
  1376. Class<?> c = Class.forName("android.app.StatusBarManager");
  1377. Method method = c.getMethod("disable", int.class);
  1378. method.invoke(service, state);
  1379. } catch (Exception e) {
  1380. printError(e);
  1381. }
  1382. }
  1383. public void disableSystemUIEx(int state) {
  1384. try {
  1385. @SuppressLint("WrongConstant") Object service = mContext.getSystemService("statusbar");
  1386. Class<?> c = Class.forName("android.app.StatusBarManager");
  1387. Method method = c.getMethod("disable2", int.class);
  1388. method.invoke(service, state);
  1389. } catch (Exception e) {
  1390. printError(e);
  1391. }
  1392. }
  1393. /**
  1394. * 设置usb功能
  1395. *
  1396. * @param function
  1397. */
  1398. public void setUsbFunction(String function) {
  1399. UsbManager um = (UsbManager) mContext.getSystemService(Service.USB_SERVICE);
  1400. if (Build.VERSION.SDK_INT < 26) {
  1401. //8.0以下
  1402. try {
  1403. Method setCurrentFunction = um.getClass().getMethod("setCurrentFunction", String.class);
  1404. setCurrentFunction.invoke(um, function);
  1405. Method setUsbDataUnlocked = um.getClass().getMethod("setUsbDataUnlocked", boolean.class);
  1406. if (function != null && function.equals("none")) {
  1407. setUsbDataUnlocked.invoke(um, false);
  1408. } else {
  1409. setUsbDataUnlocked.invoke(um, true);
  1410. }
  1411. } catch (Exception e) {
  1412. printError(e);
  1413. }
  1414. } else {
  1415. //8.0以上
  1416. try {
  1417. Method setCurrentFunction = um.getClass().getMethod("setCurrentFunction", String.class, boolean.class);
  1418. if (function != null && function.equals("none")) {
  1419. setCurrentFunction.invoke(um, function, false);
  1420. } else {
  1421. setCurrentFunction.invoke(um, function, true);
  1422. }
  1423. } catch (Exception e) {
  1424. printError(e);
  1425. }
  1426. }
  1427. }
  1428. /**
  1429. * 设置用户限制
  1430. *
  1431. * @param key
  1432. * @param value
  1433. */
  1434. public void setUserRestriction(String key, boolean value) {
  1435. UserManager um = (UserManager) mContext.getSystemService(Service.USER_SERVICE);
  1436. try {
  1437. Method method = um.getClass().getMethod("setUserRestriction", String.class, boolean.class);
  1438. method.invoke(um, key, value);
  1439. } catch (Exception e) {
  1440. printError(e);
  1441. }
  1442. }
  1443. /**
  1444. * 是否有用户限制
  1445. *
  1446. * @param key
  1447. * @return
  1448. */
  1449. public boolean hasUserRestriction(String key) {
  1450. UserManager um = (UserManager) mContext.getSystemService(Service.USER_SERVICE);
  1451. if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
  1452. try {
  1453. return um.hasUserRestriction(key);
  1454. } catch (Exception e) {
  1455. printError(e);
  1456. }
  1457. }
  1458. return false;
  1459. }
  1460. /**
  1461. * 权限转OP代码
  1462. *
  1463. * @param permission
  1464. * @return
  1465. */
  1466. public int permissionToOpCode(String permission) {
  1467. AppOpsManager manager = (AppOpsManager) mContext.getSystemService(Service.APP_OPS_SERVICE);
  1468. try {
  1469. Method method = manager.getClass().getMethod("permissionToOpCode", String.class);
  1470. return (int) method.invoke(manager, permission);
  1471. } catch (Exception e) {
  1472. printError(e);
  1473. }
  1474. return -1;
  1475. }
  1476. /**
  1477. * 禁止卸载应用
  1478. *
  1479. * @param packageName
  1480. * @param block
  1481. * @return
  1482. */
  1483. public boolean setBlockUninstall(String packageName, boolean block) {
  1484. Object mPm = getIPackageManager();
  1485. if (mPm == null) return false;
  1486. try {
  1487. Method method = mPm.getClass().getMethod("setBlockUninstallForUser", String.class, boolean.class, int.class);
  1488. return (boolean) method.invoke(mPm, packageName, block, 0);
  1489. } catch (Exception e) {
  1490. printError(e);
  1491. }
  1492. return false;
  1493. }
  1494. /**
  1495. * 是否禁止卸载应用
  1496. *
  1497. * @param packageName
  1498. * @return
  1499. */
  1500. public boolean isUninstallBlocked(String packageName) {
  1501. Object mPm = getIPackageManager();
  1502. if (mPm == null) return false;
  1503. try {
  1504. Method method = mPm.getClass().getMethod("getBlockUninstallForUser", String.class, int.class);
  1505. return (boolean) method.invoke(mPm, packageName, 0);
  1506. } catch (Exception e) {
  1507. printError(e);
  1508. }
  1509. return false;
  1510. }
  1511. /**
  1512. * 设置默认桌面
  1513. *
  1514. * @param launcher
  1515. */
  1516. public void setHomeLauncher(ComponentName launcher) {
  1517. Object mPm = getIPackageManager();
  1518. if (mPm == null) return;
  1519. try {
  1520. Method method = mPm.getClass().getMethod("setHomeActivity", ComponentName.class, int.class);
  1521. method.invoke(mPm, launcher, 0);
  1522. } catch (Exception e) {
  1523. printError(e);
  1524. }
  1525. }
  1526. /**
  1527. * 设置默认桌面
  1528. *
  1529. * @param packageName
  1530. * @param className
  1531. */
  1532. public void setHomeLauncher(String packageName, String className) {
  1533. setHomeLauncher(new ComponentName(packageName, className));
  1534. }
  1535. /**
  1536. * 设置默认桌面
  1537. *
  1538. * @param packageName
  1539. */
  1540. public boolean setHomeLauncher(String packageName) {
  1541. if (packageName == null) return false;
  1542. List<ComponentName> launchers = new ArrayList<>();
  1543. getHomeLauncherList(launchers);
  1544. for (ComponentName launcher : launchers) {
  1545. if (launcher.getPackageName().equals(packageName)) {
  1546. setHomeLauncher(launcher);
  1547. return true;
  1548. }
  1549. }
  1550. return false;
  1551. }
  1552. /**
  1553. * 获取默认桌面
  1554. *
  1555. * @return
  1556. */
  1557. public ComponentName getHomeLauncher() {
  1558. List<ComponentName> mList = new ArrayList<>();
  1559. return getHomeLauncherList(mList);
  1560. }
  1561. /**
  1562. * 获取默认桌面包名
  1563. *
  1564. * @return
  1565. */
  1566. public String getHomeLauncherPackage() {
  1567. ComponentName launcher = getHomeLauncher();
  1568. return launcher != null ? launcher.getPackageName() : null;
  1569. }
  1570. /**
  1571. * 清除默认桌面
  1572. */
  1573. public void clearHomeLauncher() {
  1574. ComponentName launcher = getHomeLauncher();
  1575. if (launcher != null) {
  1576. try {
  1577. mContext.getPackageManager().clearPackagePreferredActivities(launcher.getPackageName());
  1578. } catch (Exception e) {
  1579. printError(e);
  1580. }
  1581. }
  1582. }
  1583. /**
  1584. * 获取桌面列表,返回默认桌面
  1585. *
  1586. * @param launchers
  1587. * @return
  1588. */
  1589. public ComponentName getHomeLauncherList(List<ComponentName> launchers) {
  1590. if (launchers == null) return null;
  1591. try {
  1592. PackageManager pm = mContext.getPackageManager();
  1593. Method method = pm.getClass().getMethod("getHomeActivities", List.class);
  1594. List<ResolveInfo> resolveInfos = new ArrayList<>();
  1595. ComponentName defaultLauncher = (ComponentName) method.invoke(pm, resolveInfos);
  1596. for (ResolveInfo resolveInfo : resolveInfos) {
  1597. if (resolveInfo.activityInfo != null
  1598. && hasValue(resolveInfo.activityInfo.packageName)
  1599. && hasValue(resolveInfo.activityInfo.name)) {
  1600. launchers.add(new ComponentName(resolveInfo.activityInfo.packageName, resolveInfo.activityInfo.name));
  1601. }
  1602. }
  1603. return defaultLauncher;
  1604. } catch (Exception e) {
  1605. printError(e);
  1606. }
  1607. return null;
  1608. }
  1609. /**
  1610. * 禁用sim卡
  1611. */
  1612. public void disableMobileRadios() {
  1613. IInterface mIPhone = getAIDLService("phone", "com.android.internal.telephony.ITelephony");
  1614. try {
  1615. Method method = mIPhone.getClass().getMethod("shutdownMobileRadios");
  1616. method.invoke(mIPhone);
  1617. } catch (Exception e) {
  1618. e.printStackTrace();
  1619. }
  1620. }
  1621. /**
  1622. * 设置电源保护模式
  1623. *
  1624. * @param mode
  1625. * @return
  1626. */
  1627. public boolean setPowerSaveMode(int mode) {
  1628. try {
  1629. IInterface mIPowerManagerEx = getAIDLService("power_ex", "android.os.IPowerManagerEx");
  1630. Method setPowerSaveMode = mIPowerManagerEx.getClass().getMethod("setPowerSaveMode", int.class);
  1631. return (boolean) setPowerSaveMode.invoke(mIPowerManagerEx, mode);
  1632. } catch (Exception e) {
  1633. printError(e);
  1634. }
  1635. return false;
  1636. }
  1637. /**
  1638. * 添加电源优化白名单
  1639. *
  1640. * @param packageName
  1641. */
  1642. public void addPowerSaveWhiteApp(String packageName) {
  1643. IInterface mIDeviceIdleController = getAIDLService("deviceidle", "android.os.IDeviceIdleController");
  1644. if (mIDeviceIdleController != null) {
  1645. try {
  1646. Method method = mIDeviceIdleController.getClass().getMethod("addPowerSaveWhitelistApp", String.class);
  1647. method.invoke(mIDeviceIdleController, packageName);
  1648. } catch (Exception e) {
  1649. printError(e);
  1650. }
  1651. }
  1652. }
  1653. /**
  1654. * 移除电源优化白名单
  1655. *
  1656. * @param packageName
  1657. */
  1658. public void removePowerSaveWhiteApp(String packageName) {
  1659. IInterface mIDeviceIdleController = getAIDLService("deviceidle", "android.os.IDeviceIdleController");
  1660. if (mIDeviceIdleController != null) {
  1661. try {
  1662. Method method = mIDeviceIdleController.getClass().getMethod("removePowerSaveWhitelistApp", String.class);
  1663. method.invoke(mIDeviceIdleController, packageName);
  1664. } catch (Exception e) {
  1665. printError(e);
  1666. }
  1667. }
  1668. }
  1669. /**
  1670. * 是否电源优化白名单
  1671. *
  1672. * @param packageName
  1673. * @return
  1674. */
  1675. public boolean isPowerSaveWhiteApp(String packageName) {
  1676. IInterface mIDeviceIdleController = getAIDLService("deviceidle", "android.os.IDeviceIdleController");
  1677. if (mIDeviceIdleController != null) {
  1678. try {
  1679. Method method = mIDeviceIdleController.getClass().getMethod("isPowerSaveWhitelistApp", String.class);
  1680. return (boolean) method.invoke(mIDeviceIdleController, packageName);
  1681. } catch (Exception e) {
  1682. e.printStackTrace();
  1683. }
  1684. }
  1685. return false;
  1686. }
  1687. /**
  1688. * 挂载外部存储
  1689. */
  1690. public void mountExternalStorage() {
  1691. StorageManager sm = (StorageManager) mContext.getSystemService(Service.STORAGE_SERVICE);
  1692. if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
  1693. List<StorageVolume> volumes = sm.getStorageVolumes();
  1694. if (volumes != null) {
  1695. for (StorageVolume volume : volumes) {
  1696. try {
  1697. if (!volume.isPrimary()) {
  1698. String volumeId = (String) volume.getClass().getMethod("getId").invoke(volume);
  1699. sm.getClass().getMethod("mount", String.class).invoke(sm, volumeId);
  1700. }
  1701. //print("挂载外部存储成功");
  1702. } catch (Exception e) {
  1703. e.printStackTrace();
  1704. printError(e);
  1705. //print("挂载外部存储失败");
  1706. }
  1707. }
  1708. }
  1709. }
  1710. }
  1711. /**
  1712. * 卸载外部存储
  1713. */
  1714. public void unmountExternalStorage() {
  1715. StorageManager sm = (StorageManager) mContext.getSystemService(Service.STORAGE_SERVICE);
  1716. if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
  1717. List<StorageVolume> volumes = sm.getStorageVolumes();
  1718. if (volumes != null) {
  1719. for (StorageVolume volume : volumes) {
  1720. try {
  1721. if (!volume.isPrimary()) {
  1722. String volumeId = (String) volume.getClass().getMethod("getId").invoke(volume);
  1723. sm.getClass().getMethod("unmount", String.class).invoke(sm, volumeId);
  1724. }
  1725. //print("卸载外部存储成功");
  1726. } catch (Exception e) {
  1727. e.printStackTrace();
  1728. printError(e);
  1729. //print("卸载外部存储失败");
  1730. }
  1731. }
  1732. }
  1733. }
  1734. }
  1735. /**
  1736. * 截屏
  1737. *
  1738. * @return
  1739. */
  1740. public Bitmap screenshot() {
  1741. WindowManager wm = (WindowManager) mContext.getSystemService(Context.WINDOW_SERVICE);
  1742. if (Build.VERSION.SDK_INT >= 31) {
  1743. //android 12
  1744. VirtualDisplay virtualDisplay = null;
  1745. ImageReader reader = null;
  1746. Image image = null;
  1747. try {
  1748. DisplayMetrics metrics = new DisplayMetrics();
  1749. wm.getDefaultDisplay().getRealMetrics(metrics);
  1750. DisplayManager dm = (DisplayManager) mContext.getSystemService(Service.DISPLAY_SERVICE);
  1751. reader = ImageReader.newInstance(metrics.widthPixels, metrics.heightPixels, PixelFormat.RGBA_8888, 1);
  1752. virtualDisplay = dm.createVirtualDisplay("launcher3_screen", metrics.widthPixels, metrics.heightPixels, metrics.densityDpi, reader.getSurface(),
  1753. DisplayManager.VIRTUAL_DISPLAY_FLAG_AUTO_MIRROR);
  1754. int count = 0;
  1755. while (image == null) {
  1756. Thread.sleep(50);
  1757. image = reader.acquireLatestImage();
  1758. if (++count > 10) {
  1759. break;
  1760. }
  1761. }
  1762. if (image != null) {
  1763. int width = image.getWidth();
  1764. int height = image.getHeight();
  1765. final Image.Plane[] planes = image.getPlanes();
  1766. final ByteBuffer buffer = planes[0].getBuffer();
  1767. int pixelStride = planes[0].getPixelStride();
  1768. int rowStride = planes[0].getRowStride();
  1769. int rowPadding = rowStride - pixelStride * width;
  1770. Bitmap bitmap = Bitmap.createBitmap(width + rowPadding / pixelStride, height, Bitmap.Config.ARGB_8888);
  1771. bitmap.copyPixelsFromBuffer(buffer);
  1772. return bitmap;
  1773. }
  1774. } catch (Throwable e) {
  1775. printError("screenshot", e);
  1776. } finally {
  1777. try {
  1778. if (image != null) {
  1779. image.close();
  1780. }
  1781. } catch (Exception e2) {
  1782. e2.printStackTrace();
  1783. }
  1784. try {
  1785. if (virtualDisplay != null) {
  1786. virtualDisplay.release();
  1787. }
  1788. } catch (Exception e2) {
  1789. e2.printStackTrace();
  1790. }
  1791. try {
  1792. if (reader != null) {
  1793. reader.close();
  1794. }
  1795. } catch (Exception e2) {
  1796. e2.printStackTrace();
  1797. }
  1798. }
  1799. } else {
  1800. try {
  1801. Class c = Class.forName("android.view.SurfaceControl");
  1802. // if (Build.VERSION.SDK_INT >= 31) {
  1803. // /*Class CDisplayCaptureArgs = Class.forName("android.view.SurfaceControl$DisplayCaptureArgs");
  1804. // Method method = c.getDeclaredMethod("captureDisplay", CDisplayCaptureArgs);
  1805. // method.setAccessible(true);
  1806. // Object mScreenshotHardwareBuffer = method.invoke(c, null);
  1807. // Log.i(TAG, "screenshot" + (mScreenshotHardwareBuffer == null));*/
  1808. // } else {
  1809. //
  1810. // }
  1811. Method method = c.getMethod("screenshot", Rect.class, int.class, int.class, int.class);
  1812. return (Bitmap) method.invoke(c, new Rect(), 0, 0, wm.getDefaultDisplay().getRotation());
  1813. } catch (Exception e) {
  1814. printError("screenshot", e);
  1815. }
  1816. }
  1817. return null;
  1818. }
  1819. public Bitmap screenshotHw() {
  1820. WindowManager wm = (WindowManager) mContext.getSystemService(Context.WINDOW_SERVICE);
  1821. Class c = null;
  1822. try {
  1823. c = Class.forName("android.view.SurfaceControl");
  1824. Method method = c.getMethod("screenshot_ext_hw", Rect.class, int.class, int.class, int.class);
  1825. return (Bitmap) method.invoke(c, new Rect(0, 0, 2000, 1200), 2000, 1200, wm.getDefaultDisplay().getRotation());
  1826. } catch (Throwable e) {
  1827. printError(e);
  1828. }
  1829. return null;
  1830. }
  1831. public Bitmap screenshot(int minLayer, int maxLayer) {
  1832. WindowManager wm = (WindowManager) mContext.getSystemService(Context.WINDOW_SERVICE);
  1833. try {
  1834. Class c = Class.forName("android.view.SurfaceControl");
  1835. Method method = c.getMethod("screenshot", Rect.class, int.class, int.class, int.class, int.class, boolean.class, int.class);
  1836. return (Bitmap) method.invoke(c, new Rect(), 0, 0, minLayer, maxLayer, true, wm.getDefaultDisplay().getRotation());
  1837. } catch (Exception e) {
  1838. printError(e);
  1839. }
  1840. return null;
  1841. }
  1842. /**
  1843. * 设置防火墙模式
  1844. *
  1845. * @param isWhiteMode
  1846. */
  1847. public void setFirewallMode(boolean isWhiteMode) {
  1848. IInterface mINetworkManagementService = getNetworkManagement();
  1849. if (mINetworkManagementService != null) {
  1850. for (int i = 0; i <= 3; i++) {
  1851. try {
  1852. Method setFirewallChainEnabled = mINetworkManagementService.getClass().getDeclaredMethod("setFirewallChainEnabled", int.class, boolean.class);
  1853. setFirewallChainEnabled.invoke(mINetworkManagementService, i, isWhiteMode);
  1854. } catch (Exception e) {
  1855. printError(e);
  1856. }
  1857. }
  1858. }
  1859. }
  1860. /**
  1861. * 设置防火墙规则
  1862. *
  1863. * @param packageName
  1864. * @param allow
  1865. */
  1866. public void setFirewallPackageRule(String packageName, boolean allow) {
  1867. int uid = getPackageUid(packageName);
  1868. if (uid <= 0) return;
  1869. IInterface mINetworkManagementService = getNetworkManagement();
  1870. if (mINetworkManagementService != null) {
  1871. for (int i = 0; i <= 3; i++) {
  1872. try {
  1873. Method method = mINetworkManagementService.getClass().getDeclaredMethod("setFirewallUidRule", int.class, int.class, int.class);
  1874. method.invoke(mINetworkManagementService, i, uid, allow ? FIREWALL_RULE_ALLOW : FIREWALL_RULE_DENY);
  1875. } catch (Exception e) {
  1876. printError("setFirewallPackageRule", e);
  1877. }
  1878. }
  1879. }
  1880. }
  1881. /**
  1882. * 设置防火墙规则 <=android9.0
  1883. *
  1884. * @param packageNames
  1885. * @param allow
  1886. */
  1887. public void setFirewallPackageRules(List<String> packageNames, boolean allow) {
  1888. if (packageNames == null || packageNames.isEmpty()) return;
  1889. int size = packageNames.size();
  1890. int[] uids = new int[size];
  1891. int[] rules = new int[size];
  1892. int allowValue = allow ? FIREWALL_RULE_ALLOW : FIREWALL_RULE_DENY;
  1893. for (int i = 0; i < size; i++) {
  1894. uids[i] = getPackageUid(packageNames.get(i));
  1895. rules[i] = allowValue;
  1896. print(uids[i], rules[i]);
  1897. }
  1898. IInterface mINetworkManagementService = getNetworkManagement();
  1899. if (mINetworkManagementService != null) {
  1900. for (int i = 0; i <= 3; i++) {
  1901. try {
  1902. Method method = mINetworkManagementService.getClass().getDeclaredMethod("setFirewallUidRules", int.class, int[].class, int[].class);
  1903. method.invoke(mINetworkManagementService, i, uids, rules);
  1904. } catch (Exception e) {
  1905. e.printStackTrace();
  1906. print("setFirewallPackageRules", e);
  1907. }
  1908. }
  1909. }
  1910. }
  1911. /**
  1912. * 设置防火墙状态
  1913. *
  1914. * @param enabled
  1915. */
  1916. public void setFirewallEnabled(boolean enabled) {
  1917. IInterface mINetworkManagementService = getNetworkManagement();
  1918. if (mINetworkManagementService != null) {
  1919. try {
  1920. Method setFirewallEnabled = mINetworkManagementService.getClass().getDeclaredMethod("setFirewallEnabled", boolean.class);
  1921. setFirewallEnabled.invoke(mINetworkManagementService, enabled);
  1922. } catch (Exception e) {
  1923. printError(e);
  1924. }
  1925. }
  1926. }
  1927. /**
  1928. * 防火墙是否开启
  1929. *
  1930. * @return
  1931. */
  1932. public boolean isFirewallEnabled() {
  1933. IInterface mINetworkManagementService = getNetworkManagement();
  1934. if (mINetworkManagementService != null) {
  1935. try {
  1936. Method isFirewallEnabled = mINetworkManagementService.getClass().getDeclaredMethod("isFirewallEnabled");
  1937. return (boolean) isFirewallEnabled.invoke(mINetworkManagementService);
  1938. } catch (Exception e) {
  1939. printError(e);
  1940. }
  1941. }
  1942. return false;
  1943. }
  1944. /**
  1945. * 设置ip转发是否可用
  1946. *
  1947. * @param enabled
  1948. */
  1949. public void setIpForwardingEnabled(boolean enabled) {
  1950. IInterface mINetworkManagementService = getNetworkManagement();
  1951. if (mINetworkManagementService != null) {
  1952. try {
  1953. Method setIpForwardingEnabled = mINetworkManagementService.getClass().getDeclaredMethod("setIpForwardingEnabled", boolean.class);
  1954. setIpForwardingEnabled.invoke(mINetworkManagementService, enabled);
  1955. } catch (Exception e) {
  1956. printError(e);
  1957. }
  1958. }
  1959. }
  1960. /**
  1961. * ip转发是否能用
  1962. *
  1963. * @return
  1964. */
  1965. public boolean isIpForwardingEnabled() {
  1966. IInterface mINetworkManagementService = getNetworkManagement();
  1967. if (mINetworkManagementService != null) {
  1968. try {
  1969. Method getIpForwardingEnabled = mINetworkManagementService.getClass().getDeclaredMethod("getIpForwardingEnabled");
  1970. return (boolean) getIpForwardingEnabled.invoke(mINetworkManagementService);
  1971. } catch (Exception e) {
  1972. printError(e);
  1973. }
  1974. }
  1975. return false;
  1976. }
  1977. /**
  1978. * 设置锁屏是否禁用
  1979. */
  1980. public void setLockScreenDisabled(boolean disabled) {
  1981. Class c = null;
  1982. try {
  1983. c = Class.forName("com.android.internal.widget.LockPatternUtils");
  1984. Method method = c.getDeclaredMethod("setLockScreenDisabled", boolean.class, int.class);
  1985. method.setAccessible(true);
  1986. method.invoke(newInstance(c, new Class[]{Context.class}, mContext), disabled, 0);
  1987. } catch (Exception e) {
  1988. e.printStackTrace();
  1989. }
  1990. }
  1991. /*
  1992. * 内部数据
  1993. *
  1994. */
  1995. private static boolean hasElement(Collection c) {
  1996. return c != null && !c.isEmpty();
  1997. }
  1998. private static boolean hasElement(Object[] array) {
  1999. return array != null && array.length > 0;
  2000. }
  2001. private static boolean hasElement(Map map) {
  2002. return map != null && !map.isEmpty();
  2003. }
  2004. private static boolean hasValue(String value) {
  2005. return value != null && !value.isEmpty();
  2006. }
  2007. private static boolean isEmpty(String value) {
  2008. return !hasValue(value);
  2009. }
  2010. private static boolean isNumeric(String str) {
  2011. Pattern pattern = Pattern.compile("[0-9]*");
  2012. return pattern.matcher(str).matches();
  2013. }
  2014. private static boolean equalsValue(String v1, String v2) {
  2015. return v1 != null && v2 != null && v1.equals(v2);
  2016. }
  2017. private SystemApi setOpState(String packageName, int opCode, boolean isAllow) {
  2018. if (isAllow) {
  2019. setOpMode(packageName, opCode, AppOpsManager.MODE_ALLOWED);
  2020. } else {
  2021. setOpMode(packageName, opCode, AppOpsManager.MODE_IGNORED);
  2022. }
  2023. return this;
  2024. }
  2025. public boolean grantRuntimePermission(String packageName, String permission) {
  2026. try {
  2027. Method method = PackageManager.class.getMethod("grantRuntimePermission", String.class, String.class, UserHandle.class);
  2028. UserHandle userHandle = (UserHandle) newInstance(UserHandle.class, new Class[]{int.class}, 0);
  2029. method.invoke(mContext.getPackageManager(), packageName, permission, userHandle);
  2030. return true;
  2031. } catch (Exception e) {
  2032. printError(e);
  2033. }
  2034. return false;
  2035. }
  2036. public void revokeRuntimePermission(String packageName, String permission) {
  2037. try {
  2038. Method method = PackageManager.class.getMethod("revokeRuntimePermission", String.class, String.class, UserHandle.class);
  2039. UserHandle userHandle = (UserHandle) newInstance(UserHandle.class, new Class[]{int.class}, 0);
  2040. method.invoke(mContext.getPackageManager(), packageName, permission, userHandle);
  2041. } catch (Exception e) {
  2042. printError(e);
  2043. }
  2044. }
  2045. private int getPackageUid(String packageName) {
  2046. try {
  2047. PackageInfo info = mContext.getPackageManager().getPackageInfo(packageName, PackageManager.GET_DISABLED_COMPONENTS);
  2048. if (info != null && info.applicationInfo != null) {
  2049. return info.applicationInfo.uid;
  2050. }
  2051. } catch (Exception e) {
  2052. e.printStackTrace();
  2053. }
  2054. return 0;
  2055. }
  2056. private String makeSettingsValue(String value) {
  2057. return value != null && !value.trim().isEmpty() ? value : "\"\"";
  2058. }
  2059. // public void unlockDevice() {
  2060. // try {
  2061. // IInterface mITurstManager = getAIDLService("trust", "android.app.trust.ITrustManager");
  2062. // Method method= mITurstManager.getClass().getMethod("setDeviceLockedForUser", int.class, boolean.class);
  2063. // method.invoke(mITurstManager, 0, false);
  2064. // } catch (Exception e) {
  2065. // printError("unlockDevice", e);
  2066. // }
  2067. //
  2068. // }
  2069. public interface OnPackageInstallListener {
  2070. void onPackageInstalled(String packageName, int returnCode);
  2071. }
  2072. public interface OnPackageDeleteListener {
  2073. void onPackageDeleted(String packageName, int returnCode);
  2074. }
  2075. private Set<String> getDeniedPermissionList(String packageName, String[] permissions) {
  2076. Set<String> mDeniedPermissionList = new HashSet<>();
  2077. PackageManager pm = mContext.getPackageManager();
  2078. for (String permission : permissions) {
  2079. int pmState = pm.checkPermission(permission, packageName);
  2080. int opMode = getOpMode(packageName, permissionToOpCode(permission));
  2081. boolean hasPermission = pmState == PackageManager.PERMISSION_GRANTED && (opMode == AppOpsManager.MODE_ALLOWED || opMode == AppOpsManager.MODE_DEFAULT);
  2082. if (!hasPermission) {
  2083. mDeniedPermissionList.add(permission);
  2084. }
  2085. }
  2086. return mDeniedPermissionList;
  2087. }
  2088. private Object newInstance(Class clazz, Class[] argsType, Object... args) {
  2089. Object instance = null;
  2090. try {
  2091. Constructor constructor = clazz.getConstructor(argsType);
  2092. constructor.setAccessible(true);
  2093. instance = constructor.newInstance(args);
  2094. } catch (Exception e) {
  2095. printError(e);
  2096. }
  2097. return instance;
  2098. }
  2099. private void print(Object... info) {
  2100. if (mLoggerEnabled || mDebug) {
  2101. if (info == null || info.length == 0) {
  2102. return;
  2103. }
  2104. StringBuilder sb = new StringBuilder();
  2105. for (Object o : info) {
  2106. sb.append(o != null ? o.toString() + ", " : ", ");
  2107. }
  2108. String msg = sb.toString();
  2109. if (msg.endsWith(",")) msg = sb.deleteCharAt(sb.length() - 1).toString();
  2110. Log.i(TAG, msg);
  2111. }
  2112. }
  2113. private void printError(Throwable e) {
  2114. printError(null, e);
  2115. }
  2116. private void printError(String tag, Throwable e) {
  2117. if (mLoggerEnabled || mDebug) {
  2118. if (e.getCause() != null) {
  2119. Log.e(TAG, (tag == null ? "" : tag + " error=") + e.getCause().toString());
  2120. } else {
  2121. Log.e(TAG, (tag == null ? "" : tag + " error=") + e.toString());
  2122. }
  2123. }
  2124. }
  2125. /**
  2126. * android9.0 安装应用
  2127. *
  2128. * @param path
  2129. * @param listener
  2130. */
  2131. private void installPackageFromQ(final String path, final OnPackageInstallListener listener) {
  2132. if (Build.VERSION.SDK_INT < Build.VERSION_CODES.LOLLIPOP) {
  2133. return;
  2134. }
  2135. int mSessionId = -1;
  2136. String packageName = null;
  2137. try {
  2138. PackageManager pm = mContext.getPackageManager();
  2139. PackageInfo packageInfo = pm.getPackageArchiveInfo(path, PackageManager.GET_ACTIVITIES | PackageManager.GET_SERVICES);
  2140. if (packageInfo != null) {
  2141. packageName = packageInfo.packageName;
  2142. }
  2143. PackageInstaller packageInstaller = pm.getPackageInstaller();
  2144. PackageInstaller.SessionParams sessionParams = new PackageInstaller.SessionParams(PackageInstaller.SessionParams.MODE_FULL_INSTALL);
  2145. File apkFile = new File(path);
  2146. print("apkFile length" + apkFile.length());
  2147. sessionParams.setSize(apkFile.length());
  2148. mSessionId = packageInstaller.createSession(sessionParams);
  2149. } catch (Throwable e) {
  2150. printError(e);
  2151. }
  2152. if (mSessionId != -1 && packageName != null) {
  2153. final int finalMSessionId = mSessionId;
  2154. final String finalPackageName = packageName;
  2155. new Thread() {
  2156. @Override
  2157. public void run() {
  2158. super.run();
  2159. boolean copySuccess = onTransfesApkFile(path, finalMSessionId);
  2160. if (copySuccess) {
  2161. if (mHandler != null) {
  2162. mHandler.post(new Runnable() {
  2163. @Override
  2164. public void run() {
  2165. execInstallAPP(finalMSessionId, finalPackageName, listener);
  2166. }
  2167. });
  2168. } else {
  2169. execInstallAPP(finalMSessionId, finalPackageName, listener);
  2170. }
  2171. } else {
  2172. if (mHandler != null) {
  2173. mHandler.post(new Runnable() {
  2174. @Override
  2175. public void run() {
  2176. if (listener != null) {
  2177. listener.onPackageInstalled(finalPackageName, STATUS_FAILURE);
  2178. }
  2179. }
  2180. });
  2181. } else {
  2182. if (listener != null) {
  2183. listener.onPackageInstalled(finalPackageName, STATUS_FAILURE);
  2184. }
  2185. }
  2186. }
  2187. }
  2188. }.start();
  2189. } else {
  2190. if (listener != null) {
  2191. listener.onPackageInstalled(packageName, STATUS_FAILURE);
  2192. }
  2193. }
  2194. }
  2195. private boolean onTransfesApkFile(String apkFilePath, int mSessionId) {
  2196. if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
  2197. InputStream in = null;
  2198. OutputStream out = null;
  2199. PackageInstaller.Session session = null;
  2200. boolean success = false;
  2201. try {
  2202. File apkFile = new File(apkFilePath);
  2203. session = mContext.getPackageManager().getPackageInstaller().openSession(mSessionId);
  2204. out = session.openWrite("base.apk", 0, apkFile.length());
  2205. in = new FileInputStream(apkFile);
  2206. int total = 0, c;
  2207. byte[] buffer = new byte[1024 * 1024];
  2208. while ((c = in.read(buffer)) != -1) {
  2209. total += c;
  2210. out.write(buffer, 0, c);
  2211. }
  2212. session.fsync(out);
  2213. success = true;
  2214. } catch (Throwable e) {
  2215. printError(e);
  2216. } finally {
  2217. if (null != session) {
  2218. session.close();
  2219. }
  2220. try {
  2221. if (null != out) {
  2222. out.close();
  2223. }
  2224. if (null != in) {
  2225. in.close();
  2226. }
  2227. } catch (Exception e) {
  2228. printError(e);
  2229. }
  2230. }
  2231. return success;
  2232. }
  2233. return false;
  2234. }
  2235. /**
  2236. * 执行安装并通知安装结果
  2237. */
  2238. private void execInstallAPP(int mSessionId, final String packageName, final OnPackageInstallListener listener) {
  2239. if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
  2240. PackageInstaller.Session session = null;
  2241. try {
  2242. session = mContext.getPackageManager().getPackageInstaller().openSession(mSessionId);
  2243. Intent intent = new Intent(mContext, new BroadcastReceiver() {
  2244. @Override
  2245. public void onReceive(Context context, Intent intent) {
  2246. if (intent != null) {
  2247. int status = intent.getIntExtra(PackageInstaller.EXTRA_STATUS, PackageInstaller.STATUS_FAILURE);
  2248. if (listener != null) {
  2249. listener.onPackageInstalled(packageName, status);
  2250. }
  2251. }
  2252. }
  2253. }.getClass());
  2254. PendingIntent pendingIntent = PendingIntent.getBroadcast(mContext,
  2255. 1, intent,
  2256. PendingIntent.FLAG_UPDATE_CURRENT);
  2257. session.commit(pendingIntent.getIntentSender());
  2258. } catch (Exception e) {
  2259. printError(e);
  2260. printError(e);
  2261. if (listener != null) {
  2262. listener.onPackageInstalled(packageName, STATUS_FAILURE);
  2263. }
  2264. } finally {
  2265. if (null != session) {
  2266. session.close();
  2267. }
  2268. }
  2269. }
  2270. }
  2271. private ComponentName getDeviceAdminClass(Context context, String pkgName) {
  2272. List<ResolveInfo> infos = context.getPackageManager().queryBroadcastReceivers(
  2273. new Intent(DeviceAdminReceiver.ACTION_DEVICE_ADMIN_ENABLED),
  2274. PackageManager.GET_DISABLED_UNTIL_USED_COMPONENTS);
  2275. if (infos != null) {
  2276. for (ResolveInfo info : infos) {
  2277. if (info.activityInfo.packageName.equals(pkgName)) {
  2278. return new ComponentName(pkgName, info.activityInfo.name);
  2279. }
  2280. }
  2281. }
  2282. return null;
  2283. }
  2284. private boolean isAppInstalled(String pkgName) {
  2285. try {
  2286. PackageInfo info = mContext.getPackageManager().getPackageInfo(pkgName, PackageManager.GET_DISABLED_COMPONENTS);
  2287. return info != null;
  2288. } catch (Exception e) {
  2289. printError(e);
  2290. }
  2291. return false;
  2292. }
  2293. private void fixedPermissionInner(String packageName, String permission) {
  2294. updatePermissionFlags(packageName, permission, FLAG_PERMISSION_SYSTEM_FIXED, FLAG_PERMISSION_SYSTEM_FIXED);
  2295. }
  2296. private void unfixedPermissionInner(String packageName, String permission) {
  2297. updatePermissionFlags(packageName, permission, FLAG_PERMISSION_SYSTEM_FIXED, 0);
  2298. }
  2299. private UserHandle newUserHandler(int id) {
  2300. return (UserHandle) newInstance(UserHandle.class, new Class[]{int.class}, id);
  2301. }
  2302. private Object getIPackageManager() {
  2303. try {
  2304. Class<?> atClass = Class.forName("android.app.ActivityThread");
  2305. Method method = atClass.getDeclaredMethod("getPackageManager");
  2306. return method.invoke(atClass);
  2307. } catch (Exception e) {
  2308. printError(e);
  2309. }
  2310. return null;
  2311. }
  2312. private IInterface getAIDLService(String serverName, String interfaceName) {
  2313. IBinder binder = getService(serverName);
  2314. if (binder != null) {
  2315. return getInterface(interfaceName, binder);
  2316. }
  2317. return null;
  2318. }
  2319. private IBinder getService(String name) {
  2320. try {
  2321. Class ServiceManager = Class.forName("android.os.ServiceManager");
  2322. Method getService = ServiceManager.getMethod("getService", String.class);
  2323. return (IBinder) getService.invoke(ServiceManager, name);
  2324. } catch (Exception e) {
  2325. printError(e);
  2326. }
  2327. return null;
  2328. }
  2329. private IInterface getInterface(String name, IBinder service) {
  2330. try {
  2331. Class<?> mClass = Class.forName(name + "$Stub");
  2332. Method asInterface = mClass.getDeclaredMethod("asInterface", IBinder.class);
  2333. return (IInterface) asInterface.invoke(null, service);
  2334. } catch (Exception e) {
  2335. printError(e);
  2336. }
  2337. return null;
  2338. }
  2339. /**
  2340. * 是否禁止联网 error
  2341. *
  2342. * @param packageName
  2343. * @return
  2344. */
  2345. private boolean isNetworkDisabled(String packageName) {
  2346. int uid = getPackageUid(packageName);
  2347. if (uid <= 0) return false;
  2348. IInterface mINetworkManagementService = getNetworkManagement();
  2349. if (mINetworkManagementService != null) {
  2350. try {
  2351. Method isNetworkRestricted = mINetworkManagementService.getClass().getDeclaredMethod("isNetworkRestricted", int.class);
  2352. return (boolean) isNetworkRestricted.invoke(mINetworkManagementService, uid);
  2353. } catch (Exception e) {
  2354. printError(e);
  2355. }
  2356. }
  2357. return false;
  2358. }
  2359. private IInterface getNetworkManagement() {
  2360. return getAIDLService("network_management", "android.os.INetworkManagementService");
  2361. }
  2362. public void setLoggerEnabled(boolean loggerEnabled) {
  2363. this.mLoggerEnabled = loggerEnabled;
  2364. }
  2365. public static ComponentName parse(String componentName) {
  2366. if (componentName == null || componentName.isEmpty()) return null;
  2367. int pos = componentName.indexOf('/');
  2368. if (pos > 0 && pos < componentName.length() - 1) {
  2369. String packageName = componentName.substring(0, pos).trim();
  2370. String className = componentName.substring(pos + 1).trim();
  2371. if (className.startsWith(".")) {
  2372. className = packageName + className;
  2373. }
  2374. return new ComponentName(packageName, className);
  2375. } else {
  2376. return null;
  2377. }
  2378. }
  2379. public boolean removeTask(int taskId) {
  2380. IInterface mIActivityManager = getAIDLService("activity", "android.app.IActivityManager");
  2381. if (mIActivityManager != null) {
  2382. try {
  2383. Method method = mIActivityManager.getClass().getDeclaredMethod("removeTask", int.class);
  2384. return (boolean) method.invoke(mIActivityManager, taskId);
  2385. } catch (Exception e) {
  2386. e.printStackTrace();
  2387. }
  2388. }
  2389. return false;
  2390. }
  2391. public static String getFactoryMacAddr(Context context) {
  2392. WifiManager manager = (WifiManager) context.getApplicationContext().getSystemService(Service.WIFI_SERVICE);
  2393. try {
  2394. Method getFactoryMacAddresses = manager.getClass().getMethod("getFactoryMacAddresses");
  2395. getFactoryMacAddresses.setAccessible(true);
  2396. String[] macAddrs = (String[]) getFactoryMacAddresses.invoke(manager, null);
  2397. if (macAddrs != null && macAddrs.length > 0) {
  2398. return macAddrs[0].toUpperCase();
  2399. }
  2400. } catch (Throwable e) {
  2401. e.printStackTrace();
  2402. }
  2403. return null;
  2404. }
  2405. }

完整代码:https://github.com/yuanfang235/systemmanagerlib

声明:本文内容由网友自发贡献,转载请注明出处:【wpsshop博客】
推荐阅读
相关标签
  

闽ICP备14008679号