Android学习笔记Android Developer Blog

Can I use this Intent?

2016-10-19  本文已影响9人  Viking_Den

Android提供了非常强大且容易使用的工具:Intents(意图)。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;
}

下面是我如何使用它:

@Override
public 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没有安装的话,菜单中的扫描按钮将会置灰,不能点击。其实,还有另外一个方法,就是使用startActivity()方法,并且去捕捉是否有ActivityNotFoundException异常抛出,但是这个只会显示有这个问题,而你不能预测它,并且不能在出现异常时更新UI显示,阻止用户去操作。这个方法同样也可以在程序启动时,询问用户是否愿意去安装此缺失的应用,如果同意,你可以通过合适的URI地址引导他到应用市场去下载。

原文出处:Can I use this Intent?

上一篇下一篇

猜你喜欢

热点阅读