Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to determine which Activity launched current Activity in Android?

Without using an Intent and passing an extra parameter, is it possible to determine which Activity launched the current Activity?

like image 976
code Avatar asked Sep 19 '25 10:09

code


1 Answers

There are two approaches to do.

  1. the common one

use startActivityForResult in your calling activity to start the activity. Here I use ActivityCompat for backward compatibility.

ActivityCompat.startActivityForResult(this, new Intent(this, MyActivity.class), 0, null);

Then in the callee activity, you can use the following code to detect the calling activity.

    if (getCallingActivity() != null) {
        Log.d(TAG, getCallingActivity().getClassName());
    }

NOTE In the calling activity, you don't have to implement onActivityResult if you don't need transfer data from callee activity.

  1. the deprecated one

use the system's back stack to get the recent tasks. But it won't work after API 21, it's deprecated after API 21.

declare the necessary permission in the mainifest.

<uses-permission android:name="android.permission.GET_TASKS" />

Then in your callee activity

ActivityManager activityManager = (ActivityManager) getSystemService(ACTIVITY_SERVICE);
for (ActivityManager.RecentTaskInfo taskInfo : activityManager.getRecentTasks(1, 0)) {
        Log.d(TAG, taskInfo.baseIntent.getComponent().getClassName());
}
like image 151
alijandro Avatar answered Sep 20 '25 23:09

alijandro