Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
462 views
in Technique[技术] by (71.8m points)

caching - How to delete other applications cache from our android app?

I'm trying to develop an android app that could erase others application cache data, I tried to browse through all blogs but none of them worked for me, I can able to clear my application's cache by the following code

File cache = getCacheDir();
            File appDir = new File(cache.getParent());
            if (appDir.exists()) 
            {
                String[] children = appDir.list();
                for (String s : children) 
                {
                    if (!s.equals("lib"))
                    {
                        deleteDir(new File(appDir, s));
                        Toast.makeText(DroidCleaner.this, "Cache Cleaned", Toast.LENGTH_LONG).show();
                        Log.i("TAG", "**************** File /data/data/APP_PACKAGE/" + s + " DELETED *******************");
                    }
                }
            }

public static boolean deleteDir(File dir) 
{
    if (dir != null && dir.isDirectory()) 
    {
        String[] children = dir.list();
        for (int i = 0; i < children.length; i++) 
        {
            boolean success = deleteDir(new File(dir, children[i]));
            if (!success) 
            {
                return false;
            }
        }
    }
    return dir.delete();
}

My manifest code

<uses-permission android:name="android.permission.CLEAR_APP_CACHE"/>

I tested the code on 2.2, 2.3 and 4.0

and after seeing the post in the following link Android: Clear Cache of All Apps?

I changed my code to

PackageManager  pm = getPackageManager();
// Get all methods on the PackageManager
Method[] methods = pm.getClass().getDeclaredMethods();
for (Method m : methods) {
    if (m.getName().equals("freeStorage")) {
        // Found the method I want to use
        try {
            long desiredFreeStorage = 8 * 1024 * 1024 * 1024; // Request for 8GB of free space
        m.invoke(pm, desiredFreeStorage , null);
    } catch (Exception e) {
        // Method invocation failed. Could be a permission problem
    }
    break;
   }
}

I want to clear other application's cache, can any body please help me, please correct me if I'm wrong, Thanks in advance.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

This API is no more supported in API 23, that is Marshmallow. Permission is deprecated in Marshmallow.

But there is another way by asking run time permission for Accessories. Try app All-in-one Toolbox from play store. This app is able to clear other apps cache even in Marshmallow. Then it should be possible for us to do so.

I am researching on this. Once I found the solution, I will update the answer. Thanks.


OLD ANSWER IS AS FOLLOWS


I used the following code and now I'm able to clear all application's cache without rooting, it's working perfectly for me,

private static final long CACHE_APP = Long.MAX_VALUE;
private CachePackageDataObserver mClearCacheObserver;

btnCache.setOnClickListener(new View.OnClickListener() {

        @Override
        public void onClick(View v) {
            clearCache();
        }
    });//End of btnCache Anonymous class

void clearCache() 
{
    if (mClearCacheObserver == null) 
    {
      mClearCacheObserver=new CachePackageDataObserver();
    }

    PackageManager mPM=getPackageManager();

    @SuppressWarnings("rawtypes")
    final Class[] classes= { Long.TYPE, IPackageDataObserver.class };

    Long localLong=Long.valueOf(CACHE_APP);

    try 
    {
      Method localMethod=
          mPM.getClass().getMethod("freeStorageAndNotify", classes);

      /*
       * Start of inner try-catch block
       */
      try 
      {
        localMethod.invoke(mPM, localLong, mClearCacheObserver);
      }
      catch (IllegalArgumentException e) 
      {
        // TODO Auto-generated catch block
        e.printStackTrace();
      }
      catch (IllegalAccessException e) 
      {
        // TODO Auto-generated catch block
        e.printStackTrace();
      }
      catch (InvocationTargetException e)
      {
        // TODO Auto-generated catch block
        e.printStackTrace();
      }
      /*
       * End of inner try-catch block
       */
    }
    catch (NoSuchMethodException e1)
    {
      // TODO Auto-generated catch block
      e1.printStackTrace();
    }
}//End of clearCache() method

private class CachePackageDataObserver extends IPackageDataObserver.Stub 
{
    public void onRemoveCompleted(String packageName, boolean succeeded) 
    {

    }//End of onRemoveCompleted() method
}//End of CachePackageDataObserver instance inner class

And also create a pacakge in your src folder with the name android.content.pm inside that package create a file in the name IPackageDataObserver.aidl and paste the following code to it

package android.content.pm;

/**
 * API for package data change related callbacks from the Package Manager.
 * Some usage scenarios include deletion of cache directory, generate
 * statistics related to code, data, cache usage(TODO)
 * {@hide}
 */
oneway interface IPackageDataObserver {
    void onRemoveCompleted(in String packageName, boolean succeeded);
}

and in your manifest make sure you used the following code

<uses-permission android:name="android.permission.CLEAR_APP_CACHE"/>

If you guys find any problem feel free to contact me, Thanks.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...