title: How to detect switching between users
body: <p>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.</p>
  
  <p>Is there any broadcast receiver I can register to get notified?</p>
  
  <p>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?</p>
  
  <hr>
  
  <p><strong>ANSWER EXPLAINED</strong></p>
  
  <p>Thanks @CommonsWare for the correct answer. I will explain a bit more how to detect a user switch.</p>
  
  <p>First be aware that the documentation explicitly says that receivers must be registered  through <code>Context.registerReceiver</code>. Therefore do something like:</p>
  
  <pre><code>UserSwitchReceiver receiver = new UserSwitchReceiver();
  IntentFilter filter = new IntentFilter();
  filter.addAction( Intent.ACTION_USER_BACKGROUND );
  filter.addAction( Intent.ACTION_USER_FOREGROUND );
  registerReceiver( receiver, filter );
  </code></pre>
  
  <p>Then in the receiver you can also retrieve the user id. Here is a small snippet:</p>
  
  <pre><code>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 );
      }
  }
  </code></pre>