Intent.resolveActivity

来源:互联网 发布:java自动生成代码原理 编辑:程序博客网 时间:2024/06/10 22:16

详解1:

在自己的应用程序中利用第三方应用程序的Activity和Service是十分方便的,但是你无法保证用户设备上安装了特定的某个应用软件,或者设备上有能够处理你的Intent请求的程序。

 因此,在启动第三方APK里的Activity之前,确定调用是否可以解析为一个Activity是一种很好的做法。

通过Intent的resolveActivity方法,并想该方法传入包管理器可以对包管理器进行查询以确定是否有Activity能够启动该Intent:

[java] view plain copy
  1. // Create the impliciy Intent to use to start a new Activity.  
  2. Intent intent = new Intent(Intent.ACTION_DIAL, Uri.parse("tel:555-2368"));  
  3. // Check if an Activity exists to perform this action.  
  4. PackageManager pm = context.getPackageManager();  
  5. ComponentName cn = intent.resolveActivity(pm);  
  6. if (cn == null) {  
  7.     // If there is no Activity available to perform the action  
  8.     // Check to see if the Google Play Store is available.  
  9.     Uri marketUri = Uri.parse("market://search?q=pname:com.myapp.packagename");  
  10.     Intent marketIntent = new Intent(Intent.ACTION_VIEW).setData(marketUri);  
  11.     // If the Google Play Store is available, use it to download an application  
  12.     // capable of performing the required action. Otherwise log an error.  
  13.     if (marketIntent.resolveActivity(pm) != null) {  
  14.         context.startActivity(marketIntent);  
  15.     } else {  
  16.         Log.d(TAG, "Market client not available.");  
  17.     }  
  18. else{  
  19.     context.startActivity(intent);  


------------------------------------------------------------------------------------------------------------------------------------

2”

类似打开相机,发送图片等隐式Intent,是并不一定能够在所有的Android设备上都正常运行。例如打开相机的隐式Intent,如果系统相机应用被关闭或者不存在相机应用,又或者是相机应用的某些权限被关闭等等情况都可能导致这个隐式的Intent无法正常工作。一旦发生隐式Intent找不到合适的调用组件的情况,系统就会抛出ActivityNotFoundException的异常,如果我们的应用没有对这个异常做任何处理,那应用就会发生Crash。

预防这个问题的最佳解决方案是在发出这个隐式Intent之前调用resolveActivity做检查,关于这个API的解释以及用法如下:

android_dev_patterns_implicit_intent

然后这个API的使用范例如下:

12345
Intent intent = new Intent(Intent.ACTION_XXX);ComponentName componentName = intent.resolveActivity(getPackageManager());if(componentName != null) {    String className = componentName.getClassName();} 
原创粉丝点击