歡迎來到Linux教程網
Linux教程網
Linux教程網
Linux教程網
Linux教程網 >> Linux編程 >> Linux編程 >> Android啟動Activity前確定Intent 能否解析

Android啟動Activity前確定Intent 能否解析

日期:2017/3/1 9:34:29   编辑:Linux編程

在自己的應用程序中利用第三方應用程序的Activity 和Service 是十分方便的,但是,你無法保證用戶設備上安裝了特定的某個應用程序,或者設備上有能夠處理你的請求的應用程序。

因此,在調用startActivity 之前,確定調用是否可以解析為一個Activity 是一種很好的做法。

通過調用Intent 的resolveActivity 方法,並向該方法傳入包管理器,可以對包管理器進行查詢,

確定是否有Activity 能夠啟動以響應該Intent。

if (somethingWeird && itDontLookGood) {
// Createthe impliciy Intent to use to start a new Activity.
Intentintent =
newIntent(Intent.ACTION_DIAL, Uri.parse("tel:555-2368"));
// Check ifan Activity exists to perform this action.
PackageManager pm = getPackageManager();
ComponentName cn = intent.resolveActivity(pm);
if (cn ==null) {
// If thereis no Activity available to perform the action
// Check tosee if the Google Play Store is available.
UrimarketUri =
Uri.parse("market://search?q=pname:com.myapp.packagename");
IntentmarketIntent = new
Intent(Intent.ACTION_VIEW).setData(marketUri);
// If theGoogle Play Store is available, use it to download anapplication
// capableof performing the required action. Otherwise log an
//error.
if(marketIntent.resolveActivity(pm) != null)
startActivity(marketIntent);
else
Log.d(TAG,"Market client not available.");
}
else
startActivity(intent);
}

更多Android相關信息見Android 專題頁面 http://www.linuxidc.com/topicnews.aspx?tid=11

Copyright © Linux教程網 All Rights Reserved