13
我有一個服務在前臺模式下運行,我想檢測運行Android 4.2或更高版本的平板電腦上的用戶會話之間的切換。如何檢測用戶之間的切換
有沒有我可以註冊的廣播接收器來獲得通知?
我注意到,一旦在鎖定屏幕上選擇了另一個用戶會話,Google音樂就會停止音樂播放。它如何檢測交換機?
ANSWER EXPLAINED
感謝@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);
然後在接收器中,您還可以檢索用戶標識。這裏是一個小片段:
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);
}
}
我很驚訝,服務繼續在你的情況下運行。你真的檢查過它繼續嗎? – 2013-03-13 17:25:55
是的。一方面,我可以看到我的應用程序的日誌形成另一個用戶的帳戶。另一方面,當我回到原始用戶(運行我的服務)時,前臺通知圖標就在那裏。日誌中沒有指示服務已停止的消息。 – 2013-03-13 17:36:50
我已經嘗試了Google Play的廣播流應用,並且在切換到其他用戶時也不會死亡。 – 2013-03-13 17:53:04