【问题标题】:Dynamic Activity Chooser动态活动选择器
【发布时间】:2013-08-30 02:19:11
【问题描述】:

我有两个执行相同功能的“查看器”活动,但一个是旧查看器,它对旧 API 有更好的支持。如果遇到问题,用户可以在设置中切换到旧版查看器。

有两种方法可以打开查看器,一种是通过启动器打开画廊活动,另一种是通过直接转到相应查看器的 VIEW Intent。

由于可以直接从外部应用调用查看器,因此需要有逻辑来决定要显示哪个查看器。我以“ViewerChooser”活动的形式这样做。

public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);

    Intent viewer = new Intent();
    SharedPreferences settings = PreferenceManager.getDefaultSharedPreferences(this);
    if (!settings.contains(FullSettingsActivity.KEY_UseLegacyViewer))
    {
        SharedPreferences.Editor editor = settings.edit();
        editor.putBoolean(FullSettingsActivity.KEY_UseLegacyViewer, !Util.hasHoneycomb());
    }

    if(settings.getBoolean(FullSettingsActivity.KEY_UseLegacyViewer, false))
    {
        viewer.setClass(this, LegacyViewerActivity.class);
    }
    else
    {
        viewer.setClass(this, ImageViewerActivity.class);
    }

    viewer.setData(getIntent().getData());
    startActivityForResult(viewer, REQUEST_VIEWER);
}

/**
 * Simply forward on the result
 */
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
    super.onActivityResult(requestCode, resultCode, data);
    setResult(resultCode, data);
    finish();
}

如果需要,它还会将结果转发出去。这很实用,但有点笨拙,因为活动会在瞬间显示一个空白屏幕。

有没有更好的方法来处理动态选择的两个不同活动的相同意图?

【问题讨论】:

    标签: android android-intent android-activity


    【解决方案1】:

    您可以在 onClick 方法或用于启动活动的任何方法中执行此操作:

    int currentapiVersion = android.os.Build.VERSION.SDK_INT;
    if (currentapiVersion >= android.os.Build.VERSION_CODES.FROYO){
        // Do something for froyo and above versions
    } else{
        // do something for phones running an SDK before froyo
    }
    

    【讨论】:

    • 最初我就是这样做的,但它可以处理意图。例如,在图像上请求 VIEW 的文件浏览器将直接打开查看器,因此它需要比这更高级一些,因此需要中间的 ViewerChooser。
    • 编写两个不同的活动,并为所需的 API 调用一个。或者在相同的意图(类)中使用它,并且每当您对运行的操作系统进行调节时。真的没有更多我可以告诉你的了;您只需要找到一种使用此代码的智能方法来根据操作系统版本运行您的应用程序。
    【解决方案2】:

    您会看到空白屏幕,因为您正在使用 Activity 来决定要运行哪个 OTHER Activity。为什么不尝试为 VIEW 意图注册广播接收器并从那里启动适当的 Activity。

    【讨论】:

    • 这听起来很有希望。我周末会离开,但是当我回来更新你的信息时,我会看看 BroadcastReceivers。谢谢。
    • BroadcastReceivers 对新的安全性很不利。在应用明确运行之前,它们不会被注册。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-09-29
    • 1970-01-01
    • 2023-03-16
    • 1970-01-01
    • 1970-01-01
    • 2015-07-15
    相关资源
    最近更新 更多