Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Retrieve calling Activity from Intent in Android

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?

like image 582
mstrdenz188 Avatar asked Oct 30 '14 10:10

mstrdenz188


People also ask

How can I get call activity in Android?

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

How do you get a response from an activity in Android?

You must call the second activity using the startActivityForResult method. In your second activity, when it is finished, you can execute the setResult method where basically you put the result information. Then, on your first activity, you override the onActivityResult method.

How can an intent call another activity?

Return to the activity_main. xml file to call the method from the button: Select the button in the Layout Editor. In the Attributes window, locate the onClick property and select sendMessage [MainActivity] from its drop-down list.


1 Answers

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.

like image 180
Zeeshan Ahmed Avatar answered Oct 19 '22 05:10

Zeeshan Ahmed