Android: automatic logout

1.7k views Asked by At

Hi I want to logout automatically after a determined time of inactivity my Android app. In the Second Activity in onPause I save the time when the app is in pause in a variable. In MainActivity in method onresume I save the time when the app restarts in another variable and calculate the difference between two variables. If this difference is greater than a determined time, for example 10 seconds there is logout.

This code of my MainActivity:

public class MainActivity extends Activity {

    private EditText username,password;
    public static final String MyPREFERENCES = "MyPrefs" ;
    public static final String name = "nameKey"; 
    public static final String pass = "passwordKey"; 
    SharedPreferences sharedpreferences;

    public static Long t0;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        username = (EditText)findViewById(R.id.editText1);
        password = (EditText)findViewById(R.id.editText2);

        username.setText("***");
        password.setText("***");

        t0 = Welcome.t0;
    }


    @Override
    protected void onResume() {
        sharedpreferences=getSharedPreferences(MyPREFERENCES, 
                Context.MODE_PRIVATE);
        if (sharedpreferences.contains(name))
        {
            if(sharedpreferences.contains(pass)){
                Intent i = new Intent(this,SecondActivity.class);
                startActivity(i);
            }

        Calendar c = Calendar.getInstance();
        SimpleDateFormat sdf = new SimpleDateFormat("HH:mm:ss");
        String strDate = sdf.format(c.getTime());
        System.out.println(strDate);

        Date d;
        try {
            d = sdf.parse(strDate);
            long second2=d.getSeconds();

            long ts=Math.abs(second2-t0);

            if (ts>=10){

                logout();
                Intent i2 = new Intent(this,MainActivity.class);
                startActivity(i2);
                }

        } catch (ParseException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }

    }
        super.onResume();
    }

    public void login(View view){
        Editor editor = sharedpreferences.edit();
        String u = username.getText().toString();
        String p = password.getText().toString();
        if(u.equals("***") && p.equals("***")){

            editor.putString(name, u);
            editor.putString(pass, p);
            editor.commit();
            Intent i = new Intent(this,SecondActivity.Welcome.class);
            startActivity(i); 
        }
        else{
            Toast.makeText(MainActivity.this, "ko", Toast.LENGTH_SHORT).show();

        }
    }
    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        // Inflate the menu; this adds items to the action bar if it is present.
        getMenuInflater().inflate(R.menu.main, menu);
        return true;
    }


    public void onPause() {
        super.onPause();
        this.finish();
    }

    public void closing() {
        finish();
    }

    public void logout(){
        SharedPreferences sharedpreferences = getSharedPreferences
                (MainActivity.MyPREFERENCES, Context.MODE_PRIVATE);
        Editor editor = sharedpreferences.edit();

        editor.clear();
        editor.commit();
        moveTaskToBack(true); 
        this.finish();
    }

}

The code of Second Activity is:

public class Second extends Activity {

    static Long t0;

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

    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        // Inflate the menu; this adds items to the action bar if it is present.
        getMenuInflater().inflate(R.menu.welcome, menu);
        return true;
    }
    public void logout(View view){
        SharedPreferences sharedpreferences = getSharedPreferences
                (MainActivity.MyPREFERENCES, Context.MODE_PRIVATE);
        Editor editor = sharedpreferences.edit();

        editor.clear();
        editor.commit();
        moveTaskToBack(true); 
        this.finish();
    }

    public void exit(View view){

        moveTaskToBack(true); 
        this.finish();

    }

     public void onPause() {
     super.onPause();
            Calendar c = Calendar.getInstance();
            SimpleDateFormat sdf = new SimpleDateFormat("HH:mm:ss");
            String strDate = sdf.format(c.getTime());


                            Date d;
                            try {
                                d = sdf.parse(strDate);
                                long second=d.getSeconds();

                                Welcome.t0=second;

                            } catch (ParseException e) {
                                // TODO Auto-generated catch block
                                e.printStackTrace();
                            }

                            this.finish();

       }

        public void closing() {
            finish();
        }

}

This cose doens't work, because after the first time it works fine but the second time it doesn't work, there aren't logout. How can I solve this problem?

2

There are 2 answers

0
Dhinakaran Thennarasu On BEST ANSWER

Set Alarm:

Calendar cal = Calendar.getInstance();

cal.add(Calendar.MINUTE, "YourTimeinMinutes"); // you can use Calendar.Seconds etc according to your need

Intent intent = new Intent(YourActivity.this, AlarmReceiver.class);
PendingIntent sender = PendingIntent.getBroadcast(YourActivity.this, 0, intent, PendingIntent.FLAG_UPDATE_CURRENT);

// Get the AlarmManager service
AlarmManager am = (AlarmManager) getSystemService(ALARM_SERVICE);
am.set(AlarmManager.RTC_WAKEUP, cal.getTimeInMillis(), sender);

AlarmReceiver.class

public class AlarmReceiver extends BroadcastReceiver 
{
    @Override
    public void onReceive(Context context, Intent intent) 
    {   
        //your logic 
    }
}

Dont forget to add receiver in manifest inside your application tag :

  <receiver  android:name=".AlarmReceiver"  ></receiver>

Add unregister your broadcast onPause.

3
Uma Kanth On

I suggest you to use a countDownTimer for it, started as soon as you open the application.

new CountDownTimer(10000, 1000) {//CountDownTimer for 10 seconds

 public void onTick(long millisUntilFinished) {
     }

 public void onFinish() {
     //logout here.
SharedPreferences sharedpreferences = getSharedPreferences
            (MainActivity.MyPREFERENCES, Context.MODE_PRIVATE);
    Editor editor = sharedpreferences.edit();

    editor.clear();
    editor.commit();
    moveTaskToBack(true); 
    this.finish();
 }
}
.start();