Petrakeas Petrakeas - 1 year ago 62
Android Question

How to load different activity implementation according to Android API level?

I want to have an activity class, e.g. ActivityLegacy, for API levels older than level x and an activity class, e.g. ActivityNew for newer devices.

Is it possible that I choose the proper implementation at runtime and load it? I don't want to start a new intent.

Answer Source

I don't want to start a new intent.

Um, well, the only way to get an activity to appear on the screen is via an Intent. Somebody is calling startActivity() or kin. Whether that is your code or third-party code would depend on circumstance.

Is it possible that I choose the proper implementation at runtime and load it?

If you are the one calling startActivity(), craft the Intent for your desired class.

If you are not the one calling startActivity(), I would recommend that you have just one activity, then use fragments (or something similar) for the activity contents, so that you can cleanly load in the right fragment based on API level. Otherwise, you have two main options that I can think of.

If the outside party is using an implicit Intent (e.g., action string) to start up your activity, you could have two <activity> elements for the same <action> in the manifest, one for each of your two implementations. However, they would each have android:enabled pointing to boolean resources, where those resources would vary by API level. Suppose you want a different activity on Android 6.0 than on older versions. res/values/bools.xml would define is23 to be false and isPre23 to be true. res/values-v23/bools.xml would define is23 to be true and isPre23 to be false. Your pre-23 activity would have android:enabled="@bool/isPre23"; your 23-and-above activity would have android:enabled="@bool/is23". This way, only one activity will be enabled for that action string, based on API level.

If you are in some screwball scenario where an explicit Intent that you do not control is the one that is being used to start the activity, you would need a total of three activities:

  1. The pre-23 one.

  2. The 23-and-over one.

  3. The one identified by that explicit Intent, which would use Theme.NoDisplay (so it has no UI). In onCreate(), you would call startActivity() for the right activity based on API level, then call finish(), to pass control to the desired activity.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download