2017年12月25日 星期一

Detect switching between users

Reference:

https://stackoverflow.com/questions/15392126/how-to-detect-switching-between-users


Description:

Listen the ACTION_USER_BACKGROUND and ACTION_USER_FOREGROUND broadcast to detect switching between users.


Code snippet:


IntentFilter filter = new IntentFilter();
filter.addAction(Intent.ACTION_USER_BACKGROUND);
filter.addAction(Intent.ACTION_USER_FOREGROUND);
registerReceiver(mUserSwitchReceiver, filter);



public class UserSwitchReceiver extends BroadcastReceiver {
    private static final String TAG = "UserSwitchReceiver";
    @Override    public void onReceive(Context context, Intent intent) {
        String action = intent.getAction();
        
        if(Intent.ACTION_USER_FOREGROUND.equals(action)){
            // Todo: do something when switch in the user
        } else if(Intent.ACTION_USER_BACKGROUND.equals(action)){
            // Todo: do something when switch out the user
        }
    }
}

沒有留言: