androiduser-inactivity

How Sign out to loginActivity when user inactive using common method for all activities in Android


In my application i want to sign out to loginActivity after 3 min when user inactive

i am currently use this code to do that but in my application there is more than 20 activities so without pasting this bunch of code every activity i want common method to do that, please help me

Here is the my code

public class HomeActivity extends AppCompatActivity {

    private Handler handler;
    private Runnable r;


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_home);


        handler = new Handler();
        r = new Runnable() {

            @Override
            public void run() {

                Intent intent = new Intent(getApplicationContext(), LoginActivity.class);
                startActivity(intent);
                finish();

                Toast.makeText(HomeActivity.this, "Logged out after 3 minutes on inactivity.", Toast.LENGTH_SHORT).show();
            }
        };

        startHandler();

    }

    public void stopHandler() {
        handler.removeCallbacks(r);

    }

    public void startHandler() {
        handler.postDelayed(r, 3 * 60 * 1000);

    }

    @Override
    public void onUserInteraction() {
        super.onUserInteraction();
        stopHandler();
        startHandler();
    }

    @Override
    protected void onPause() {

        stopHandler();
        super.onPause();

    }

    @Override
    protected void onResume() {
        super.onResume();
        startHandler();

        Log.d("onResume", "onResume_restartActivity");

    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        stopHandler();

    }

}

Solution

  • Define a class like

    public class BaseActivity extends AppCompatActivity {
      // Write logic of logout same as what you wrote in HomeActivity
    }
    

    Now extend this BaseActivity to each activities which meant to show after login. like

    public class HomeActivity extends BaseActivity {
      // Remove code related to logout from this class.
    }