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
- // Add a filter to get all programs, system programs, and programs installed by the user
- Private List queryFilterAppInfo (int filter ){
- // Query all installed applications
- List listAppcations =
- Pm. getInstalledApplications (PackageManager. GET_UNINSTALLED_PACKAGES );
- Collections. sort (listAppcations, new
- ApplicationInfo. DisplayNameComparator (pm); // sort
- List appInfos = new ArrayList (); // Save the filtered AppInfo
- // Filter Based on conditions
- Switch (filter ){
- Case FILTER_ALL_APP: // All Applications
- AppInfos. clear ();
- For (ApplicationInfo app: listAppcations ){
- If (app. packageName. equals ("com. android. appmanager") {// filter yourself
- Continue;
- }
- AppInfos. add (getAppInfo (app ));
- }
- Return appInfos;
- Case FILTER_SYSTEM_APP: // System Program
- AppInfos. clear ();
- For (ApplicationInfo app: listAppcations ){
- If (app. flags & ApplicationInfo. FLAG_SYSTEM )! = 0 ){
- If (app. packageName. equals ("com. android. appmanager" "font-family: Arial,
- Helvetica, sans-serif; ">) // wifi {// filter yourself
- Continue;
- }
- AppInfos. add (getAppInfo (app ));
- }
- }
- Return appInfos;
- Case FILTER_THIRD_APP: // third-party Application
- AppInfos. clear ();
- For (ApplicationInfo app: listAppcations ){
- // Non-system program
- If (app. flags & ApplicationInfo. FLAG_SYSTEM) <= 0 ){
- If (app. packageName. equals ("com. android. appmanager "))
- Continue;
- }
- AppInfos. add (getAppInfo (app ));
- }
- // It is a system program. After being manually updated by the user, the system program becomes a third-party application.
- Else if (app. flags & ApplicationInfo. FLAG_UPDATED_SYSTEM_APP )! = 0)
- {
- If (app. packageName. equals ("geeya. android. appmanage") {// filter yourself
- Continue;
- }
- AppInfos. add (getAppInfo (app ));
- }
- }
- Break;
- Default:
- Return null;
- }
- Return appInfos;
- } 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
- // Bindler mechanism service class formed by aidl File
- Public class PkgSizeObserver extends IPackageStatsObserver. Stub {
- /***
- * Callback function,
- *
- * @ Param pStatus
- * The returned data is encapsulated in the PackageStats object.
- * @ Param succeeded
- * Indicates that the callback is successful.
- */
- @ Override
- Public void onGetStatsCompleted (PackageStats pStats, boolean succeeded)
- Throws RemoteException {
- Long cachesize; // cache size
- Long datasize; // data size
- Long codesize; // application size
- Long totalsize; // The total size.
- // System. out. println ("data start init! ");
- Synchronized (Integer. class ){
- Cachesize = pStats. cacheSize; // cache size
- Datasize = pStats. dataSize; // data size
- Codesize = pStats. codeSize; // application size
- Totalsize = cachesize + datasize + codesize;
- Message msg = mHandler. obtainMessage ();
- Msg. what = MSG_SIZE_CHANGE;
- Bundle bundle = new Bundle ();
- Bundle. putLong ("cachesize", cachesize );
- Bundle. putLong ("datasize", datasize );
- Bundle. putLong ("codesize", codesize );
- Bundle. putLong ("totalsize", totalsize );
- Bundle. putString ("packageName", pStats. packageName );
- Msg. obj = bundle;
- MHandler. sendMessage (msg );
- }
- }
- }
- // Obtain the size information of each apk, including the data zone, code zone, and cache zone.
- // Query the package size information
- Public void queryPacakgeSize (String pkgName) throws Exception {
- If (pkgName! = Null ){
- // Use the radiation mechanism to obtain the hidden function getPackageSizeInfo of the PackageManager class
- PackageManager pm = getPackageManager (); // get the pm object
- Try {
- // Obtain the hidden function through the reflection mechanism
- Method getPackageSizeInfo =
- Pm. getClass (). getDeclaredMethod ("getPackageSizeInfo", String. class,
- IPackageStatsObserver. class );
- GetPackageSizeInfo. invoke (pm, pkgName, new PkgSizeObserver ());
- } Catch (Exception ex ){
- // Log. e (TAG, "NoSuchMethodException ");
- Ex. printStackTrace ();
- Throw ex; // throw an exception
- }
- }
- } 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
- // System function, String Conversion long-String (kb)
- Private String formateFileSize (long size ){
- Return Formatter. formatFileSize (MainActivity. this, size );
- } 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
- // CLEAR user data
- Class ClearUserDataObserver extends IPackageDataObserver. Stub {
- Public void onRemoveCompleted (final String packageName, final boolean
- Succeeded ){
- Final Message msg = mHandler. obtainMessage ();
- If (succeeded ){
- Msg. what = CLEAR_USER_DATA;
- } Else {
- Msg. what = NOT_CLEAR_USER_DATA;
- }
- MHandler2.sendMessage (msg );
- }
- }
- // Clear apk data
- Public void clearAppUserData (String pkgname ){
- // 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.
- Pm. clearApplicationUserData (pkgname, new ClearUserDataObserver ());
- } Copy the code
Okay. Now it's time to uninstall the program. Check the code.
Java code
- // Uninstall apk
- Ublic void unInstallApp (String pkgname ){
- Log. e ("unInstallApp (String pkgname)", "pkgname is" + pkgname );
- Intent intent = new Intent ();
- // 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.
- Intent. setAction ("android. intent. action. DELETE. HIDE ");//
- The DELETE. HIDE action does not need to be confirmed by the system. Unmount directly!
- Uri packageURI = Uri. parse ("package:" + pkgname );
- Intent. setData (packageURI );
- 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
- // Get the Running Service
- Public List getRunningService (){
- List runServiceList = am. getRunningServices (30 );
- List Services_List = new ArrayList ();//
- Save the AppInfo
- Log. e ("getRunningService. size = ",
- New Integer (runServiceList. size (). toString ());
- String pkgname = "";
- ApplicationInfo appByPkgName = null;
- For (RunningServiceInfo info: runServiceList ){
- Pkgname = info. service. getPackageName ();
- // System. out. println ("service package is:" + pkgname +
- // "Pid =" + info. pid); // the ID of the program
- // Filter out the services of these systems. Only the services installed by the user are displayed.
- If (pkgname. equals ("com. android. appmanager") {// filter yourself
- Continue;
- }
- Try {
- AppByPkgName = pm. getApplicationInfo (pkgname,
- PackageManager. GET_UNINSTALLED_PACKAGES); // The last parameter is generally 0.
- .
- } Catch (NameNotFoundException e ){
- // Log. e ("MainActivity 841 line", "appByPkgName =
- Pm. getApplicationInfo (pkgname, PackageManager. GET_UNINSTALLED_PACKAGES)
- Exception! ");
- E. printStackTrace ();
- }
- Services_List.add (getRunningInfo (appByPkgName ));//
- Services that contain the same package. Here, we only need to display one.
- }
- // 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:
- PkgName is equal. Two objects are equal!
- Set set = new HashSet ();
- For (RunningInfo x: Services_List ){
- Set. add (x );
- }
- For (RunningInfo y: set ){
- Services_List.add (y );
- }
- Return Services_List;
- } Copy the code
After obtaining the running service, you can stop the service at will. The code for stopping the service is:
Java code
- // Forcibly stop an app
- Ublic boolean stopApp (String pkgname ){
- Boolean flag = false;
- ActivityManager am = (ActivityManager)
- MContext. getSystemService (Context. ACTIVITY_SERVICE );
- Try {
- Method forceStopPackage;
- ForceStopPackage = am. getClass (). getDeclaredMethod ("forceStopPackage ",
- String. class); // reflection to obtain the hidden method (hide)
- ForceStopPackage. setAccessible (true); // obtain the value of the Private member variable
- ForceStopPackage. invoke (am, pkgname );
- Flag = true;
- } Catch (IllegalArgumentException e ){
- E. printStackTrace ();
- Flag = false;
- } Catch (IllegalAccessException e ){
- E. printStackTrace ();
- Flag = false;
- } Catch (InvocationTargetException e ){
- E. printStackTrace ();
- Flag = false;
- } Catch (SecurityException e ){
- E. printStackTrace ();
- Flag = false;
- } Catch (NoSuchMethodException e ){
- E. printStackTrace ();
- Flag = false;
- }
- 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!