I was reviewing the Google I/O Session 2012 app and came across this TODO
// TODO: use <meta-data> element instead
private static final Class[] sPhoneActivities = new Class[]{
MapActivity.class,
SessionDetailActivity.class,
SessionsActivity.class,
TrackDetailActivity.class,
VendorDetailActivity.class,
};
// TODO: use <meta-data> element instead
private static final Class[] sTabletActivities = new Class[]{
MapMultiPaneActivity.class,
SessionsVendorsMultiPaneActivity.class,
};
public static void enableDisableActivities(final Context context) {
boolean isHoneycombTablet = isHoneycombTablet(context);
PackageManager pm = context.getPackageManager();
// Enable/disable phone activities
for (Class a : sPhoneActivities) {
pm.setComponentEnabledSetting(new ComponentName(context, a),
isHoneycombTablet
? PackageManager.COMPONENT_ENABLED_STATE_DISABLED
: PackageManager.COMPONENT_ENABLED_STATE_ENABLED,
PackageManager.DONT_KILL_APP);
}
// Enable/disable tablet activities
for (Class a : sTabletActivities) {
pm.setComponentEnabledSetting(new ComponentName(context, a),
isHoneycombTablet
? PackageManager.COMPONENT_ENABLED_STATE_ENABLED
: PackageManager.COMPONENT_ENABLED_STATE_DISABLED,
PackageManager.DONT_KILL_APP);
}
}
Which made me wonder how would one execute that TODO.
I came up with this approach (Note: this is modelled after the Google I/O Session 2012 app UIUtilis.java):
In the
AndroidManifest.xml
defineActivity
s to include the<meta-data>
:The hard work is put in the method
configureDeviceSpecificActivities(Context context)
fun fact: it doesn't work without the
GET_META_DATA
flag, as themetaData
will always return as null if you don't include that tag.The last touch is to call this method, likely in the
onCreate
of your initialActivity
Now you can have
Activity
s that are specially designed for phones and tablets for the times when just changing the layout and maybe including moreFragment
s isn't sufficient.NOTE:
final String class_name = info.packageName + info.name;
might have to befinal String class_name = info.name;
if you see a warning.NOTE(2):
final String target_device = info.metaData.getString("target_device", "").toLowerCase();
should be for backward compatibility past API 12.NOTE(3):
target_device.toLowerCase();
uses the default locale implicitly. Usetarget_device.toLowerCase(Locale.US)
instead. And made all changes in the code above.