How to switch between Android apps programmatically

2.3k views Asked by At

I want to switch quickly between two running Android apps, a Client and a Server, for debugging purposes. The two are connected by a socket connection. Ideally, I'd like to add a button to both to toggle to the other (preserving the connection) so I can easily see what's going on at both ends.

Here's what I tried:

  • Using "Recent Apps" button
    This worked fine but is a bit awkward, especially if the stack is big.

  • Using Split Screens
    This also worked fine but the small screens were problematic

  • Tried Third-Party App Switchers but didn't like these.

  • Tried startActivity by package name (on button click)
    This would be my preferred solution but had problems. Switched Ok but each time a fresh task was created, started and pushed onto the stack (not preserving the connection). Code below:

    void switchToClient()       // from Server (on Button click)
    {
        // Alternative Flags Tried: none, FLAG_ACTIVITY_SINGLE_TOP, FLAG_ACTIVITY_NEW_TASK, other
        Intent intent;
        intent = this.getPackageManager().getLaunchIntentForPackage( "com.example.Client" );
        intent.setFlags( Intent.FLAG_ACTIVITY_NEW_TASK );
        startActivity( intent );
    }  
    
1

There are 1 answers

0
DontPanic On BEST ANSWER

I finally figured out how to switch between apps programatically (preserving their state). In each app, I used 'getTaskId()' to get its task id and saved it to a file on /sdcard/.

Then, in each app, on a button click, I call

void switchTask()
{
  int tid;
  ActivityManager am;
  am = (ActivityManager)Ctx.getSystemService( Context.ACTIVITY_SERVICE );
  tid = getPkgTaskId();  // read task id of *other* app from file
  am.moveTaskToFront( tid, 0, null );
}

Note: These need permissions:

  • READ_EXTERNAL_STORAGE
  • WRITE_EXTERNAL_STORAGE
  • REORDER_TASKS