TShopping

標題: android application更新廣播定義和接收 [打印本頁]

作者: woff    時間: 2015-10-6 23:17
標題: android application更新廣播定義和接收
android自帶的設置中有application的管理這個功能,包含顯示,卸載等操作。application分為本地應用和sdcard應用。
本地應用有添加,刪除和更新,監控的方式是通過廣播來執行,具體廣播註冊代碼如下:
IntentFilter filter = new IntentFilter(Intent.ACTION_PACKAGE_ADDED);
  1. filter.addAction(Intent.ACTION_PACKAGE_REMOVED);  
  2. filter.addAction(Intent.ACTION_PACKAGE_CHANGED);  
  3. filter.addDataScheme( "package" );  
  4. mContext.registerReceiver( this , filter);
複製代碼


在接到廣播時,可以獲取到變化的application的包名,獲取包名代碼如下:
  1. String actionStr = intent.getAction();  
  2.          if  (Intent.ACTION_PACKAGE_ADDED.equals(actionStr)) {  
  3.              Uri data = intent.getData();  
  4.              String pkgName = data.getEncodedSchemeSpecificPart();  
  5.              addPackage(pkgName);  
  6.          }  else  if  (Intent.ACTION_PACKAGE_REMOVED.equals(actionStr)) {  
  7.              Uri data = intent.getData();  
  8.              String pkgName = data.getEncodedSchemeSpecificPart();  
  9.              removePackage(pkgName);  
  10.          }  else  if  (Intent.ACTION_PACKAGE_CHANGED.equals(actionStr)) {  
  11.              Uri data = intent.getData();  
  12.              String pkgName = data.getEncodedSchemeSpecificPart();  
  13.              invalidatePackage(pkgName);  
  14.          }  
複製代碼


安裝在sdcard中的application比較特殊,sdcard掛載的時候,要顯示安裝的application。sdcard卸載的時候,不去顯示安裝的application。

      可以通過廣播的方式判定sdcard中的application是否可以available。具體註冊廣播代碼如下:

  1. IntentFilter sdFilter =  new  IntentFilter();  
  2.       sdFilter.addAction(Intent.ACTION_EXTERNAL_APPLICATIONS_AVAILABLE);  
  3.       sdFilter.addAction(Intent.ACTION_EXTERNAL_APPLICATIONS_UNAVAILABLE);  
  4.       mContext.registerReceiver( this , sdFilter);  
複製代碼


接收廣播時,可以獲取sdcard中的application中的包名,具體代碼如下:

     if (Intent.ACTION_EXTERNAL_APPLICATIONS_AVAILABLE.equals(actionStr) ||
  1. Intent.ACTION_EXTERNAL_APPLICATIONS_UNAVAILABLE.equals(actionStr)) {  
  2.     // When applications become available or unavailable (perhaps because  
  3.     // the SD card was inserted or ejected) we need to refresh the  
  4.     // AppInfo with new label, icon and size information as appropriate  
  5.     // given the newfound (un)availability of the application.  
  6.     // A simple way to do that is to treat the refresh as a package  
  7.     // removal followed by a package addition.  
  8.     String pkgList[] = intent.getStringArrayExtra(Intent.EXTRA_CHANGED_PACKAGE_LIST);  
  9.     if  (pkgList ==  null  || pkgList.length ==  0 ) {  
  10.         // Ignore  
  11.         return ;  
  12.     }  
  13.     boolean  avail = Intent.ACTION_EXTERNAL_APPLICATIONS_AVAILABLE.equals(actionStr);  
  14.     if  (avail) {  
  15.         for  (String pkgName : pkgList) {  
  16.             invalidatePackage(pkgName);  
  17.         }  
  18.     }  
  19. }  
複製代碼





歡迎光臨 TShopping (http://www.tshopping.com.tw/) Powered by Discuz! X3.2