To start a specific app on a specific display in Android using the Java API, you need to use a combination of ActivityManager, Intent, and Display APIs. Here’s a step-by-step guide:
First, you need to identify the display you want to launch the app on. You can use the DisplayManager to get the list of available displays and their IDs.
javaDisplayManager displayManager = (DisplayManager) getSystemService(Context.DISPLAY_SERVICE); Display[] displays = displayManager.getDisplays(); int targetDisplayId = displays[1].getDisplayId(); // Example: Use the second display
Create an Intent to launch the desired app. You can use the package name and activity name of the target app.
javaIntent launchIntent = getPackageManager().getLaunchIntentForPackage("com.example.app"); if (launchIntent == null) { // Handle error: App not found return; }
To launch the app on a specific display, you need to set the FLAG_ACTIVITY_LAUNCH_ADJACENT flag and specify the display ID using ActivityOptions.
javaActivityOptions options = ActivityOptions.makeBasic(); options.setLaunchDisplayId(targetDisplayId); launchIntent.addFlags(Intent.FLAG_ACTIVITY_LAUNCH_ADJACENT); startActivity(launchIntent, options.toBundle());
Ensure your app has the necessary permissions in the AndroidManifest.xml:
xml<uses-permission android:name="android.permission.SYSTEM_ALERT_WINDOW" />
If you are targeting Android 10 (API 29) or higher, you may also need to request the MANAGE_EXTERNAL_STORAGE permission or use the new scoped storage model.
Here’s a full example of how to launch an app on a specific display:
javaDisplayManager displayManager = (DisplayManager) getSystemService(Context.DISPLAY_SERVICE); Display[] displays = displayManager.getDisplays(); if (displays.length > 1) { int targetDisplayId = displays[1].getDisplayId(); // Use the second display Intent launchIntent = getPackageManager().getLaunchIntentForPackage("com.example.app"); if (launchIntent != null) { ActivityOptions options = ActivityOptions.makeBasic(); options.setLaunchDisplayId(targetDisplayId); launchIntent.addFlags(Intent.FLAG_ACTIVITY_LAUNCH_ADJACENT); startActivity(launchIntent, options.toBundle()); } else { Log.e("AppLaunch", "App not found"); } } else { Log.e("AppLaunch", "No secondary display found"); }