Search code examples
androidandroid-activityactivity-lifecycle

Log the why of the activity is resumed


Is there a way to know if a activity's onresume is called because "back button" or if is called because the intire application Was in background ? I have to log this different actions :/ This is the scenario : I have 4 activity A-B-C-D ;  i need to log the navigation between activity and i don't want to log the onresume caused by Application wake from background:)


Solution

  • From Activity A, when you will start the Activity B/C/D, use and identifier and start the activity for result.

    For example:

    int ActivityBID = 1;
    Intent i = new Intent(this,  ActivityB.class);
    startActivityForResult(i, ActivityBID );
    

    In your Activity B you override the onBackPressed:

    @Override
    public void onBackPressed() {
       Intent intent = new Intent();
       intent.putExtra("activity","B")
       setResult(RESULT_OK, intent);        
       finish();
    }
    

    And backing to Activity A:

    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == ActivityBID ) {
             if(resultCode == RESULT_OK){
                 String stredittext=data.getStringExtra("activity");
             }     
        }
    } 
    

    Note: The inner if and the variable is not necessary, because you already know what activity you result are from, but, i think you may want to pass some data in this return, so i leave then.

    Edit Image exemplify the ActivityForResult

    Imagem