Android教程網
  1. 首頁
  2. Android 技術
  3. Android 手機
  4. Android 系統教程
  5. Android 游戲
您现在的位置: Android教程網 >> Android系統教程 >  >> Android 技術 >> Android 開發實例

Android PendingIntent 與 Intent 的本質區別

編輯:Android 開發實例

在學習 AlarmManager 時,我們常常會遇到 PendingIntent。要理解它,得先從熟悉的 Intent 說起。

Intent 代表你的「意圖」。比如你想啟動某個 Activity,就會透過 Intent 描述它的某些特徵,讓系統找到並啟動它,而不是別的 Activity。當你調用 startActivity(intent) 時,這個 Activity 便立即被啟動。

而 PendingIntent 呢?「Pending」一詞,中文意為「待定、將來發生或來臨」。顧名思義,PendingIntent 並不像 Intent 那樣立即觸發,而是在合適的時機才會去啟動對應的 Intent。換句話說,這個 intent 不是由你的應用直接觸發,而是交給另一個應用(比如系統)在未來某個時刻代為觸發。

理解這個概念最生動的例子,莫過於 PackageInstaller 中的這段代碼:

private class ClearCacheReceiver extends BroadcastReceiver {
    public static final String INTENT_CLEAR_CACHE = "com.android.packageinstaller.CLEAR_CACHE";

    @Override
    public void onReceive(Context context, Intent intent) {
        Message msg = mHandler.obtainMessage(FREE_SPACE);
        msg.arg1 = (getResultCode() == 1) ? SUCCEEDED : FAILED;
        mHandler.sendMessage(msg);
    }
}

以及觸發清理空間的邏輯:

private void checkOutOfSpace(long size) {
    if (localLOGV) Log.i(TAG, "Checking for " + size + " number of bytes");
    if (mClearCacheReceiver == null) {
        mClearCacheReceiver = new ClearCacheReceiver();
    }

    registerReceiver(mClearCacheReceiver, new IntentFilter(ClearCacheReceiver.INTENT_CLEAR_CACHE));

    PendingIntent pi = PendingIntent.getBroadcast(this, 0,
            new Intent(ClearCacheReceiver.INTENT_CLEAR_CACHE), 0);

    mPm.freeStorage(size, pi.getIntentSender());
}

這裡的邏輯頗具代表性:應用先創建一個 PendingIntent,再把它交給 PackageManagerService。當系統完成緩存清理後,便會透過這個 PendingIntent「回頭」通知原應用。相應地,在 PackageManagerService 中:

public void freeStorageAndNotify(final long freeStorageSize, final IPackageDataObserver observer) {
    mContext.enforceCallingOrSelfPermission(
            android.Manifest.permission.CLEAR_APP_CACHE, null);
    // 清理緩存可能耗時,放入異步隊列
    mHandler.post(new Runnable() {
        public void run() {
            mHandler.removeCallbacks(this);
            int retCode = -1;
            if (mInstaller != null) {
                retCode = mInstaller.freeCache(freeStorageSize);
                if (retCode < 0) {
                    Slog.w(TAG, "Couldn't clear application caches");
                }
            }
            if (observer != null) {
                try {
                    observer.onRemoveCompleted(null, (retCode >= 0));
                } catch (RemoteException e) {
                    Slog.w(TAG, "RemoveException when invoking call back");
                }
            }
        }
    });
}

由此不難看出,PendingIntent 本質上是一份「授權憑證」——它把「未來要執行某個 Intent 的權利」打包授權給了其他應用或系統組件。這種延遲、跨進程的觸發機制,正是它區別於普通 Intent 的核心所在。

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