OnActivityResult () is called at unexpected time

In my main activity I have:

Intent settings_intent = new Intent(this, SettingsActivity.class); settings_intent.putExtra("SomeID", some_int); startActivityForResult(settings_intent, 1); 

And then, in my SettingsActivity application, I:

 @Override public void onBackPressed() { super.onBackPressed(); // pass back settings: Intent data = new Intent(); data.putExtra("SomeThing", some_number); setResult(200, data); finish(); } 

And finally, I tried the following in my main activity:

 @Override protected void onActivityResult(int requestCode, int resultCode, Intent data) { makeToast("called"); super.onActivityResult(requestCode, resultCode, data); } 

However, the “called up” toast happens as soon as my “Settings” begins, and not when it ends. I have spent quite a lot of time on this now. Any help is appreciated. Thanks.

+4
source share
2 answers

Most likely, your settings activity has a launch mode set to singleTask in your manifest. This leads to an immediate cancellation of the response when calling startActivityForResult() .

Note that this method should only be used with Intent protocols, which return the result. In other protocols (such as ACTION_MAIN or ACTION_VIEW), you may not get the result when you expect. For example, if the activity that you perform uses singleTask, it will not start in your task, and you will immediately receive the result of the cancellation.

from startActivityForResult() documentation

+14
source
 @Override protected void onActivityResult(int requestCode, int resultCode, Intent data) { if(requestCode==1) makeToast("called"); super.onActivityResult(requestCode, resultCode, data); } 
-1
source

Source: https://habr.com/ru/post/1385695/


All Articles