Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to know the calling activity in android

I have an activity which is called by few other activities. For example: I have Activity1,Activity2,Activity3. Activity1 calls Activity2 and pass parameter. Activity3 also calls Activity2 and pass parameter.

Now based on the calling activity, Activity2 performs some task. But how do I know which activity is calling Activity2?? can anybody plz help me??

like image 435
Crime Master Gogo Avatar asked Feb 11 '11 10:02

Crime Master Gogo


People also ask

How can call activity from another activity in Android?

Start the Second Activity To start an activity, call startActivity() and pass it your Intent . The system receives this call and starts an instance of the Activity specified by the Intent .

What is main activity in Android?

Typically, one activity in an app is specified as the main activity, which is the first screen to appear when the user launches the app. Each activity can then start another activity in order to perform different actions.

What does finish () do in Android?

On Clicking the back button from the New Activity, the finish() method is called and the activity destroys and returns to the home screen.


2 Answers

If you start the activity with startActivityForResult(Intent, int), then you can get calling activity by getCallingActivity().getClassName().

like image 105
Zain Ali Avatar answered Sep 18 '22 03:09

Zain Ali


A. If you can use startActivityForResult

As per Zain Ali's answer below: If you can start Activity with startActivityForResult() then you can get name of calling Activity class by this.getCallingActivity().getClassName();

B. If you can not use startActivityForResult

If you can not use startActivityForResult(), then you can use following method: You can pass additional parameter in intent, check the value in activity and act accordingly.

1) Define an interface or constants class to define integer constants to indicate calling activity

public interface ActivityConstants {             public static final int ACTIVITY_1 = 1001;             public static final int ACTIVITY_2 = 1002;             public static final int ACTIVITY_3 = 1003; } 

2) Add extra parameter in intent while calling Activity2.

        Intent act2 = new Intent(context, Activity2.class);                 act2.putExtra("calling-activity", ActivityConstants.ACTIVITY_1);     // or ActivityConstants.ACTIVITY_3 if called form Activity3 startActivity(act2); 

3) Check the value of this extra parameter in Activity2 and act accordingly..

int callingActivity = getIntent().getIntExtra("calling-activity", 0);          switch (callingActivity) {         case ActivityConstants.ACTIVITY_1:             // Activity2 is started from Activity1             break;         case ActivityConstants.ACTIVITY_3:             // Activity2 is started from Activity3             break;         } 
like image 29
Udayan Avatar answered Sep 19 '22 03:09

Udayan