Auto Logout of App when in Background

2020-05-06 12:50发布

I Have created an app which will log out within 1 Min; when it is running in the background, by employing Alarm Mgr method. However, when I debug and run in on Android based device, nothing happens. I have run some basic diagnostic test and found out that BaseActivity is not being logged in the Logcat.

  public class BaseActivity extends Activity{

    BaseActivity context;
    private AlarmManager alarmMgr; //TO CALL OUT THE CLASS OF THE ALARM SERVICE
    private PendingIntent alarmIntent; // FOR TARGET FUNCTION TO PERFORM WITH BROADCASTRECEIVER

    BaseActivity(){
        context=this;
    }


    @Override
     protected void onStart(){

         Log.i("RootActivity:SampleBootReceiver", "On Timeout after 1 min");

         super.onStart();// CALLING ON SUPER CLASS METHOD OF ALARM MGR

   if(alarmMgr != null){    
          alarmMgr.cancel(alarmIntent);
             // IN START CONDITION, VAL OF ALARM IS NOT NULL, WILL ABORT INTENT, ELSE WILL

   START()

         }

 }

 // CLASS IS CALLED WHEN APP IS NO LONGER VISIBLE TO USER (FUNCTIONING IN THE BACKGROUND)

  @Override

   protected void onStop(){

    super.onStop();

    alarmMgr = (AlarmManager)context.getSystemService(Context.ALARM_SERVICE);

    Intent intent= new Intent(context, SampleBootReceiver.class); 

    alarmIntent=PendingIntent.getBroadcast(context, 0, intent, 0); 

    alarmMgr.set(AlarmManager.ELAPSED_REALTIME_WAKEUP,SystemClock.elapsedRealtime()+60000, alarmIntent);
        //SCHEDULE ALARM TO 1 MIN
    }
    public class SampleBootReceiver extends BroadcastReceiver{
        // ONCE THE ALARM IS LAUNCHED, WILL LOGOUT THE APP
        @Override
        public void onReceive(Context context, Intent intent){
            //LOGOUT OF THE SERVICE
            Log.i("RootActivity:SampleBootReceiver", "On Timeout after 1 min");
            Intent intent_login= new Intent(context, MainActivity.class);
            //CLOSE ALL OTHER ACTIVITIES AND BRING THE ACTIVITY BEING LAUNCHED TO THE TOP
            intent_login.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
            startActivity(intent_login);
            //stopServiceAndLogout();
            finish();
        }
    }
    public void cancelAlarm(Context context){
        //UPON REACTIVATION OF APP, CANCEL THE ALARM(IF SET) TO ENSURE LOGOUT WILL NOT BE EXECUTED
        if(alarmMgr!=null){
            alarmMgr.cancel(alarmIntent); 
        }
    }
}

3条回答
聊天终结者
2楼-- · 2020-05-06 13:26

The problem is AlarmManager is not able to find the broadcastreceiver to invoke.

Solution to write SampleBootReceiver in different file and declare it in manifest. PendingIntent.getBroadcast will not find it unless it is declare in manifest. Declare it as below (Change packagename accordingly),

<receiver android:name="com.app.packagename.SampleBootReceiver"></receiver>

Create PendingBroadcast as below (add PendingIntent.FLAG_UPDATE_CURRENT as last param):

Intent intent= new Intent(context, SampleBootReceiver.class);
PendingIntent alarmIntent=PendingIntent.getBroadcast(context, 0, intent, PendingIntent.FLAG_UPDATE_CURRENT);
AlarmManager alarmManager = (AlarmManager) context.getSystemService(Context.ALARM_SERVICE);
alarmManager.set(AlarmManager.RTC_WAKEUP, System.currentTimeMillis() + (1 * 60 * 1000), alarmIntent);
查看更多
▲ chillily
3楼-- · 2020-05-06 13:35

You can declare time period for logout in your Activity.java or in your fragment.java file.

@Override
public void onStart() {
    super.onStart();

     new Handler().postDelayed(new Runnable() {

            @Override
            public void run() {
                finish(); // To CLOSE YOUR APP IN ACTIVITY

               ///LOG OUT CODE HERE


            }
        }, 1800000 ); //HAlf hour -1800000


}
查看更多
时光不老,我们不散
4楼-- · 2020-05-06 13:36

I think you need to call registerReceiver - you can find some info here

You should call something like this inside your OnStart() method:

context.registerReceiver(alarmMgr, alarmIntent);

EDIT - I would do something like this:

public class BaseActivity extends Activity {
    BaseActivity context;
    private AlarmManager alarmMgr; //TO CALL OUT THE CLASS OF THE ALARM SERVICE
    private PendingIntent alarmIntent; // FOR TARGET FUNCTION TO PERFORM WITH BROADCASTRECEIVER
    private BroadcastReceiver br;

    BaseActivity(){
        context=this;
    }    

    @Override
     protected void onStart(){

         Log.i("RootActivity:SampleBootReceiver", "On Timeout after 1 min");    
         super.onStart();// CALLING ON SUPER CLASS METHOD OF ALARM MGR    
         setupAlarm(); // this could be called in onCreate() instead    
    }

    @Override
    protected void onStop() {
         super.onStop();
         alarmMgr.set( AlarmManager.ELAPSED_REALTIME_WAKEUP, SystemClock.elapsedRealtime() + SIXTY_SECONDS, alarmIntent );
    }

    private void setupAlarm() {
          br = new BroadcastReceiver() {
                @Override
                public void onReceive(Context c, Intent i) {
                        // DO YOUR LOGOUT LOGIC HERE
                        Toast.makeText(c, "You are now logged out.", Toast.LENGTH_LONG).show();
                }
            };
          registerReceiver(br, new IntentFilter("com.myapp.logout") );
          alarmIntent = PendingIntent.getBroadcast( this, 0, new Intent("com.myapp.logout"),0);
          alarmMgr = (AlarmManager)(this.getSystemService( Context.ALARM_SERVICE ));
    }
}

And make sure you clean everything up in the destroy method:

@Override
protected void onDestroy() {
       alarmMgr.cancel(alarmIntent);
       unregisterReceiver(br);
       super.onDestroy();
}

Setting up the AlarmManager and the broadcasting is handled in the setupAlarm() method. In the OnStop() method, you actually set the alarm to go off after 60 seconds (60 * 1000 milliseconds), at which point it broadcasts to the br (BroadcastReceiver) and you can run your logout logic.

EDIT 2 - I have tested out this code on a Galaxy S5 and it worked nicely. You can find the code here. All you have to do is run the app, press home and wait for 10 seconds and a toast will appear saying you have been logged out.

查看更多
登录 后发表回答