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 );
}
}
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With