android 接口(2)

11) 網址/IP白名單接口

---------- frameworks/base/core/java/android/provider/Settings.java

  1. /** @hide */
  2. public static final String PRIZE_NET_WHITELIST_ON = "prize_net_whiteon";

 -------------frameworks/base/packages/SettingsProvider/res/values/defaults.xml

<bool name="net_white_on">false</bool>

--------frameworks/base/packages/SettingsProvider/src/com/android/providers/settings/DatabaseHelper.java

loadBooleanSetting(stmt, Settings.System.PRIZE_NET_WHITELIST_ON, R.bool.net_white_on);

-------frameworks/base/core/java/android/os/INetworkManagementService.aidl

  1. /**
  2. * setBrowserWhiteListEnable add network white list
  3. */
  4. void setBrowserWhiteListEnable(String white_list, boolean allow);
  5. /**
  6. * delBrowserWhiteListChainTable del network white list
  7. */
  8. void delBrowserWhiteListChainTable(String white_list, boolean allow);

-------frameworks/base/services/core/java/com/android/server/NetworkManagementService.java

  1. @Override
  2. public void setBrowserWhiteListEnable(String white_list, boolean allow) {
  3. enforceSystemUid();
  4. final String rule = allow ? "allow" : "deny";
  5. try {
  6. Slog.e("snail_", "-----setBrowserWhiteListEnable---white_list==" + white_list +" bool=="+allow);
  7. mConnector.execute("firewall", "set_browserwhitelist_enable", white_list, rule);
  8. } catch (NativeDaemonConnectorException e) {
  9. Slog.e("snail_", "-----setBrowserWhiteListEnable----Exception----white_list==" + white_list +" bool=="+allow + ": " + e);
  10. throw e.rethrowAsParcelableException();
  11. }
  12. }
  13. @Override
  14. public void delBrowserWhiteListChainTable(String white_list, boolean allow) {
  15. enforceSystemUid();
  16. final String rule = allow ? "allow" : "deny";
  17. try {
  18. Slog.e("snail_", "-----delBrowserWhiteListChainTable---white_list==" + white_list +" bool=="+allow);
  19. mConnector.execute("firewall", "del_browserwhitelist_chaintable", white_list, rule);
  20. } catch (NativeDaemonConnectorException e) {
  21. Slog.e("snail_", "-----delBrowserWhiteListChainTable----Exception----white_list==" + white_list +" bool=="+allow + ": " + e);
  22. throw e.rethrowAsParcelableException();
  23. }
  24. }

 --------system/netd/server/FirewallController.h

  1. int setBrowserWhiteListEnable(const char*, FirewallRule);
  2. int delBrowserWhiteListChainTable(const char*, FirewallRule);

 --------system/netd/server/FirewallController.cpp

  1. int FirewallController::setBrowserWhiteListEnable(const char* list, FirewallRule rule) {
  2. //const char *chaintable = "WEBWHITELIST";
  3. //const char *FORWARD_MARK = "1";
  4. const char* op;
  5. if (rule == ALLOW) {
  6. ALOGE("--snail_-----setBrowserWhiteListEnable------rule == allow-------");
  7. op = "-I";
  8. } else {
  9. ALOGE("--snail_-----setBrowserWhiteListEnable------rule == deny-------");
  10. op = "-D";
  11. }
  12. ALOGE("---snail_------set_browserwhitelist_enable-list===%s", list);
  13. const char *split = ",";
  14. char *p;
  15. char* white_list = const_cast<char*>(list);
  16. p = strtok(white_list,split);
  17. int res = 0;
  18. //iptables -t filter -N WEBWHITELIST
  19. //iptables -I OUTPUT -p tcp -j WEBWHITELIST
  20. //iptables -t mangle -N WEBWHITELIST
  21. //iptables -t mangle -I fw_mangle_POSTROUTING -p udp -j WEBWHITELIST
  22. res |= execIptables(V4V6, "-t", "mangle", "-N", "WEBWHITELIST", NULL);
  23. ALOGE("---snail_-------New WEBWHITELIST---------res===%d", res);
  24. if(res == 0){
  25. res |= execIptables(V4V6, "-t", "mangle", "-I", "fw_mangle_POSTROUTING", "-p", "udp", "-j", "WEBWHITELIST", NULL);
  26. while(p!=NULL) {
  27. ALOGE("---snail_-set_browserwhitelist_enable-p!=NULL===%s\n", p);
  28. //iptables -A WEBWHITELIST -p tcp -m string --string Host: --algo bm -j MARK --set-mark 1
  29. //iptables -A WEBWHITELIST -p tcp -m mark --mark 1 -m string --string baidu --algo bm -j ACCEPT
  30. //iptables -A WEBWHITELIST -p tcp -m mark --mark 1 -j REJECT
  31. //iptables -t mangle -A WEBWHITELIST -p udp --dport 53 -m string --string baidu --algo bm -j ACCEPT
  32. //iptables -t mangle -A WEBWHITELIST -p udp --dport 53 -m string --string taobao --algo bm -j ACCEPT
  33. //iptables -t mangle -A WEBWHITELIST -p udp --dport 53 -j DROP
  34. //res |= execIptables(V4V6, "-A", "WEBWHITELIST", "-p", "tcp", "-m", "string", "--string" ,"Host:", "--algo", "bm","-j", "MARK", "--set-mark", "1", NULL);
  35. //res |= execIptables(V4V6, "-A", "WEBWHITELIST", "-p", "tcp", "-m", "mark", "--mark" ,"1" , "-m", "string", "--string" , p, "--algo", "bm", "-j", "ACCEPT", NULL);
  36. res |= execIptables(V4V6, "-t", "mangle", "-A", "WEBWHITELIST", "-p", "udp", "--dport", "53", "-m" ,"string", "--string" , p, "--algo", "bm", "-j", "ACCEPT", NULL);
  37. p = strtok(NULL,split);
  38. }
  39. //res |= execIptables(V4V6, "-A", "WEBWHITELIST", "-p", "tcp", "-m", "mark", "--mark" ,"1", "-j", "REJECT", NULL);
  40. res |= execIptables(V4V6, "-t", "mangle", "-A", "WEBWHITELIST", "-p", "udp", "--dport", "53", "-j", "DROP", NULL);
  41. }
  42. ALOGE("---snail_------set_browserwhitelist_enable-list---end===%d", res);
  43. return res;
  44. }
  45. int FirewallController::delBrowserWhiteListChainTable(const char* list, FirewallRule rule) {
  46. const char* op;
  47. const char *DEL = "1";
  48. if (rule == ALLOW) {
  49. ALOGE("--snail_-----delBrowserWhiteListChainTable------rule == allow-------");
  50. op = "-I";
  51. } else {
  52. ALOGE("--snail_-----delBrowserWhiteListChainTable------rule == deny-------");
  53. op = "-D";
  54. }
  55. ALOGE("---snail_------delBrowserWhiteListChainTable-list===%s", list);
  56. //iptables -D OUTPUT 1
  57. //iptables -t filter -F WEBWHITELIST
  58. //iptables -t filter -X WEBWHITELIST
  59. //iptables -t mangle -D fw_mangle_POSTROUTING 1
  60. //iptables -t mangle -F WEBWHITELIST
  61. //iptables -t mangle -X WEBWHITELIST
  62. int res = 0;
  63. res |= execIptables(V4V6, "-t", "mangle", "-D", "fw_mangle_POSTROUTING", DEL, NULL);
  64. res |= execIptables(V4V6, "-t", "mangle", "-F", "WEBWHITELIST", NULL);
  65. res |= execIptables(V4V6, "-t", "mangle", "-X", "WEBWHITELIST", NULL);
  66. return res;
  67. }

 ----------system/netd/server/CommandListener.cpp

  1. int CommandListener::FirewallCmd::runCommand(SocketClient *cli, int argc,
  2. char **argv) {
  3. if (!strcmp(argv[1], "set_browserwhitelist_enable")) {
  4. ALOGE("---snail_---------runCommand------set_browserwhitelist_enable---start-----");
  5. if (argc != 4) {
  6. ALOGE("---snail_---------runCommand------set_browserwhitelist_enable---Error---");
  7. cli->sendMsg(ResponseCode::CommandSyntaxError,
  8. "Usage: firewall set_browserwhitelist_enable <rmnet0> <allow|deny>", false);
  9. return 0;
  10. }
  11. const char* white_list = argv[2];
  12. FirewallRule rule = parseRule(argv[3]);
  13. ALOGE("---snail_---------runCommand------set_browserwhitelist_enable-white_list===%s", argv[2]);
  14. int res = gCtls->firewallCtrl.setBrowserWhiteListEnable(white_list, rule);
  15. return sendGenericOkFail(cli, res);
  16. }
  17. if (!strcmp(argv[1], "del_browserwhitelist_chaintable")) {
  18. ALOGE("---snail_---------runCommand------del_browserwhitelist_chaintable---start-----");
  19. if (argc != 4) {
  20. ALOGE("---snail_---------runCommand------del_browserwhitelist_chaintable---Error---");
  21. cli->sendMsg(ResponseCode::CommandSyntaxError,
  22. "Usage: firewall del_browserwhitelist_chaintable <rmnet0> <allow|deny>", false);
  23. return 0;
  24. }
  25. const char* white_list = argv[2];
  26. FirewallRule rule = parseRule(argv[3]);
  27. ALOGE("---snail_---------runCommand------del_browserwhitelist_chaintable-white_list===%s", argv[2]);
  28. int res = gCtls->firewallCtrl.delBrowserWhiteListChainTable(white_list, rule);
  29. return sendGenericOkFail(cli, res);
  30. }

app實現

  1. @Override
  2. public void setBrowserWhiteListEnable(boolean white_list_on,String white_list) throws RemoteException {
  3. // TODO Auto-generated method stub
  4. //String onnetfile = "/sdcard/.WhiteListNetList";
  5. //Utils.initWhiteListNetList(onnetfile);
  6. //List<String> list = Utils.readNetWhiteList(onnetfile);
  7. List<String> list = Utils.readNetWhiteListByProvider(RemoteService.this);
  8. String[] array = new String[list.size()];
  9. // List轉換成數組
  10. for (int i = 0; i < list.size(); i++) {
  11. array[i] = list.get(i);
  12. TXLog.d(TAG, "----------setBrowserWhiteListEnable----------------array[i]=="+array[i]);
  13. }
  14. //Utils.writeNetWhiteList(onnetfile, Arrays.asList(white_list.split(",")));
  15. Utils.whiteNetWhiteListByProvider(RemoteService.this, Arrays.asList(white_list.split(",")));
  16. if(white_list_on){ Utils.delBrowserWhiteListChainTable(true, white_list);
  17. Utils.setBrowserWhiteListEnable(true, white_list);
  18. Settings.System.putInt(RemoteService.this.getApplicationContext().getContentResolver(),Settings.System.PRIZE_NET_WHITELIST_ON,1);
  19. }else {
  20. Utils.delBrowserWhiteListChainTable(true, white_list);
  21. Settings.System.putInt(RemoteService.this.getApplicationContext().getContentResolver(),Settings.System.PRIZE_NET_WHITELIST_ON,0);
  22. }
  23. }
  24. @Override
  25. public String[] getBrowserWhiteList() throws RemoteException {
  26. // TODO Auto-generated method stub
  27. //String onnetfile = "/sdcard/.WhiteListNetList";
  28. //Utils.initWhiteListNetList(onnetfile);
  29. //List<String> list = Utils.readNetWhiteList(onnetfile);
  30. int isopen = Settings.System.getInt(RemoteService.this.getApplicationContext().getContentResolver(),Settings.System.PRIZE_NET_WHITELIST_ON,0);
  31. if(isopen==0){
  32. TXLog.d(TAG, "----------getBrowserWhiteList-------return null--------");
  33. return null;
  34. }
  35. List<String> list = Utils.readNetWhiteListByProvider(RemoteService.this);
  36. String[] array = new String[list.size()];
  37. // List轉換成數組
  38. for (int i = 0; i < list.size(); i++) {
  39. array[i] = list.get(i);
  40. TXLog.d(TAG, "----------getBrowserWhiteList----------------array[i]=="+array[i]);
  41. }
  42. return array;
  43. }
  44. @Override
  45. public void addBrowserWhiteList(String addwhite) throws RemoteException {
  46. // TODO Auto-generated method stub
  47. //String onnetfile = "/sdcard/.WhiteListNetList";
  48. //Utils.initWhiteListNetList(onnetfile);
  49. //List<String> list = Utils.readNetWhiteList(onnetfile);
  50. List<String> list = Utils.readNetWhiteListByProvider(RemoteService.this);
  51. Utils.delBrowserWhiteListChainTable(true, addwhite);
  52. List<String> addlist = Arrays.asList(addwhite.split(","));
  53. for (int i = 0; i < addlist.size(); i++) {
  54. if(!list.contains(addlist.get(i))){
  55. list.add(addlist.get(i));
  56. }
  57. }
  58. StringBuilder csBuilder = new StringBuilder();
  59. for(String weburl : list){
  60. csBuilder.append(weburl);
  61. csBuilder.append(",");
  62. }
  63. if(csBuilder.length()>1){
  64. csBuilder.deleteCharAt(csBuilder.length()-1);
  65. }
  66. //Utils.writeNetWhiteList(onnetfile, Arrays.asList(csBuilder.toString().split(",")));
  67. //List<String> newlist = Utils.readNetWhiteList(onnetfile);
  68. Utils.whiteNetWhiteListByProvider(RemoteService.this, Arrays.asList(csBuilder.toString().split(",")));
  69. Utils.setBrowserWhiteListEnable(true, csBuilder.toString());
  70. Settings.System.putInt(RemoteService.this.getApplicationContext().getContentResolver(),Settings.System.PRIZE_NET_WHITELIST_ON,1);
  71. }
  72. public static void whiteNetWhiteListByProvider(Context context, List<String> webnames){
  73.     try {
  74. Uri uri = Uri.parse("content://com.prize.txInterface.provider/ip");
  75. context.getApplicationContext().getContentResolver().delete(uri,null,null);
  76. for (int i = 0; i < webnames.size(); i++) {
  77. String host = webnames.get(i);
  78. TXLog.d(TAG,"---------------whiteNetWhiteListByProvider------------host==="+host);
  79. if(!TextUtils.isEmpty(host)){
  80. Cursor cursor = context.getApplicationContext().getContentResolver().query(uri, null, "host = ?",new String[]{host}, null);
  81. if(cursor != null){
  82.          if(cursor.getCount()<=0){
  83. ContentValues values = new ContentValues();
  84. values.put("host", host);
  85. values.put("isActive", "true");
  86. TXLog.d(TAG,"---------------whiteNetWhiteListByProvider------------insert==="+host);
  87. context.getApplicationContext().getContentResolver().insert(uri, values);
  88. }
  89. }
  90. }
  91.     }
  92. } catch (Exception e) {
  93. // TODO: handle exception
  94. TXLog.d(TAG,"---------------whiteNetWhiteListByProvider------------"+e.getMessage());
  95. return ;
  96. }
  97. }
  98. public static void delBrowserWhiteListChainTable(boolean white_list_on ,String white_list){
  99. INetworkManagementService netMgr = INetworkManagementService.Stub.asInterface(ServiceManager.getService(Context.NETWORKMANAGEMENT_SERVICE));
  100. try {
  101. Log.e(TAG,"----delBrowserWhiteListChainTable-------------white_list=="+white_list);
  102. netMgr.delBrowserWhiteListChainTable(white_list,white_list_on);
  103. } catch (Exception e) {
  104. Log.e(TAG,"----delBrowserWhiteListChainTable-----RemoteException----------e==="+e.getMessage());
  105. e.printStackTrace();
  106. }
  107. }
  108. public static void setBrowserWhiteListEnable(boolean white_list_on ,String white_list){
  109. INetworkManagementService netMgr = INetworkManagementService.Stub.asInterface(ServiceManager.getService(Context.NETWORKMANAGEMENT_SERVICE));
  110. try {
  111. Log.e(TAG,"----setBrowserWhiteListEnable-------------white_list=="+white_list);
  112. netMgr.setBrowserWhiteListEnable(white_list,white_list_on);
  113. } catch (Exception e) {
  114. Log.e(TAG,"----setBrowserWhiteListEnable-----RemoteException----------e==="+e.getMessage());
  115. e.printStackTrace();
  116. }
  117. }

12)  APK安裝白名單接口

