13

or should i send some extra data in the Intent to know the call ?if there is no predefined method,like getIntent and do something with it ?

Harinder
  • 11,776
  • 16
  • 70
  • 126

3 Answers3

59

I know this question is answered already but I have a better solution..

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.

See getCallingActivity for more details.

So you can check in Activity before finishing for calling activity. If result is null Activity was called by startActivity() and if result is not null then Activity was called by startActivityForResult(). Thats it.

example :-

if (getCallingActivity() == null) {
    //This Activity was called by startActivity 
} else {
   //This Activity was called by startActivityForResult
}
WarrenFaith
  • 57,492
  • 25
  • 134
  • 150
Pankaj Kumar
  • 81,967
  • 29
  • 167
  • 186
  • Please note that `getCallingActivity()` returns `null` if the activity launch mode of the started activity is `singleTask` or `singleInstance`, or started with `FLAG_ACTIVITY_NEW_TASK`. – EpicPandaForce Sep 18 '15 at 11:16
  • @EpicPandaForce In such cases, I think there is no meaning of using `startActivityForResult` to call such Activity which uses these flags. So the result is as expected. What you say? – Pankaj Kumar Sep 18 '15 at 12:08
  • I don't know, all I know is that I ran into a `NullPointerException` today, and the fix was to remove `singleInstance` from the launch mode. – EpicPandaForce Sep 18 '15 at 12:43
6

I think that you should expose several intents for the same activity in your manifest, then test the calling intent to adapt your behaviour.

Example for your activity intent filter in the manifest:

  <intent-filter>
    <action android:name="android.intent.action.VIEW" />
    <action android:name="android.intent.action.EDIT" />
    <action android:name="android.intent.action.PICK" />
    <category android:name="android.intent.category.DEFAULT" />
  </intent-filter>

and corresponding code in your activity onCreate:

if (getIntent().getAction().equals(Intent.ACTION_VIEW)) {
        // do whatever you need to do here
} else if (getIntent().getAction().equals(Intent.ACTION_PICK)){
 ...
}
Laurent'
  • 2,611
  • 1
  • 14
  • 22
3

you can put a flag like "0" and "1" , putting it in intent, so if "0" then its startActivity or "1" for startActivityForResult... this is simple, isnt it?

mayank_droid
  • 1,015
  • 10
  • 19
  • This is kind of messy because you handle more data than you really need. The answer below from @PankajKumar is the cleanest possible one. – WarrenFaith Jul 10 '13 at 22:49