編輯:關於 Android 程式設計
光看 Android 設定 → 應用程式 → 選擇某個 App,裡頭就有「清除快取」這個按鈕。這個功能要怎麼自己實作?答案藏在 Setting 的原始碼裡。

要取得快取大小,關鍵方法是 PackageManager.getPackageSizeInfo()。但麻煩的是——這個方法是 @hide 的,不對外公開。SDK 中看不到它,直接呼叫會編譯失敗。
解法是反射。 while 不優雅,但這是拿到系統內部資訊的常見途徑。
package com.wang.clearcache;
import java.lang.reflect.Method;
import android.os.Bundle;
import android.os.RemoteException;
import android.app.Activity;
import android.content.pm.IPackageStatsObserver;
import android.content.pm.PackageManager;
import android.content.pm.PackageStats;
public class MainActivity extends Activity {
private PackageManager pm;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
pm = getPackageManager();
try {
Method method = PackageManager.class.getMethod(
"getPackageSizeInfo",
new Class[] { String.class, IPackageStatsObserver.class });
method.invoke(pm, new Object[] {
"com.wang.clearcache",
new IPackageStatsObserver.Stub() {
@Override
public void onGetStatsCompleted(PackageStats pStats,
boolean succeeded)
throws RemoteException {
long cachesize = pStats.cacheSize;
long codesize = pStats.codeSize;
long datasize = pStats.dataSize;
System.out.println("cachesize: " + cachesize);
System.out.println("codesize: " + codesize);
System.out.println("datasize: " + datasize);
}
}
});
} catch (Exception e) {
e.printStackTrace();
}
}
}
取得快取資訊需要 android.permission.GET_PACKAGE_SIZE:
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="https://schemas.android.com/apk/res/android"
package="com.wang.clearcache"
android:versionCode="1"
android:versionName="1.0">
<uses-sdk android:minSdkVersion="8" android:targetSdkVersion="17" />
<uses-permission android:name="android.permission.GET_PACKAGE_SIZE" />
<application>
<activity android:name=".MainActivity">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
</application>
</manifest>
程式中用到了 IPackageStatsObserver 與 PackageStats,兩者都屬於系統內部 API,SDK 沒有提供,必須自己建立對應的 aidl 檔案放到 src/android/content/pm/ 下。
IPackageStatsObserver.aidl
/*
** Copyright 2007, The Android Open Source Project
**
** Licensed under the Apache License, Version 2.0 (the "License");
** you may not use this file except in compliance with the License.
** You may obtain a copy of the License at
**
** https://www.apache.org/licenses/LICENSE-2.0
**
** Unless required by applicable law or agreed to in writing, software
** distributed under the License is distributed on an "AS IS" BASIS,
** WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
** See the License for the specific language governing permissions and
** limitations under the License.
*/
package android.content.pm;
import android.content.pm.PackageStats;
/**
* 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.
* {@hide}
*/
oneway interface IPackageStatsObserver {
void onGetStatsCompleted(in PackageStats pStats, boolean succeeded);
}
PackageStats.aidl
/* ** Copyright 2007, The Android Open Source Project ** ** Licensed under the Apache License, Version 2.0 (the "License"); ** you may not use this file except in compliance with the License. ** You may obtain a copy of the License at ** ** https://www.apache.org/licenses/LICENSE-2.0 ** ** Unless required by applicable law or agreed to in writing, software ** distributed under the License is distributed on an "AS IS" BASIS, ** WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. ** See the License for the specific language governing permissions and ** limitations under the License. */ package android.content.pm; parcelable PackageStats;
注意 oneway 這個修飾詞:它表示呼叫端不會等待回傳,適用於「通知型」的跨進行情況,能避免呼叫端被遠端服務阻塞。

本文示範的是查詢大小。若要進一步真的把快取刪掉,系統提供的 API 是 PackageManager.freeStorageAndNotify() 與 freeStorage(),同樣是隱藏 API,需要反射呼叫,而且需要 CLEAR_APP_CACHE 權限(signature 等級)。
如果目標只是清掉自己 App 的快取,其實完全不需要這套反射把戲——Context.getCacheDir() 拿到的目錄,自己的 App 有完整權限,直接遞迴刪除檔案即可:
public static void clearCache(Context context) {
deleteFiles(context.getCacheDir());
// 外部快取(API 19+)
File external = context.getExternalCacheDir();
if (external != null) {
deleteFiles(external);
}
}
private static void deleteFiles(File dir) {
File[] children = dir.listFiles();
if (children != null) {
for (File child : children) {
if (child.isDirectory()) {
deleteFiles(child);
} else {
child.delete();
}
}
}
}
本文的反射 + 隱藏 AIDL 手法在當時的 Android 版本上行得通,但在現代系統上會遇到幾個硬性障礙,值得先了解再決定要不要走這條路:
onGetStatsCompleted() 拿到的數值會是全 0。只有系統簽章的應用(或放在 /system/priv-app 的)才真的拿得到。<queries> 明確宣告,否則 PackageManager 查詢會被過濾。IPackageStatsObserver 是 oneway,回呼的執行緒與時機無法預期,更新 UI 前要記得切回主執行緒。結論:如果你的需求是「清理自己 App 的快取」,用上面的 deleteFiles() 就足夠了,簡單又穩定;若是要做一個類似「手機清理大師」的工具去清其他 App,那麼無論用哪種手段,都需要使用者取得 Root 或走 Device Admin / 系統簽章途徑,這已不是單純的 API 問題。
Android 讓 Button 置中:gravity 與 RelativeLayout 的搭配
按鈕置中看似理所當然,實際寫起來卻常出錯,原因在於許多人把 gravity 與 layout_gravity 搞混了。前者決定「元件內部內容」的對齊方式,後者才決定「元件
Android 泡泡聊天介面實作教學(附完整程式碼)
本文透過一個完整範例,帶大家動手打造類似即時通訊軟體的「泡泡」對話介面。點擊發送按鈕後,輸入的文字會立刻以對話框的形式呈現在畫面上。 這個實作是在網路上既有範例的基礎上
Android WebView 錯誤碼處理方式
WebView 載入網頁時,可能遇到 404、401、403 或其他錯誤。若直接顯示預設錯誤頁,使用者體驗通常不佳,因此可攔截錯誤並顯示自訂內容。自訂錯誤頁一種做法是在
Android 屬性動畫(下):Evaluator、Keyframe、布局動畫與轉場動畫
前言 上一篇我們把屬性動畫的實作骨幹講完了:怎麼寫一個動畫、怎麼在沒有現成屬性的情況下自行補上屬性,以及怎麼用 ValueAnimator 驅動動畫。本篇接著把剩下的幾