The final piece is to detect which shortcut the user is gazing at and respond to a trigger (click) by launching the app.
When we launch a new app from this one, we need to reference the MainActivity
object. One way to do it is to make it a singleton object. Let's do that now. Note that you can get into trouble defining activities as singletons. Android can launch multiple instances of a single Activity
class, but even across apps, static variables are shared.
At the top of the MainActivity
class, add an instance
variable:
public static MainActivity instance;
Initialize it in onCreate
:
protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); instance = this;
Now in MainActivity
, add a handler to the Cardboard trigger:
@Override public void onCardboardTrigger(){ overlayView.onTrigger(); }
Then, in OverlayView
, add the following method:
public void onTrigger() { shortcuts.get( getSlot() ).launch(); }
We're using getSlot
to index into our shortcuts list. Because we checked the boundary conditions in getSlot
itself, we don't need to worry about ArrayIndexOutOfBounds
exceptions.
Finally, add a launch()
method to Shortcut
:
public void launch() { ComponentName name = new ComponentName(info.applicationInfo.packageName, info.name); Intent i = new Intent(Intent.ACTION_MAIN); i.addCategory(Intent.CATEGORY_LAUNCHER); i.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_RESET_TASK_IF_NEEDED); i.setComponent(name); if(MainActivity.instance != null) { MainActivity.instance.startActivity(i); } else { Log.e(TAG, "Cannot find activity singleton"); } }
We use the ActivityInfo
object that we stored in the Shortcut
class to create a new Intent
instance, and then call MainActivity.instance.startActivity
with it as an argument to launch the app.
Note that once you've launched a new app, there's no system-wide way to get back to LauncherLobby from within VR. The user will have to remove the phone from the Cardboard Viewer, and then click on the back button. However, the SDK does support CardboardView.setOnCardboardBackButtonListener
which can be added to your Cardboard apps if you want to present a back or exit button.
There you have it! LauncherLobby is ready to rock and roll.