Android教程網
  1. 首頁
  2. Android 技術
  3. Android 手機
  4. Android 系統教程
  5. Android 游戲

Android 清理快取功能實作(含反射呼叫與 AIDL)

編輯:關於 Android 程式設計

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

核心:getPackageSizeInfo

要取得快取大小,關鍵方法是 PackageManager.getPackageSizeInfo()。但麻煩的是——這個方法是 @hide 的,不對外公開。SDK 中看不到它,直接呼叫會編譯失敗。

解法是反射。 while 不優雅,但這是拿到系統內部資訊的常見途徑。

Java 程式碼

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>

需要的兩個 AIDL 檔案

程式中用到了 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 版本上行得通,但在現代系統上會遇到幾個硬性障礙,值得先了解再決定要不要走這條路:

  • GET_PACKAGE_SIZE 是 signature 權限。普通第三方 App 申請了也不會被核發,onGetStatsCompleted() 拿到的數值會是全 0。只有系統簽章的應用(或放在 /system/priv-app 的)才真的拿得到。
  • 查詢其他 App 的資訊受 Android 11 的套件可見性限制。需要在 Manifest 用 <queries> 明確宣告,否則 PackageManager 查詢會被過濾。
  • 隱藏 API 從 Android 9 起被黑名單攔截。非官方 SDK 的反射呼叫會被執行期攔下,只有限定白名單中的 API 可用。
  • 跨進程 Binder 邊界。若在非 UI 執行緒呼叫,注意 IPackageStatsObserver 是 oneway,回呼的執行緒與時機無法預期,更新 UI 前要記得切回主執行緒。

結論:如果你的需求是「清理自己 App 的快取」,用上面的 deleteFiles() 就足夠了,簡單又穩定;若是要做一個類似「手機清理大師」的工具去清其他 App,那麼無論用哪種手段,都需要使用者取得 Root 或走 Device Admin / 系統簽章途徑,這已不是單純的 API 問題。

  1. 上一篇文章:
  2. 下一篇文章:
Copyright © Android教程網 All Rights Reserved