Creating Explicit Intents at Runtime
Listing 24.8 Launching pressed activity (NerdLauncherFragment.java)
private class ActivityHolder extends RecyclerView.ViewHolder
implements View.OnClickListener {
private ResolveInfo mResolveInfo;
private TextView mNameTextView;
public ActivityHolder(View itemView) {
super(itemView);
mNameTextView = (TextView) itemView;
mNameTextView.setOnClickListener(this);
}
public void bindActivity(ResolveInfo resolveInfo) {
...
}
@Override
public void onClick(View v) {
ActivityInfo activityInfo = mResolveInfo.activityInfo;
Intent i = new Intent(Intent.ACTION_MAIN)
.setClassName(activityInfo.applicationInfo.packageName,
activityInfo.name);
startActivity(i);
}
}
Notice that in this intent you are sending an action as part of an explicit intent. Most apps will behave
the same whether you include the action or not. However, some may change their behavior. The same
activity can display different interfaces depending on how it is started. As a programmer, it is best to
declare your intentions clearly and let the activities you start do what they will.
In Listing 24.8, you get the package name and class name from the metadata and use them to create an
explicit intent using the Intent method:
public Intent setClassName(String packageName, String className)
This is different from how you have created explicit intents in the past. Before, you used an Intent
constructor that accepts a Context and a Class object:
public Intent(Context packageContext, Class<?> cls)
This constructor uses its parameters to get what the Intent really needs – a ComponentName. A
ComponentName is a package name and a class name stuck together. When you pass in an Activity
and a Class to create an Intent, the constructor determines the fully qualified package name from the
Activity.
You could also create a ComponentName yourself from the package and class names and use the
following Intent method to create an explicit intent:
public Intent setComponent(ComponentName component)
However, it is less code to use setClassName(...), which creates the component name behind the
scenes.