---------frameworks/base/core/java/android/provider/Settings.java

  1. /** @hide */
  2. public static final String PRIZE_INSTALL_WHITELIST_ON = "prize_install_whiteon";

------frameworks/base/packages/SettingsProvider/res/values/defaults.xml

 	<bool name="install_white_on">false</bool>

 ------frameworks/base/packages/SettingsProvider/src/com/android/providers/settings/DatabaseHelper.java

loadBooleanSetting(stmt, Settings.System.PRIZE_INSTALL_WHITELIST_ON, R.bool.install_white_on);
  1. @Override
  2. public void setApkWhiteListEnable(boolean iscaninstall, String whitelist)
  3. throws RemoteException {
  4. // TODO Auto-generated method stub
  5. //Utils.initWhiteListAppList(whitelist);
  6. //Utils.readInstallWhiteList(whitelist);
  7. //Utils.writeInstallWhiteList("/sdcard/.WhiteListAppList", Arrays.asList(whitelist.split(",")));
  8. Utils.readInstallWhiteListByProvider(RemoteService.this.getApplicationContext());
  9. Utils.whiteInstallWhiteListByProvider(RemoteService.this.getApplicationContext(),Arrays.asList(whitelist.split(",")));
  10. if(iscaninstall){
  11. Settings.System.putInt(RemoteService.this.getApplicationContext().getContentResolver(),Settings.System.PRIZE_INSTALL_WHITELIST_ON,1);
  12. }else {
  13. Settings.System.putInt(RemoteService.this.getApplicationContext().getContentResolver(),Settings.System.PRIZE_INSTALL_WHITELIST_ON,0);
  14. }
  15. }
  16. public static List<String> readInstallWhiteListByProvider(Context context){
  17. try {
  18. Uri uri = Uri.parse("content://com.prize.txInterface.provider/install");
  19. List<String> list = new ArrayList<String>();
  20. Cursor cursor = context.getApplicationContext().getContentResolver().query(uri, null, null,null, null);
  21. if(cursor!=null&&cursor.moveToFirst()){
  22. do{
  23. String pkg = cursor.getString(cursor.getColumnIndex("package"));
  24. TXLog.d(TAG,"---------------readInstallWhiteListByProvider------------pkg=="+pkg);
  25. if(!TextUtils.isEmpty(pkg)&& !list.contains(pkg)){
  26. list.add(pkg);
  27. }
  28. }while(cursor.moveToNext());
  29. }
  30. return list;
  31. } catch (Exception e) {
  32. // TODO: handle exception
  33. TXLog.d(TAG,"---------------readInstallWhiteListByProvider------------"+e.getMessage());
  34. return null;
  35. }
  36. }
  37. public static void whiteInstallWhiteListByProvider(Context context, List<String> pkgnames){
  38. try {
  39. Uri uri = Uri.parse("content://com.prize.txInterface.provider/install");
  40. context.getApplicationContext().getContentResolver().delete(uri,null,null);
  41. for (int i = 0; i < pkgnames.size(); i++) {
  42. String pkg = pkgnames.get(i);
  43. TXLog.d(TAG,"---------------whiteInstallWhiteListByProvider------------pkg==="+pkg);
  44. if(!TextUtils.isEmpty(pkg)){
  45. Cursor cursor = context.getApplicationContext().getContentResolver().query(uri, null, "package = ?",new String[]{pkg}, null);
  46. if(cursor != null){
  47. if(cursor.getCount()<=0){
  48. ContentValues values = new ContentValues();
  49. values.put("package", pkg);
  50. values.put("isActive", "true");
  51. TXLog.d(TAG,"---------------whiteInstallWhiteListByProvider------------insert==="+pkg);
  52. context.getApplicationContext().getContentResolver().insert(uri, values);
  53. }
  54. }
  55. }
  56. }
  57. } catch (Exception e) {
  58. // TODO: handle exception
  59. TXLog.d(TAG,"---------------whiteInstallWhiteListByProvider------------"+e.getMessage());
  60. return ;
  61. }
  62. }

