How to uninstall programs, clear data, and stop services on android

Source: Internet
Author: User

How to uninstall programs, clear data, and stop services on android
To uninstall programs, clear data, and stop running services, the code is summarized as follows:
The main classes used are:
PackageManager
ActivityManager
ApplicationInfo
RunningServiceInfo
Method
There are also two android. the source file in pm is used to generate a pile, IPackageStatsObserver. java and IPackageDataObserver. java, from the name, we can see that they are related to the package status and size. Find the source code of these two files on the Internet and put them in android under the src directory of the project. under the pm package, create your own package.
First, you need to obtain the installed apk in the system. The first is the system apk, and the second is the third-party apk. Therefore, you can specify a filter when obtaining the apk, see the following code:
Java code

  1. // Add a filter to get all programs, system programs, and programs installed by the user

  2. Private List queryFilterAppInfo (int filter ){
  3. // Query all installed applications
  4. List listAppcations =
  5. Pm. getInstalledApplications (PackageManager. GET_UNINSTALLED_PACKAGES );
  6. Collections. sort (listAppcations, new
  7. ApplicationInfo. DisplayNameComparator (pm); // sort
  8. List appInfos = new ArrayList (); // Save the filtered AppInfo
  9. // Filter Based on conditions
  10. Switch (filter ){
  11. Case FILTER_ALL_APP: // All Applications
  12. AppInfos. clear ();
  13. For (ApplicationInfo app: listAppcations ){
  14. If (app. packageName. equals ("com. android. appmanager") {// filter yourself
  15. Continue;
  16. }
  17. AppInfos. add (getAppInfo (app ));
  18. }
  19. Return appInfos;
  20. Case FILTER_SYSTEM_APP: // System Program
  21. AppInfos. clear ();
  22. For (ApplicationInfo app: listAppcations ){
  23. If (app. flags & ApplicationInfo. FLAG_SYSTEM )! = 0 ){
  24. If (app. packageName. equals ("com. android. appmanager" "font-family: Arial,
  25. Helvetica, sans-serif; ">) // wifi {// filter yourself
  26. Continue;
  27. }
  28. AppInfos. add (getAppInfo (app ));
  29. }
  30. }
  31. Return appInfos;
  32. Case FILTER_THIRD_APP: // third-party Application
  33. AppInfos. clear ();
  34. For (ApplicationInfo app: listAppcations ){
  35. // Non-system program
  36. If (app. flags & ApplicationInfo. FLAG_SYSTEM) <= 0 ){
  37. If (app. packageName. equals ("com. android. appmanager "))
  38. Continue;
  39. }
  40. AppInfos. add (getAppInfo (app ));
  41. }
  42. // It is a system program. After being manually updated by the user, the system program becomes a third-party application.
  43. Else if (app. flags & ApplicationInfo. FLAG_UPDATED_SYSTEM_APP )! = 0)
  44. {
  45. If (app. packageName. equals ("geeya. android. appmanage") {// filter yourself
  46. Continue;
  47. }
  48. AppInfos. add (getAppInfo (app ));
  49. }
  50. }
  51. Break;
  52. Default:
  53. Return null;
  54. }
  55. Return appInfos;
  56. } Copy the code
    AppInfo is a class defined by myself. It contains the package name, data area size, code area size, and other attributes of the application.
    Well, now let's get the data area size, cache area size, and code area size of the app package. here we need to use the reflection mechanism to get the hidden method of the PackageManager class getPackageSizeInfo (), the specific implementation of this method is implemented through the callback function. here we need to use the pile generated by the IPackageStatsObserver class.
    Java code

    1. // Bindler mechanism service class formed by aidl File

    2. Public class PkgSizeObserver extends IPackageStatsObserver. Stub {
    3. /***
    4. * Callback function,
    5. *
    6. * @ Param pStatus
    7. * The returned data is encapsulated in the PackageStats object.
    8. * @ Param succeeded
    9. * Indicates that the callback is successful.
    10. */
    11. @ Override
    12. Public void onGetStatsCompleted (PackageStats pStats, boolean succeeded)
    13. Throws RemoteException {
    14. Long cachesize; // cache size
    15. Long datasize; // data size
    16. Long codesize; // application size
    17. Long totalsize; // The total size.
    18. // System. out. println ("data start init! ");
    19. Synchronized (Integer. class ){
    20. Cachesize = pStats. cacheSize; // cache size
    21. Datasize = pStats. dataSize; // data size
    22. Codesize = pStats. codeSize; // application size
    23. Totalsize = cachesize + datasize + codesize;
    24. Message msg = mHandler. obtainMessage ();
    25. Msg. what = MSG_SIZE_CHANGE;
    26. Bundle bundle = new Bundle ();
    27. Bundle. putLong ("cachesize", cachesize );
    28. Bundle. putLong ("datasize", datasize );
    29. Bundle. putLong ("codesize", codesize );
    30. Bundle. putLong ("totalsize", totalsize );
    31. Bundle. putString ("packageName", pStats. packageName );
    32. Msg. obj = bundle;
    33. MHandler. sendMessage (msg );
    34. }
    35. }
    36. }
    37. // Obtain the size information of each apk, including the data zone, code zone, and cache zone.
    38. // Query the package size information
    39. Public void queryPacakgeSize (String pkgName) throws Exception {
    40. If (pkgName! = Null ){
    41. // Use the radiation mechanism to obtain the hidden function getPackageSizeInfo of the PackageManager class
    42. PackageManager pm = getPackageManager (); // get the pm object
    43. Try {
    44. // Obtain the hidden function through the reflection mechanism
    45. Method getPackageSizeInfo =
    46. Pm. getClass (). getDeclaredMethod ("getPackageSizeInfo", String. class,
    47. IPackageStatsObserver. class );
    48. GetPackageSizeInfo. invoke (pm, pkgName, new PkgSizeObserver ());
    49. } Catch (Exception ex ){
    50. // Log. e (TAG, "NoSuchMethodException ");
    51. Ex. printStackTrace ();
    52. Throw ex; // throw an exception
    53. }
    54. }
    55. } Copy the code
      This is the best way to encapsulate the app size data into messages for sending !!
      This section also describes how to convert long data into a file size format.
      Java code

      1. // System function, String Conversion long-String (kb)

      2. Private String formateFileSize (long size ){
      3. Return Formatter. formatFileSize (MainActivity. this, size );
      4. } Copy the code
        Well, now let's clear user data. Here we need to use the previously downloaded file IPackageDataObserver, which is the same as getting the app size and implemented through callback.
        Java code

        1. // CLEAR user data

        2. Class ClearUserDataObserver extends IPackageDataObserver. Stub {
        3. Public void onRemoveCompleted (final String packageName, final boolean
        4. Succeeded ){
        5. Final Message msg = mHandler. obtainMessage ();
        6. If (succeeded ){
        7. Msg. what = CLEAR_USER_DATA;
        8. } Else {
        9. Msg. what = NOT_CLEAR_USER_DATA;
        10. }
        11. MHandler2.sendMessage (msg );
        12. }
        13. }
        14. // Clear apk data
        15. Public void clearAppUserData (String pkgname ){
        16. // After testing, this method cannot be obtained through reflection. I have to write it like this and can only compile it in the source code.
        17. Pm. clearApplicationUserData (pkgname, new ClearUserDataObserver ());
        18. } Copy the code
          Okay. Now it's time to uninstall the program. Check the code.
          Java code

          1. // Uninstall apk

          2. Ublic void unInstallApp (String pkgname ){
          3. Log. e ("unInstallApp (String pkgname)", "pkgname is" + pkgname );
          4. Intent intent = new Intent ();
          5. // This action is defined by myself on the android framework layer. DELETE. HIDE indicates that the action is uninstalled directly. Without going through the native dialog of the system.
          6. Intent. setAction ("android. intent. action. DELETE. HIDE ");//
          7. The DELETE. HIDE action does not need to be confirmed by the system. Unmount directly!
          8. Uri packageURI = Uri. parse ("package:" + pkgname );
          9. Intent. setData (packageURI );
          10. StartActivity (intent); copy the code
            The apk management is almost the same. Now let's take a look at the management of running services.
            First, obtain the running service:
            Here, my RunningInfo is a class defined by myself. It mainly serves some attributes, such as the package name, uid, pid, and so on.
            Java code

            1. // Get the Running Service

            2. Public List getRunningService (){
            3. List runServiceList = am. getRunningServices (30 );
            4. List Services_List = new ArrayList ();//
            5. Save the AppInfo
            6. Log. e ("getRunningService. size = ",
            7. New Integer (runServiceList. size (). toString ());
            8. String pkgname = "";
            9. ApplicationInfo appByPkgName = null;
            10. For (RunningServiceInfo info: runServiceList ){
            11. Pkgname = info. service. getPackageName ();
            12. // System. out. println ("service package is:" + pkgname +
            13. // "Pid =" + info. pid); // the ID of the program
            14. // Filter out the services of these systems. Only the services installed by the user are displayed.
            15. If (pkgname. equals ("com. android. appmanager") {// filter yourself
            16. Continue;
            17. }
            18. Try {
            19. AppByPkgName = pm. getApplicationInfo (pkgname,
            20. PackageManager. GET_UNINSTALLED_PACKAGES); // The last parameter is generally 0.
            21. .
            22. } Catch (NameNotFoundException e ){
            23. // Log. e ("MainActivity 841 line", "appByPkgName =
            24. Pm. getApplicationInfo (pkgname, PackageManager. GET_UNINSTALLED_PACKAGES)
            25. Exception! ");
            26. E. printStackTrace ();
            27. }
            28. Services_List.add (getRunningInfo (appByPkgName ));//
            29. Services that contain the same package. Here, we only need to display one.
            30. }
            31. // Put it in the set file to filter out those with the same package name. Here, I have rewritten the compareTo method of RunningInfo. Your rule is:
            32. PkgName is equal. Two objects are equal!
            33. Set set = new HashSet ();
            34. For (RunningInfo x: Services_List ){
            35. Set. add (x );
            36. }
            37. For (RunningInfo y: set ){
            38. Services_List.add (y );
            39. }
            40. Return Services_List;
            41. } Copy the code
              After obtaining the running service, you can stop the service at will. The code for stopping the service is:
              Java code

              1. // Forcibly stop an app

              2. Ublic boolean stopApp (String pkgname ){
              3. Boolean flag = false;
              4. ActivityManager am = (ActivityManager)
              5. MContext. getSystemService (Context. ACTIVITY_SERVICE );
              6. Try {
              7. Method forceStopPackage;
              8. ForceStopPackage = am. getClass (). getDeclaredMethod ("forceStopPackage ",
              9. String. class); // reflection to obtain the hidden method (hide)
              10. ForceStopPackage. setAccessible (true); // obtain the value of the Private member variable
              11. ForceStopPackage. invoke (am, pkgname );
              12. Flag = true;
              13. } Catch (IllegalArgumentException e ){
              14. E. printStackTrace ();
              15. Flag = false;
              16. } Catch (IllegalAccessException e ){
              17. E. printStackTrace ();
              18. Flag = false;
              19. } Catch (InvocationTargetException e ){
              20. E. printStackTrace ();
              21. Flag = false;
              22. } Catch (SecurityException e ){
              23. E. printStackTrace ();
              24. Flag = false;
              25. } Catch (NoSuchMethodException e ){
              26. E. printStackTrace ();
              27. Flag = false;
              28. }
              29. Return flag; copy the code
                The reflection mechanism is also used to obtain hidden classes.
                At this point, the application management function is almost the same,
                The rest is just the interface and the processing process of the program. It should be okay!

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.