Intent otherApp = new Intent(Action, Uri);
startActivity(otherApp);
如果,用户没有安装所需要的应用程序,在这里将会抛出异常并且ForceClose。所以我们需要在调用之前验证所需的Action是否指向一个Activity。
以下是Google官方博客中给出的一个验证:
/**
* Indicates whether the specified action can be used as an intent. This
* method queries the package manager for installed packages that can
* respond to an intent with the specified action. If no suitable package is
* found, this method returns false.
*
* @param context The application's environment.
* @param action The Intent action to check for availability.
*
* @return True if an Intent with the specified action can be sent and
* responded to, false otherwise.
*/
public static boolean isIntentAvailable(Context context, String action) {
final PackageManager packageManager = context.getPackageManager();
final Intent intent = new Intent(action);
List
packageManager.queryIntentActivities(intent,
PackageManager.MATCH_DEFAULT_ONLY);
return list.size() > 0;
}
我们可以对其进行扩展,增加Uri参数,以便匹配对URI进行的操作。
/**
* Indicates whether the specified action can be used as an intent. This
* method queries the package manager for installed packages that can
* respond to an intent with the specified action. If no suitable package is
* found, this method returns false.
*
* @param context The application's environment.
* @param action The Intent action to check for availability.
* @param uri The Intent Data Uri.
*
* @return True if an Intent with the specified action can be sent and
* responded to, false otherwise.
*/
public static boolean isIntentAvailable(Context context, String action, Uri uri) {
final PackageManager packageManager = context.getPackageManager();
final Intent intent = new Intent(action, uri);
List
packageManager.queryIntentActivities(intent,
PackageManager.MATCH_DEFAULT_ONLY);
return list.size() > 0;
}
仍然没有解决的是,这里只查询Filter中Category为android.intent.category.DEFAULT的Activity。
No comments:
Post a Comment