Android:如何根据 API 的版本进行编码?

标签 android reflection

在 Android 中,我很容易获得 SDK 的版本 (Build.VERSION.SDK),但只有当平台比 1.6 更新时我才需要使用 LabeledIntent (>Build.VERSION_CODES。 donut )

我认为反射(reflection)是必要的(我已经阅读了 this link 但对于一个类(class)或对我来说并不清楚)。

这是代码,但它给了我一个异常(exception),因为在我的 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 级别,实例化一个使用 API 级别的类或另一个使用另一个 API 级别的类。 初学者可能会忘记的唯一细节是,您必须使用要引用的最新 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 级别 5 中可用。在 LabeledIntentOld 中,我可以实现另一种控制,在我的例子中,我什么都不做就返回了 Intent 本身。

这个类的调用是这样完成的:

LabeledIntentBridge.INSTANCE.BuildLabeledIntent(URLtest,theIntent);

最佳答案

关于Android:如何根据 API 的版本进行编码?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4276352/

相关文章:

java - Scala/Java 反射式编程 : invoke constructor by typecasted arguments

android - 获取 Item recyclerView 的文本

android - 如何检查应用程序是否已从 android/Iphone 设备上卸载

android - 我无法在 Android Studio 中进行调试。我的服务从不附加到 VM,也从不在断点处停止

reflection - 如何获取 CRTP 类型的泛型类型定义

c# - 我可以获得作为 bool 传递给函数的条件的字符串表示形式吗?

Java - getConstructor()?

c# - 查明一个类型是否实现了一个泛型接口(interface)

android - 使用来自 findViewById 的 View 时出现 NullPointerException

java - 从警报管理器启动服务(无空构造函数)