21

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 );
    }
}
Xavi Gil
  • 11,460
  • 4
  • 56
  • 71
  • 2
    I'm surprised that the service keeps on running in your case. Did you actually check that it keeps on going? – Stephan Branczyk Mar 13 '13 at 17:25
  • Yes it does. On one hand, I can see my app's logs form the other user's account. On the other hand, when I go back to the original user (running my service) the foreground notification icon is there. And there is no message in the log indicating that the service was stopped. – Xavi Gil Mar 13 '13 at 17:36
  • I have tried radio streaming apps from Google Play, and they are not killed either when switching to another user. – Xavi Gil Mar 13 '13 at 17:53

1 Answers1

18

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.

CommonsWare
  • 986,068
  • 189
  • 2,389
  • 2,491
  • If the app gets killed in the meantime, ACTION_USER_FOREGROUND will not be called when switching back to the original user. Is there some way to make sure that the app is launched when user switching happens (in a similar way to `ACTION_BOOT_COMPLETED` starts the app when device boots)? – Petrakeas Nov 27 '19 at 18:38
  • @Petrakeas: Sorry, this answer was from 6.5 years ago, and I have not used those broadcasts in the interim. – CommonsWare Nov 27 '19 at 22:08