Thursday, February 1, 2018

Listen for user changed event (multi user device)

Leave a Comment

I've an app that starts itself if the phone is booted. A user told me his phone is used by two people, one of them is using my app and one not.

So I need some event to listen to when the user is switched, so that I can start my apps service if the correct user is using the phone. Anything I can use for that?

Edit

I'm listening to the boot event with a broadcast receiver registered in the manifest, so I know what this is. But I could not find anything suitable for switching users on a device

2 Answers

Answers 1

Doing tricky: Register background|foreground action event broadcast receiver and check for switching user:

ACTION_USER_BACKGROUND and ACTION_USER_FOREGROUND

Full source code:https://readyandroid.wordpress.com/event-for-switch-user-multiusersupport-android/

Many more:https://readyandroid.wordpress.com/

Answers 2

You need to look for something called BroadcastReciever in android. They are used to capture events such as camera click, phone booting up, screen unlocked etc... These events have a callback called onReceive where you can implement your login.

It's quite easy and you can Google it.

In your manifest:

<uses-permission android:name="android.permission.RECEIVE_BOOT_COMPLETED" />  

In your application element (be sure to use a fully-qualified [or relative] class name for your BroadcastReceiver):

<receiver android:name="com.example.MyBroadcastReceiver">       <intent-filter>           <action android:name="android.intent.action.BOOT_COMPLETED" />       </intent-filter>   </receiver> 

In MyBroadcastReceiver.java:

package com.example;  public class MyBroadcastReceiver extends BroadcastReceiver {     @Override     public void onReceive(Context context, Intent intent) {         Intent startServiceIntent = new Intent(context, MyService.class);         context.startService(startServiceIntent);     } } 
If You Enjoyed This, Take 5 Seconds To Share It

0 comments:

Post a Comment