我有一个服务在前台模式下运行,我想检测在Android 4.2或以上版本的平板电脑上用户会话之间的切换。
是否有广播接收器我可以注册得到通知?
我注意到,一旦在锁定屏幕上选择另一个用户会话,谷歌音乐就会停止音乐播放。它是如何检测开关的?
回答解释
感谢@CommonsWare的正确答案。我将进一步解释如何检测用户切换。
首先要注意文档明确指出接收者必须通过Context.registerReceiver
注册。因此,执行如下命令:
UserSwitchReceiver receiver = new UserSwitchReceiver();
IntentFilter filter = new IntentFilter();
filter.addAction( Intent.ACTION_USER_BACKGROUND );
filter.addAction( Intent.ACTION_USER_FOREGROUND );
registerReceiver( receiver, filter );
然后在接收器中也可以检索用户id。下面是一小段代码:
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 );
}
}
尝试ACTION_USER_FOREGROUND
和ACTION_USER_BACKGROUND
。我没有使用过它们,但它们是在API Level 17中添加的,它们的描述似乎会有所帮助。