【发布时间】:2010-11-30 20:31:16
【问题描述】:
在 Android 中,我很容易获得 SDK 的版本 (Build.VERSION.SDK),但只有当平台高于 1.6 (>Build.VERSION_CODES.DONUT) 时,我才需要使用 LabeledIntent。
我认为反射是必要的(我已阅读this link,但对于班级或我来说并不清楚)。
这是代码,但它给了我一个例外,因为在我的 Android 1.6 中,即使未应用条件,编译器也会验证包是否存在:
Intent theIntent=....;
if(Integer.parseInt(Build.VERSION.SDK) > Build.VERSION_CODES.DONUT)
{
try{
Intent intentChooser = Intent.createChooser(intent,"Choose between these programs");
Parcelable[] parcelable = new Parcelable[1];
parcelable[0] = new android.content.pm.LabeledIntent(theIntent, "", "Texto plano", 0);
intentChooser.putExtra(Intent.EXTRA_INITIAL_INTENTS, parcelable);
activity.startActivity(intentChooser);
}
catch(Exception e)
{
activity.startActivity(theIntent);
}
} else
{
activity.startActivity(intentMedicamento);
}
我是如何解决的,正确答案的一些注释
@Commonsware 告诉我如何做到这一点。我们创建了一个桥接类,以便根据 API LEVEL 实例化一个使用 API LEVEL 的类或使用另一个 API LEVEL 的另一个类。 初学者可能会忘记的唯一细节是,您必须使用要参考的最新 SDK 编译您的应用程序。
public abstract class LabeledIntentBridge {
public abstract Intent BuildLabeledIntent(String URL, Intent theintent);
public static final LabeledIntentBridge INSTANCE=buildBridge();
private static LabeledIntentBridge buildBridge() {
int sdk=new Integer(Build.VERSION.SDK).intValue();
if (sdk<5) {
return(new LabeledIntentOld());
}
return(new LabeledIntentNew());
}
}
所以在LabeledIntentNew 中,我包含了所有引用LabeledIntent 的代码,仅在API LEVEL 5 中可用。在LabeledIntentOld 中,我可以实现另一种控制,在我的情况下,我返回意图本身而不什么都不做。
对这个类的调用是这样完成的:
LabeledIntentBridge.INSTANCE.BuildLabeledIntent(URLtest,theIntent);
【问题讨论】:
-
您在项目中使用的是哪个框架版本?
-
@Flo.- 我的 AndroidManifest 定义了 minSdkVersion="4"。 LabeledIntent 仅包含在 API LEVEL 5 以上的 SDK 中。
-
是的,但您的项目中实际使用的是哪个框架版本? minSdkVersion 只是清单文件中的元信息。创建项目时,您应该在创建对话框中选择了框架版本。
-
@Flo.- 我在 2.2 和 1.6 之间切换,我的应用程序必须与两者兼容。
-
好的,那么当您切换回 1.6 时,编译器当然会抛出错误,因为您尝试使用的类不在 Android 1.6 框架中。正如您已经说过的,您必须使用反射,就像您链接到的博客文章中提到的那样。
标签: android reflection