7

I've an activity suppose "Activity A" which I start by two ways
a)StartActivity()
b) StartActivityForResult()
Now I have few methods which are having different behaviours for the way activity started. Now I want to detect that "Activity A" is started for result. So my question how we can detect that the activity is started for result? I don't want to send data through intent. Any other way more generalized?

Thank You.

Monty
  • 3,205
  • 8
  • 36
  • 61
Sandip Jadhav
  • 7,377
  • 8
  • 44
  • 76

3 Answers3

16

From this answer

When your activity was started just by startActivity() a getCallingActivity() method in target activity will return null. When it was called by startActivityForResult() it will return name of calling activity.

Example:

if (getCallingActivity() == null) {
    //This Activity was called by startActivity 
} else {
   //This Activity was called by startActivityForResult
}
Community
  • 1
  • 1
Joaquin Iurchuk
  • 5,499
  • 2
  • 48
  • 64
1

You don't need to pass any fake data in Intent. Activity has method for checking starting Activity it is called getCallingPackage()

From the documentation:

Return the name of the package that invoked this activity. This is who the data in setResult() will be sent to. You can use this information to validate that the recipient is allowed to receive the data.

pixel
  • 24,905
  • 36
  • 149
  • 251
-1

Send some boolean Extra when its called using

intent.putExtra("mBool", true);
startActivityForResult(intent);

Depending on that value, respective actions are done.

if(getIntent().hasExtra("mBool")){

//ForResult
}else{

//default
}
Archie.bpgc
  • 23,812
  • 38
  • 150
  • 226
  • 1
    Imho, bad solution. Why adding complexity to the application when you can simply check `this.getCallingActivity() != null`? – andrea.rinaldi Apr 08 '15 at 10:48
  • As I understand you can only get the calling activity when it's calling for a result. In case the activity is not calling for a result value, you couldn't change behavior depending on the calling activity. So In case you would have more than one activity calling another, you couldn't distinguish – Lama Apr 09 '15 at 13:52
  • Bad anwser as it is not using Android native solution – Marek Oct 09 '17 at 12:37
  • android native solution doesnt work either. if Intent.FLAG_ACTIVITY_NEW_TASK is set then null is returned with or with out starting for result – Hector Nov 27 '17 at 15:16