How to detect switching between users

时光总嘲笑我的痴心妄想 提交于 2019-11-29 00:24:55

问题


I have a service running in foreground mode and I'd like to detect switching between user sessions on tablets running Android 4.2 or above.

Is there any broadcast receiver I can register to get notified?

I have noticed that Google Music stops the music playback as soon as another user session is chosen on the lock screen. How does it detect the switch?


ANSWER EXPLAINED

Thanks @CommonsWare for the correct answer. I will explain a bit more how to detect a user switch.

First be aware that the documentation explicitly says that receivers must be registered through Context.registerReceiver. Therefore do something like:

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

Then in the receiver you can also retrieve the user id. Here is a small snippet:

public class UserSwitchReceiver extends BroadcastReceiver {

private static final String TAG = "UserSwitchReceiver";

    @Override
    public void onReceive(Context context, Intent intent) 
    {
        boolean userSentBackground = intent.getAction().equals( Intent.ACTION_USER_BACKGROUND );
        boolean userSentForeground = intent.getAction().equals( Intent.ACTION_USER_FOREGROUND );
        Log.d( TAG, "Switch received. User sent background = " + userSentBackground + "; User sent foreground = " + userSentForeground + ";" );

        int user = intent.getExtras().getInt( "android.intent.extra.user_handle" );
        Log.d( TAG, "user = " + user );
    }
}

回答1:


Try ACTION_USER_FOREGROUND and ACTION_USER_BACKGROUND. I have not used them, but they were added in API Level 17, and their description seems like it may help.



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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!