----- frameworks/base/services/core/java/com/android/server/pm/PackageManagerService.java

  1. private void installPackageLI(InstallArgs args, PackageInstalledInfo res){
  2. String pkgName = res.name = pkg.packageName;
  3. Log.e("snail_", "---------installPackageLI---------------------pkgName=="+pkgName);
  4. if ((installFlags & PackageManager.INSTALL_REPLACE_EXISTING) != 0){
  5. Log.e("snail_", "---------installPackageLI----------INSTALL_REPLACE_EXISTING-------------");
  6. }
  7. //boolean byprize = false;
  8. //if ((installFlags & PackageManager.INSTALL_FROM_PRIZE) != 0){
  9. // Log.e("snail_", "---------installPackageLI----------INSTALL_FROM_PRIZE-------------");
  10. // byprize = true;
  11. //}
  12. int iswhiteon = android.provider.Settings.System.getInt(mContext.getContentResolver(),android.provider.Settings.System.PRIZE_INSTALL_WHITELIST_ON,
  13. 0);
  14. Log.e("snail_", "---------installPackageLI----------------iswhiteon=="+iswhiteon);
  15. if(iswhiteon == 1){
  16. //add for installer white list
  17. boolean caninstall =false;
  18. Log.e("snail_", "---------installPackageLI----------------pkgName=="+pkgName);
  19. if(!TextUtils.isEmpty(pkgName)){
  20. if(isInstallerEnable(pkgName)/*|| byprize*/){
  21. Log.e("snail_", "---------installPackageLI----------------caninstall = true------------");
  22. caninstall = true;
  23. }
  24. if(!caninstall){
  25. //Toast.makeText(mContext, R.string.install_error, Toast.LENGTH_LONG).show();
  26. Log.e("snail_", "---------installPackageLI----------------caninstall = false------------");
  27. //res.returnCode = PackageManager.INSTALL_FAILED_DUPLICATE_PERMISSION;
  28. res.setError(PackageManager.INSTALL_FAILED_VERIFICATION_FAILURE,
  29. "app is not in the whitelist. packageName:" + pkgName);
  30. return;
  31. }
  32. }
  33. }
  34. /*add for installer white list*/
  35. private boolean isInstallerEnable(String packagename){
  36. /* ArrayList<String> whiteListApp = new ArrayList<String>();
  37. try{
  38. BufferedReader br = new BufferedReader(new InputStreamReader(
  39. new FileInputStream("/sdcard/.WhiteListAppList")));
  40. String line ="";
  41. while ((line = br.readLine()) != null){
  42. whiteListApp.add(line);
  43. }
  44. br.close();
  45. }catch(java.io.FileNotFoundException ex){
  46. Log.e("snail_", "--------isInstallerEnable------FileNotFoundException=="+ex.getMessage());
  47. return false;
  48. }catch(java.io.IOException ex){
  49. Log.e("snail_", "--------isInstallerEnable------IOException=="+ex.getMessage());
  50. return false;
  51. }
  52. Iterator<String> it = whiteListApp.iterator();
  53. while (it.hasNext()) {
  54. String whitelisItem = it.next();
  55. Log.e("snail_", "--------isInstallerEnable------whitelisItem=="+whitelisItem+" packagename=="+packagename);
  56. if (whitelisItem.equals(packagename)) {
  57. return true;
  58. }
  59. }
  60. return false;*/
  61. try {
  62. Uri uri = Uri.parse("content://com.prize.txInterface.provider/install");
  63. //List<String> list = new ArrayList<String>();
  64. Cursor cursor = mContext.getApplicationContext().getContentResolver().query(uri, null, "package = ?",new String[]{packagename}, null);
  65. if(cursor != null && cursor.moveToFirst()){
  66. Log.d(TAG,"---------readInstallWhiteListByProvider-------------exist==="+packagename);
  67. return true;
  68. }else {
  69. Log.d(TAG,"---------readInstallWhiteListByProvider-------------!!!!!exist==="+packagename);
  70. }
  71. return false;
  72. } catch (Exception e) {
  73. // TODO: handle exception
  74. Log.d("snail_","---------------readInstallWhiteListByProvider------------"+e.getMessage());
  75. return false;
  76. }
  77. }

---------packages/apps/PackageInstaller/src/com/android/packageinstaller/PackageInstallerActivity.java

  1. private boolean readInstallWhiteListByProvider(Context context,String packagename){
  2. try {
  3. Uri uri = Uri.parse("content://com.prize.txInterface.provider/install");
  4. List<String> list = new ArrayList<String>();
  5. Cursor cursor = context.getApplicationContext().getContentResolver().query(uri, null, "package = ?",new String[]{packagename}, null);
  6. if(cursor != null && cursor.moveToFirst()){
  7. Log.d(TAG,"---------readInstallWhiteListByProvider-------------exist==="+packagename);
  8. return true;
  9. }
  10. return false;
  11. } catch (Exception e) {
  12. // TODO: handle exception
  13. Log.d("snail_","---------------readInstallWhiteListByProvider------------"+e.getMessage());
  14. return false;
  15. }
  16. }
  17. private String getInstallpkg(final Uri packageUri){
  18. final String getInstallscheme = packageUri.getScheme();
  19. final PackageUtil.AppSnippet as;
  20. PackageInfo getInstallPkgInfo = null;
  21. Log.e("snail_", "-----onCreate-------getInstallpkg----------getInstallscheme=="+getInstallscheme);
  22. if(getInstallscheme.equals(SCHEME_PACKAGE)){
  23. try {
  24. getInstallPkgInfo = mPm.getPackageInfo(packageUri.getSchemeSpecificPart(),PackageManager.GET_PERMISSIONS| PackageManager.GET_UNINSTALLED_PACKAGES);
  25. } catch (NameNotFoundException e) {
  26. }
  27. if (getInstallPkgInfo != null) {
  28. return getInstallPkgInfo.packageName;
  29. }else {
  30. Log.e("snail_", "-----onCreate-------getInstallpkg---SCHEME_PACKAGE----null------");
  31. }
  32. }else if (getInstallscheme.equals(SCHEME_FILE)) {
  33. File sourceFile = new File(packageUri.getPath());
  34. PackageParser.Package parsed = PackageUtil.getPackageInfo(sourceFile);
  35. // Check for parse errors
  36. if (parsed != null) {
  37. getInstallPkgInfo = PackageParser.generatePackageInfo(parsed, null,PackageManager.GET_PERMISSIONS, 0, 0, null,new PackageUserState());
  38. if (getInstallPkgInfo != null) {
  39. return getInstallPkgInfo.packageName;
  40. }else {
  41. Log.e("snail_", "-----onCreate-------getInstallpkg---SCHEME_FILE----null------");
  42. }
  43. }
  44. }else if (getInstallscheme.equals(SCHEME_CONTENT)) {
  45. Uri baseUri = MediaStore.Files.getContentUri("external");
  46. Log.e("snail_","-----getInstallpkg--------------------SCHEME_CONTENT--------------baseUri=="+baseUri.toString());
  47. if(packageUri.toString().contains(baseUri.toString())){
  48. try {
  49. //int id = Integer.parseInt(packageUri.toString().replace(baseUri.toString()+File.separator, ""));
  50. String id = packageUri.toString().replace(baseUri.toString()+File.separator, "");
  51. String pathString = getPkgPath(PackageInstallerActivity.this,id);
  52. Log.d("snail_", "--------getApkPackagesName---SCHEME_CONTENT--------pathString=="+pathString);
  53. if(!TextUtils.isEmpty(pathString)){
  54. PackageManager pm = PackageInstallerActivity.this.getApplicationContext().getPackageManager();
  55. PackageInfo info = pm.getPackageArchiveInfo(pathString, PackageManager.GET_ACTIVITIES);
  56. ApplicationInfo appInfo = null;
  57. if (info != null) {
  58. appInfo = info.applicationInfo;
  59. String packageName = appInfo.packageName;
  60. Log.d("snail_", "--------getApkPackagesName--*****************---------packageName=="+packageName);
  61. return packageName;
  62. }
  63. }
  64. } catch (NumberFormatException e) {
  65. Log.e("snail_", "-----onCreate-------getInstallpkg---NumberFormatException------e=="+e.getMessage());
  66. e.printStackTrace();
  67. }
  68. }
  69. }
  70. return "";
  71. }
  72. public String getPkgPath(Context context,String _id) {
  73. final String[] projection = {MediaColumns.DATA};
  74. final String where = MediaColumns._ID + " = ?";
  75. Uri baseUri = MediaStore.Files.getContentUri("external");
  76. Cursor c = null;
  77. String provider = "com.android.providers.media.MediaProvider";
  78. Uri itemUri = null;
  79. context.grantUriPermission(provider, baseUri, Intent.FLAG_GRANT_READ_URI_PERMISSION);
  80. Log.d("snail_", "getItemContentUri------- projection = "+projection+", where = "+where+ ", baseUri = "+baseUri);
  81. try {
  82. c = context.getContentResolver().query(baseUri,
  83. projection,
  84. where,
  85. new String[]{_id},
  86. null);
  87. if (c != null && c.moveToNext()) {
  88. String path = c.getString(c.getColumnIndexOrThrow(MediaColumns.DATA));//DATA
  89. if (!TextUtils.isEmpty(path)) {
  90. Log.d("snail_", "getItemContentUri, path = " + path);
  91. return path;
  92. }
  93. }
  94. } catch (Exception e) {
  95. Log.e(TAG, "getItemContentUri Exception", e);
  96. } finally {
  97. if (c != null) {
  98. c.close();
  99. }
  100. }
  101. return "";
  102. }
  103. private boolean judgeInstallwhite(String pkgName){
  104. if (!TextUtils.isEmpty(pkgName)) {
  105. Log.e("snail_", "-----judgeInstallwhite------------------------pkgName=="+ pkgName);
  106. // add for installer enable/disable
  107. if (!readInstallWhiteListByProvider(PackageInstallerActivity.this,pkgName)) {
  108. Log.e("snail_","-----judgeInstallwhite-----------!!!!!!isInstallerEnable--------------");
  109. return false;
  110. }
  111. }
  112. return true;
  113. }
  114. onCreate{
  115. Log.e("snail_", "-----onCreate----------------111----------packageUri=="+packageUri);
  116. int iswhiteon = android.provider.Settings.System.getInt(this.getContentResolver(),android.provider.Settings.System.PRIZE_INSTALL_WHITELIST_ON,0);
  117. if (iswhiteon == 1) {
  118. String pkgName = getInstallpkg(packageUri);
  119. if (!TextUtils.isEmpty(pkgName)) {
  120. Log.e("snail_","-----judgeInstallwhite------------------------pkgName=="+ pkgName);
  121. // add for installer enable/disable
  122. if (!judgeInstallwhite(pkgName)) {
  123. Log.e("snail_","-----judgeInstallwhite-----------!!!!!!isInstallerEnable--------------");
  124. this.overridePendingTransition(0, 0);
  125. finish();
  126. return;
  127. }
  128. }
  129. }

13)  應用卸載接口

詳見  天芯教育需求接口實現(一)   應用靜默安裝

14)  護眼模式開關接口


  1. public static void setBluesysEnable(final Context mContext,final boolean isOpen) {
  2. final boolean BLUELIGHT_MTK = true;
  3. AsyncTask.execute(new Runnable() {
  4. public void run() {
  5. final ContentResolver mResolver = mContext.getContentResolver();
  6. Settings.System.putIntForUser(mResolver,Settings.System.PRIZE_BLULIGHT_MODE_STATE, isOpen ? 0: 1, UserHandle.USER_CURRENT);
  7. int mBluLightTimeStatus = Settings.System.getIntForUser(mResolver, Settings.System.PRIZE_BLULIGHT_TIME_STATE,0, UserHandle.USER_CURRENT);
  8. int mBluLightTimingStatus = Settings.System.getIntForUser(mResolver, Settings.System.PRIZE_BLULIGHT_TIMING_STATE,0, UserHandle.USER_CURRENT);
  9. if (isOpen) {
  10. if (BLUELIGHT_MTK) {
  11. PictureQuality.enableBlueLight(false);
  12. }
  13. if (mBluLightTimeStatus == 1) {
  14. Settings.System.putInt(mResolver, Settings.System.PRIZE_BLULIGHT_TIMING_STATE, 0);
  15. setBluLightTime(mContext,101010,Settings.System.PRIZE_BLULIGHT_START_TIME,"com.android.intent_action_open_blulight");
  16. }
  17. } else {
  18. if (BLUELIGHT_MTK) {
  19. PictureQuality.enableBlueLight(true);
  20. }
  21. /* prize-modify for huyanmode-lihuangyuan-2017-06-09-end */
  22. if (mBluLightTimingStatus == 1) {
  23. setBluLightTime(mContext,101011,Settings.System.PRIZE_BLULIGHT_END_TIME,"com.android.intent_action_close_blulight");
  24. if(mBluLightTimingStatus == 0){
  25. cancelAlarm(mContext,"com.android.intent_action_open_blulight");
  26. }
  27. }
  28. }
  29. }
  30. });
  31. }
  32. private static void cancelAlarm(final Context mContext,String action){
  33. Intent intent = new Intent();
  34. intent.setAction(action);
  35. PendingIntent pi = PendingIntent.getBroadcast(mContext, 0,intent, 0);
  36. AlarmManager am = (AlarmManager)mContext.getSystemService(Context.ALARM_SERVICE);
  37. am.cancel(pi);
  38. }
  39. private static void setBluLightTime(final Context mContext,int requestCode,String key, String action){
  40. TXLog.d(TAG,"--------setBluLightTime setBluLightTime() key = " + key);
  41. AlarmManager alarmManager = (AlarmManager) mContext.getSystemService(Context.ALARM_SERVICE);
  42. Intent mIntent = new Intent(action);
  43. PendingIntent operation = PendingIntent.getBroadcast(mContext, requestCode /* requestCode */, mIntent, 0);
  44. long alarmTime = getAlarmTime(key).getTimeInMillis();
  45. alarmManager.setExact(AlarmManager.RTC_WAKEUP,alarmTime,operation);
  46. }
  47. public static Calendar getAlarmTime(String key) {
  48. int[] mHourAndMinuteArr = parseBluLightTime(key);
  49. int hour = mHourAndMinuteArr[0];
  50. int minute = mHourAndMinuteArr[1];
  51. Log.d("BluLight","PrizeBluLightTileDefined getAlarmTime() key = " + key+",hour = "+hour+",minute = "+minute);
  52. Calendar calendar = Calendar.getInstance();
  53. calendar.setTimeInMillis(System.currentTimeMillis());
  54. int mYear = calendar.get(Calendar.YEAR);
  55. int mMonth = calendar.get(Calendar.MONTH);
  56. int mDay = calendar.get(Calendar.DAY_OF_MONTH);
  57. Calendar mCalendar = Calendar.getInstance();
  58. mCalendar.set(Calendar.YEAR, mYear);
  59. mCalendar.set(Calendar.MONTH, mMonth);
  60. mCalendar.set(Calendar.DAY_OF_MONTH, mDay);
  61. mCalendar.set(Calendar.HOUR_OF_DAY, hour);
  62. mCalendar.set(Calendar.MINUTE, minute);
  63. mCalendar.set(Calendar.SECOND, 0);
  64. mCalendar.set(Calendar.MILLISECOND, 0);
  65. long mCurrentMillis = calendar.getTimeInMillis();
  66. long mTimerMillis = mCalendar.getTimeInMillis();
  67. boolean isTimerEarlyCurrent = mTimerMillis < mCurrentMillis;
  68. boolean isEndEarlyStart = false;
  69. if(Settings.System.PRIZE_BLULIGHT_END_TIME.equals(key)){
  70. int[] mStartHourAndMinuteArr = parseBluLightTime(Settings.System.PRIZE_BLULIGHT_START_TIME);
  71. int mStartHour = mStartHourAndMinuteArr[0];
  72. int mEndHour = mStartHourAndMinuteArr[1];
  73. Calendar mStartCalendar = Calendar.getInstance();
  74. mStartCalendar.set(Calendar.YEAR, mYear);
  75. mStartCalendar.set(Calendar.MONTH, mMonth);
  76. mStartCalendar.set(Calendar.DAY_OF_MONTH, mDay);
  77. mStartCalendar.set(Calendar.HOUR_OF_DAY, mStartHour);
  78. mStartCalendar.set(Calendar.MINUTE, mEndHour);
  79. mStartCalendar.set(Calendar.SECOND, 0);
  80. mStartCalendar.set(Calendar.MILLISECOND, 0);
  81. long mStartMillis = mStartCalendar.getTimeInMillis();
  82. isEndEarlyStart = mTimerMillis < mStartMillis;
  83. }
  84. if(isTimerEarlyCurrent || isEndEarlyStart){
  85. mCalendar.set(Calendar.DAY_OF_MONTH, mDay+1);
  86. }
  87. SimpleDateFormat dfs = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss.SSS");
  88. String bgdate = dfs.format(mCalendar.getTime());
  89. Log.d("BluLight","PrizeBluLightTileDefined Time : "+bgdate);
  90. return mCalendar;
  91. }
  92. private static int[] parseBluLightTime(String key){
  93. String mBluLightTimeStatus = Settings.System.getString(mContext.getContentResolver(), key);
  94. int[] mHourAndMinuteArr = new int[2];
  95. if(mBluLightTimeStatus != null){
  96. String[] mTimeArr = mBluLightTimeStatus.split(":");
  97. for(int i=0;i<mTimeArr.length;i++){
  98. mHourAndMinuteArr[i] = Integer.parseInt(mTimeArr[i]);
  99. }
  100. }
  101. return mHourAndMinuteArr;
  102. }

15)  應用聯網控制

  1. public static void setAppFirewall(Context mContext,int uid, boolean enabled) {
  2. try {
  3. TXLog.d("PrizeNetControlsss", "setAppFirewall enabled:" + enabled+" uid=="+uid);
  4. getINetworkManagementService(mContext).setFirewallUidChainRule(uid, 0, enabled);
  5. getINetworkManagementService(mContext).setFirewallUidChainRule(uid, 1, enabled);
  6. } catch (RemoteException e) {
  7. e.printStackTrace();
  8. } catch (Exception e) {
  9. TXLog.d(TAG, "setAppFirewall exception");
  10. }
  11. }
  12. public void setFirewallUidChainRule(int uid, int networkType, boolean allow) {
  13. //enforceSystemUid();
  14. final String MOBILE = "mobile";
  15. final String WIFI = "wifi";
  16. final String rule = allow ? "allow" : "deny";
  17. final String chain = (networkType == 1) ? WIFI : MOBILE;
  18. try {
  19. mConnector.execute("firewall", "set_uid_fw_rule", uid, chain, rule);
  20. } catch (NativeDaemonConnectorException e) {
  21. throw e.rethrowAsParcelableException();
  22. }
  23. }
  24. //CommandListener.cpp
  25. if (!strcmp(argv[1], "set_uid_fw_rule")) {
  26. if (argc != 5) {
  27. cli->sendMsg(ResponseCode::CommandSyntaxError,
  28. "Usage: firewall set_uid_fw_rule <uid> <mobile|wifi> <allow|deny>",
  29. false);
  30. return 0;
  31. }
  32. int uid = atoi(argv[2]);
  33. FirewallChinaRule chain = parseChain(argv[3]);
  34. FirewallRule rule = parseRule(argv[4]);
  35. int res = gCtls->firewallCtrl.setUidFwRule(uid, chain, rule);
  36. return sendGenericOkFail(cli, res);
  37. }
  38. //FirewallController.cpp
  39. int FirewallController::setUidFwRule(int uid, FirewallChinaRule chain, FirewallRule rule) {
  40. char uidStr[16];
  41. int res = 0;
  42. const char* op;
  43. const char* fwChain;
  44. sprintf(uidStr, "%d", uid);
  45. if (rule == ALLOW) {
  46. op = "-I";
  47. } else {
  48. op = "-D";
  49. }
  50. if(chain == MOBILE) {
  51. fwChain = "mobile";
  52. }else{
  53. fwChain = "wifi";
  54. }
  55. if(chain == MOBILE) {
  56. if(rule == ALLOW)
  57. blacklistUsers.insert(uid);
  58. else
  59. blacklistUsers.erase(uid);
  60. }
  61. res |= execIptables(V4, op, fwChain, "-m", "owner", "--uid-owner", uidStr,
  62. "-j", "DROP", NULL);
  63. res |= execIptables(V6, op, fwChain, "-m", "owner", "--uid-owner", uidStr,
  64. "-j", "DROP", NULL);
  65. return res;
  66. }

16)  啓動ServiceActivity

  1. public static void startAapplication(Context context,int type,String pkg_name,String class_name){
  2. Intent mIntent=new Intent();
  3. mIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
  4. mIntent.setComponent(new ComponentName(pkg_name, class_name));
  5. TXLog.d(TAG, "----------startAapplication-----type=="+type+" pkg_name=="+pkg_name+" class_name=="+class_name);
  6. if(type==1){//service
  7. context.getApplicationContext().startService(mIntent);
  8. }else if(type==2){//activity
  9. context.getApplicationContext().startActivity(mIntent);
  10. }
  11. }

17)  控制無障礙服務

  1. package com.prize.txInterface.util;
  2. import java.util.Collections;
  3. import java.util.HashSet;
  4. import java.util.Set;
  5. import android.content.ComponentName;
  6. import android.content.Context;
  7. import android.provider.Settings;
  8. import android.text.TextUtils.SimpleStringSplitter;
  9. public class AccessibilityUtils {
  10. private static String TAG = "snail_AccessibilityUtils";
  11. /**
  12. * @return the set of enabled accessibility services. If there are not services
  13. * it returned the unmodifiable {@link Collections#emptySet()}.
  14. */
  15. public static Set<ComponentName> getEnabledServicesFromSettings(Context context) {
  16. final String enabledServicesSetting = Settings.Secure.getString(
  17. context.getContentResolver(), Settings.Secure.ENABLED_ACCESSIBILITY_SERVICES);
  18. if (enabledServicesSetting == null) {
  19. TXLog.d(TAG, "----getEnabledServicesFromSettings-------getEnabledServicesFromSettings--------");
  20. return Collections.emptySet();
  21. }
  22. TXLog.d(TAG, "----getEnabledServicesFromSettings-------getEnabledServicesFromSettings==="+enabledServicesSetting);
  23. final Set<ComponentName> enabledServices = new HashSet<ComponentName>();
  24. final SimpleStringSplitter colonSplitter = new SimpleStringSplitter(':');
  25. colonSplitter.setString(enabledServicesSetting);
  26. while (colonSplitter.hasNext()) {
  27. final String componentNameString = colonSplitter.next();
  28. TXLog.d(TAG, "----getEnabledServicesFromSettings-------componentNameString==="+componentNameString);
  29. final ComponentName enabledService = ComponentName.unflattenFromString(componentNameString);
  30. if (enabledService != null) {
  31. enabledServices.add(enabledService);
  32. }
  33. }
  34. return enabledServices;
  35. }
  36. public static void turnOnAccesibilityService(Context context, Boolean isInsert,String pack_class_name) {
  37. Set<ComponentName> enabledServices = AccessibilityUtils.getEnabledServicesFromSettings(context);
  38. if (enabledServices == (Set<?>) Collections.emptySet()) {
  39. enabledServices = new HashSet<ComponentName>();
  40. }
  41. ComponentName toggledService = ComponentName.unflattenFromString(pack_class_name);
  42. TXLog.d(TAG, "---turnOnAccesibilityService-----------preferenceKey=="+pack_class_name+" toggledService=="+toggledService.toString());
  43. boolean accessibilityEnabled = false;
  44. if(isInsert){
  45. if(!enabledServices.contains(toggledService)){
  46. enabledServices.add(toggledService);
  47. TXLog.d(TAG, "--------turnOnAccesibilityService----isInsert---!!!!!!contains---------");
  48. }else {
  49. TXLog.d(TAG, "--------turnOnAccesibilityService---isInsert----contains---------");
  50. }
  51. }else {
  52. if(!enabledServices.contains(toggledService)){
  53. TXLog.d(TAG, "--------turnOnAccesibilityService----!!isInsert---!!!!!!contains---------");
  54. }else {
  55. enabledServices.remove(toggledService);
  56. TXLog.d(TAG, "--------turnOnAccesibilityService---!!!isInsert----contains---------");
  57. }
  58. }
  59. accessibilityEnabled = true;
  60. StringBuilder enabledServicesBuilder = new StringBuilder();
  61. for (ComponentName enabledService : enabledServices) {
  62. enabledServicesBuilder.append(enabledService.flattenToString());
  63. enabledServicesBuilder.append(':');
  64. }
  65. final int enabledServicesBuilderLength = enabledServicesBuilder.length();
  66. if (enabledServicesBuilderLength > 0) {
  67. enabledServicesBuilder.deleteCharAt(enabledServicesBuilderLength - 1);
  68. }
  69. TXLog.d(TAG, "----turnOnAccesibilityService--------enabledServicesBuilder==="+ enabledServicesBuilder.toString());
  70. Settings.Secure.putString(context.getContentResolver(),Settings.Secure.ENABLED_ACCESSIBILITY_SERVICES,enabledServicesBuilder.toString());
  71. Settings.Secure.putInt(context.getContentResolver(),Settings.Secure.ACCESSIBILITY_ENABLED, accessibilityEnabled ? 1: 0);
  72. }
  73. }

