TShopping
標題:
android application更新廣播定義和接收
[打印本頁]
作者:
woff
時間:
2015-10-6 23:17
標題:
android application更新廣播定義和接收
android自帶的設置中有application的管理這個功能,包含顯示,卸載等操作。application分為本地應用和sdcard應用。
本地應用有添加,刪除和更新,監控的方式是通過廣播來執行,具體廣播註冊代碼如下:
IntentFilter filter = new IntentFilter(Intent.ACTION_PACKAGE_ADDED);
filter.addAction(Intent.ACTION_PACKAGE_REMOVED);
filter.addAction(Intent.ACTION_PACKAGE_CHANGED);
filter.addDataScheme( "package" );
mContext.registerReceiver( this , filter);
複製代碼
在接到廣播時,可以獲取到變化的application的包名,獲取包名代碼如下:
String actionStr = intent.getAction();
if (Intent.ACTION_PACKAGE_ADDED.equals(actionStr)) {
Uri data = intent.getData();
String pkgName = data.getEncodedSchemeSpecificPart();
addPackage(pkgName);
} else if (Intent.ACTION_PACKAGE_REMOVED.equals(actionStr)) {
Uri data = intent.getData();
String pkgName = data.getEncodedSchemeSpecificPart();
removePackage(pkgName);
} else if (Intent.ACTION_PACKAGE_CHANGED.equals(actionStr)) {
Uri data = intent.getData();
String pkgName = data.getEncodedSchemeSpecificPart();
invalidatePackage(pkgName);
}
複製代碼
安裝在sdcard中的application比較特殊,sdcard掛載的時候,要顯示安裝的application。sdcard卸載的時候,不去顯示安裝的application。
可以通過廣播的方式判定sdcard中的application是否可以available。具體註冊廣播代碼如下:
IntentFilter sdFilter = new IntentFilter();
sdFilter.addAction(Intent.ACTION_EXTERNAL_APPLICATIONS_AVAILABLE);
sdFilter.addAction(Intent.ACTION_EXTERNAL_APPLICATIONS_UNAVAILABLE);
mContext.registerReceiver( this , sdFilter);
複製代碼
接收廣播時,可以獲取sdcard中的application中的包名,具體代碼如下:
if (Intent.ACTION_EXTERNAL_APPLICATIONS_AVAILABLE.equals(actionStr) ||
Intent.ACTION_EXTERNAL_APPLICATIONS_UNAVAILABLE.equals(actionStr)) {
// When applications become available or unavailable (perhaps because
// the SD card was inserted or ejected) we need to refresh the
// AppInfo with new label, icon and size information as appropriate
// given the newfound (un)availability of the application.
// A simple way to do that is to treat the refresh as a package
// removal followed by a package addition.
String pkgList[] = intent.getStringArrayExtra(Intent.EXTRA_CHANGED_PACKAGE_LIST);
if (pkgList == null || pkgList.length == 0 ) {
// Ignore
return ;
}
boolean avail = Intent.ACTION_EXTERNAL_APPLICATIONS_AVAILABLE.equals(actionStr);
if (avail) {
for (String pkgName : pkgList) {
invalidatePackage(pkgName);
}
}
}
複製代碼
歡迎光臨 TShopping (http://www.tshopping.com.tw/)
Powered by Discuz! X3.2