android 緩衝 清理

來源:互聯網
上載者:User

這裡說的清除是在軟體中清理其它程式的緩衝,有兩種。均用到反射這方面的知識,沒辦法,Android系統API把這些方法隱藏了。反射就不說了,不懂得可以自己百度,Google!

  一種帶root許可權的:
Class c1 = Class.forName("android.content.pm.IPackageDataObserver");
Method method = pm.getClass().getMethod("deleteApplicationCacheFiles", String.class,IPackageDataObserver.class);
method.invoke(pm, packageName,new IPackageDataObserver.Stub(){
@Override
public void onRemoveCompleted(String packageName,
boolean succeeded) throws RemoteException {
// TODO Auto-generated method stub
}
});
<uses-permission android:name="android.permission.DELETE_CACHE_FILES" />

  另外一種是不用許可權;一鍵清理:
private static long getEnvironmentSize()
    {
      File localFile = Environment.getDataDirectory();
      long l1;
      if (localFile == null)
        l1 = 0L;
      while (true)
      {
        
        String str = localFile.getPath();
        StatFs localStatFs = new StatFs(str);
        long l2 = localStatFs.getBlockSize();
        l1 = localStatFs.getBlockCount() * l2;
        return l1;
      }
    }

PackageManager pm = activity.getPackageManager();
Class[] arrayOfClass = new Class[2];
Class localClass2 = Long.TYPE;
arrayOfClass[0] = localClass2;
arrayOfClass[1] = IPackageDataObserver.class;
Method localMethod = pm.getClass().getMethod("freeStorageAndNotify", arrayOfClass);
Long localLong = Long.valueOf(getEnvironmentSize() - 1L);
Object[] arrayOfObject = new Object[2];
arrayOfObject[0] = localLong;
localMethod.invoke(pm,localLong,new IPackageDataObserver.Stub(){
  public void onRemoveCompleted(String packageName,boolean succeeded) throws RemoteException {
       // TODO Auto-generated method stub
}});
許可權:<uses-permission android:name="android.permission.CLEAR_APP_CACHE" />

  這也是一點點見解,還不是很成熟,希望懂的多的大牛們指出不足或者錯誤之處,大家共同學習一下。
可能會遇到IPackageDataObserver這個無法導進去,自己寫一個IPackageDataObserver.aidl,內容如下:
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); 
}放在src包下就行了。

 

相關文章

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

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.