原文来自Android SDK文档中的docs/resources/articles/can-i-use-this-intent.html

Android提供了一个强大易用的Intent消息类型。 可以使用Intent 让应用成为库, 让代码模块化、可重用。比如,Home screen和AnyCut,就大量使用Intent来创建快捷方式(注:???)。

虽然Intent使用松耦合的API是一种好方式, 但是不能保证你发出的Intent 一定可以被别的应用接收, 尤其对第三方应用来说。 比如, Panoramio和它的RADAR Intent

本文主要讨论如何判断系统是否可响应我们发出的Intent。 下面的例子展示了一个通过查询系统Package Manager以确定是否有应用可以响应特定Intent的辅助方法。 可以传递Intent给这个方法, 然后根据返回结果进行某些操作。 比如,显示或隐藏用户用来触发这些Intent的选项。

/**

 * 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<ResolveInfo> list =            packageManager.queryIntentActivities(intent,                    PackageManager.MATCH_DEFAULT_ONLY);    return list.size() > 0;}

可以这样使用上述辅助方法:

@Overridepublic boolean onPrepareOptionsMenu(Menu menu) {    final boolean scanAvailable = isIntentAvailable(this,        "com.google.zxing.client.android.SCAN");    MenuItem item;    item = menu.findItem(R.id.menu_item_add);    item.setEnabled(scanAvailable);    return super.onPrepareOptionsMenu(menu);}

在这个例子中, 如果Barcode Scanner应用没安装那么相应的menu会被禁用。

另外一个更简单的办法是捕获调用startActivity()方法时可能抛出的ActivityNotFoundException, 但是这个办法只能让你在发出异常时进行处理, 而不能事先采取办法防止用户执行某些会引起错误的操作。这个技巧还可以用于应用启动的时候提示用户是否要安装某些未安装的应用, 然后使用适当的URI简单地重定向到Android Market(注: Google Play)

更多相关文章

  1. Android类参考---Fragment(四)
  2. Android中cannot be resolved or is not a field错误的解决办法
  3. Android(安卓)SurfaceFlinger中的工作线程:threadLoop()
  4. Android(安卓)Service使用方法
  5. [置顶] android fragment hidenChanged方法分析
  6. android Button实现点击事件的三种方法
  7. Android开发工具GenyMotion安装和使用方法
  8. sendBroadcast和sendStickyBroadcast的区别
  9. android scrollview嵌套scrollview,gridview,listview的方法和深

随机推荐

  1. android textview xml 属性设置
  2. Icon Design Guidelines-android 图标设
  3. android环境搭建及改变默认avd路径
  4. Android 属性动画(Property Animation) 源
  5. [better practice系列]Android处理好acti
  6. It's Android Time:程序员创富有道
  7. [置顶] 3D引擎--可移植到Android的开源的
  8. Android线程的学习
  9. 重构博客园Android App
  10. Android(安卓)PowerImageView实现,可以播