首页 诗词 字典 板报 句子 名言 友答 励志 学校 网站地图
当前位置: 首页 > 教程频道 > 移动开发 > 移动开发 >

(通译) Can I Use this Intent

2013-01-23 
(翻译) Can I Use this Intent?原文来自Android SDK文档中的?docs/resources/articles/can-i-use-this-int

(翻译) Can I Use this Intent?

原文来自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)

?

热点排行