18)  控制設備管理器

  1. @Override
  2. public void controlDeviceManager(String pkg_receiver, boolean active)
  3. throws RemoteException {
  4. // TODO Auto-generated method stub
  5. ComponentName receive = ComponentName.unflattenFromString(pkg_receiver);
  6. if(active){
  7. DeviceAdminUtils.setActiveAdmin(RemoteService.this.getApplicationContext(), receive);
  8. }else{
  9. DeviceAdminUtils.removeActiveAdmin(RemoteService.this.getApplicationContext(), receive);
  10. }
  11. }
  1. package com.prize.txInterface.util;
  2. import java.io.IOException;
  3. import java.util.ArrayList;
  4. import java.util.List;
  5. import org.xmlpull.v1.XmlPullParserException;
  6. import android.app.ActivityManagerNative;
  7. import android.os.RemoteCallback;
  8. import android.widget.AppSecurityPermissions;
  9. import android.app.Activity;
  10. import android.app.admin.DeviceAdminInfo;
  11. import android.app.admin.DeviceAdminReceiver;
  12. import android.app.admin.DevicePolicyManager;
  13. import android.content.ComponentName;
  14. import android.content.Context;
  15. import android.content.Intent;
  16. import android.content.pm.ActivityInfo;
  17. import android.content.pm.PackageManager;
  18. import android.content.pm.ResolveInfo;
  19. import android.os.Bundle;
  20. import android.os.Handler;
  21. import android.os.RemoteException;
  22. import android.util.EventLog;
  23. import android.util.Log;
  24. public class DeviceAdminUtils {
  25. private static String TAG = "snail_DeviceAdminUtils";
  26. private static DevicePolicyManager mDPM;
  27. private static PackageManager mPackageManager;
  28. private static Handler mHandler;
  29. public static void removeActiveAdmin(final Context mContext,ComponentName mComponentName){
  30. final DeviceAdminInfo mDeviceAdmin;
  31. ActivityInfo ai;
  32. try {
  33. ai = getPackageManager(mContext).getReceiverInfo(mComponentName, PackageManager.GET_META_DATA);
  34. } catch (PackageManager.NameNotFoundException e) {
  35. Log.w(TAG, "-----removeActiveAdmin----Unable to retrieve device policy " + mComponentName, e);
  36. return;
  37. }
  38. try {
  39. ActivityManagerNative.getDefault().stopAppSwitches();
  40. } catch (RemoteException e) {
  41. }
  42. if (!getDevicePolicyManager(mContext).isAdminActive(mComponentName)) {
  43. List<ResolveInfo> avail = getPackageManager(mContext).queryBroadcastReceivers(
  44. new Intent(DeviceAdminReceiver.ACTION_DEVICE_ADMIN_ENABLED),
  45. PackageManager.GET_DISABLED_UNTIL_USED_COMPONENTS);
  46. int count = avail == null ? 0 : avail.size();
  47. boolean found = false;
  48. for (int i=0; i<count; i++) {
  49. ResolveInfo ri = avail.get(i);
  50. if (ai.packageName.equals(ri.activityInfo.packageName)&& ai.name.equals(ri.activityInfo.name)) {
  51. try {
  52. // We didn't retrieve the meta data for all possible matches, so
  53. // need to use the activity info of this specific one that was retrieved.
  54. ri.activityInfo = ai;
  55. DeviceAdminInfo dpi = new DeviceAdminInfo(mContext, ri);
  56. found = true;
  57. } catch (XmlPullParserException e) {
  58. <
發佈了26 篇原創文章 · 獲贊 0 · 訪問量 2萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章