Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
416 views
in Technique[技术] by (71.8m points)

reflection - Android: how to code depending on the version of the API?

In Android I get the version of the SDK easily (Build.VERSION.SDK) but I need to use LabeledIntent only if the platform is newer than 1.6 (>Build.VERSION_CODES.DONUT)

I suppose that Reflection is necessary (I have read this link but it is not clear for a class or to me).

This is the code but it gives me an exception because in my Android 1.6, the compiler verifies if the package exists even if the condition is not applied:

 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);
  }

HOW I SOLVED IT, SOME NOTES TO THE RIGHT ANSWER

@Commonsware show me the way to do it. We create a bridge class so that depending on the API LEVEL, you instance one class that uses an API LEVEL or another class that uses another API LEVEL. The only detail one beginner could forget is that you have to compile your app with the newest SDK you are goint to make reference.

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());
 }
}

So in the LabeledIntentNew, I included all the code that refers to LabeledIntent only available in API LEVEL 5. In LabeledIntentOld, I can implement another kind of control, in my case I return the intent itself without doing nothing more.

The call to this class is done like this:

LabeledIntentBridge.INSTANCE.BuildLabeledIntent(URLtest,theIntent);
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Follow the wrapper class pattern documented in the page you linked to above.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

1.4m articles

1.4m replys

5 comments

57.0k users

...