Retrieve calling Activity from Intent in Android

13,075

In the first activity take a static activity variable like this,

public static Activity activity;

In the onCreate do this.

activity = this;

Then in the second activity do this,

Activity activity = (your activity name).activity;

This is the best solution according to my little knowledge. Just pass a code/value for the varification like this.

Intent intent = new Intent();
intent.putExtra("someValue", "data");

And in the second activity check the value, if the value is your required value then get your required activity instance. I hope this will solve your problem and if it will, please let me know.

Share:
13,075
mstrdenz188
Author by

mstrdenz188

Updated on June 17, 2022

Comments

  • mstrdenz188
    mstrdenz188 almost 2 years

    I am trying to pass along my activity pointer in my intent but I don't know how to retrieve it.

    I have a calling activity (MyActivity) with the following snippet of code:

    Intent myServiceIntent = new Intent(this, myService.class);
    startService(myServiceIntent);
    

    In my service class I want to retrieve the calling activity. Something like this:

    private Activity CurrentActivity = null;    
    public int onStartCommand(Intent intent, int flags, int startId) 
        {
            CurrentActivity = (CurrentActivity) intent.getClass();
            return super.onStartCommand(intent, flags, startId);
        }
    

    This doesn't work but I also don't know what does. I also couldn't find a putExtra that takes an activity as parameter. So how can I do this?