Foushi
Foushi

Reputation: 375

Two activities and different case for onResume method

My problem is I have two activities A and B, and 1 function in the acitivity B.

In activity A , if I click on a button it will call : this.finish(), then I will be in the second activity i.e. ActivityB and with theonResume() it will execute my function B : onResume() { functionB}

The thing i want to use functionB after this case. So I wonder if it's possible to know (when using onResume()) , from "where you come" : So If i get onResume() from another activity that is not A, It would never use function B, but It will use only B if I finish ActivityA

Hope you understand.

Thank you

Upvotes: 1

Views: 113

Answers (3)

Arslan Ashraf
Arslan Ashraf

Reputation: 867

You have to use SharedPreferences for this to work like in your scenario.

in your ActivityA. do somthing like this against your buttonClick before you call finish();

SharedPreferences sp = ActivityA.this.getSharedPreferences("prefs", MODE_PRIVATE);
 SharedPreferences.Editor preferencesEditor = sp.edit();
sp.putBoolean("from" , true);
sp.commit();

then in your ActivityB's onResume do it like this.

SharedPreferences sp = ActivityB.this.getSharedPreferences("prefs", MODE_PRIVATE);
if(sp.getBoolean("from",false))
{ 
// write your code here . it is from activirt A.
}

Upvotes: 1

vinothp
vinothp

Reputation: 10059

You should use Intent and Bundle to achieve your requirement.

Intent intent = new Intent(this, YourActivity.class);
Bundle extras = new Bundle();
extras.putBoolean(key,value); 
intent.putExtras(extras);
startActivity(intent); // This passes the information to your activity

Receive the information in your activity by using

boolean value = getIntent().getExtras().putBoolean(key);

Using value you can come to know whether its calling from onResume or from some where.

Hope that helps

Upvotes: 0

vguzzi
vguzzi

Reputation: 2428

This can be accomplished with startActivityForResult instead of startActivity. Like so:

startActivityForResult(activityIntent, 100);

Then instead of calling this.finish() you would call:

setResult(RESULT_OK);
this.finish();

Then in your resuming Activity this method will get called before onResume:

@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
    super.onActivityResult(requestCode, resultCode, data);
    if (resultCode == RESULT_OK && requestCode == 100) {
        // do something 
    }
}

Here you can set some kind of boolean variable to true to let the Activity know that it has come from your other Activity then in onResume check to see if the boolean is set to true, if it is do whatever you wish.

Upvotes: 1

Related Questions