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

Android 監聽安裝、替換與卸載廣播實作

編輯:關於 Android 程式設計

相關廣播 action

Android 會透過 Package 相關廣播通知安裝狀態,例如 ACTION_PACKAGE_ADDED、ACTION_PACKAGE_REPLACED、ACTION_PACKAGE_REMOVED。部分 action 不會通知正在處理該動作的程式本身。

註冊廣播

<receiver android:name='.AppInstallReceiver'>
  <intent-filter>
    <action android:name='android.intent.action.PACKAGE_ADDED' />
    <action android:name='android.intent.action.PACKAGE_REPLACED' />
    <action android:name='android.intent.action.PACKAGE_REMOVED' />
    <data android:scheme='package' />
  </intent-filter>
</receiver>

接收並判斷

public void onReceive(Context context, Intent intent) {
  String action = intent.getAction();
  String pkg = intent.getData().getSchemeSpecificPart();
  if (Intent.ACTION_PACKAGE_ADDED.equals(action)) { }
  if (Intent.ACTION_PACKAGE_REMOVED.equals(action)) { }
  if (Intent.ACTION_PACKAGE_REPLACED.equals(action)) { }
}

藉由 Intent 的 action 與 data,即可辨識安裝、移除或版本替換,並進一步更新應用內的狀態。

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