What is bindServiceAsUser() method in Android?

7.4k Views Asked by At

I cannot understand what is the bindServiceAsUser() method used for. Can anyone please kindly explain about it ? Googling seems doesn't help much.

    public boolean bindService(Intent intent, ServiceConnection connection, int flags) {
    return mContext.bindServiceAsUser(intent, connection, flags, UserHandle.OWNER);
}
2

There are 2 best solutions below

1
On

I've never felt the need to use bindServiceAsUser(), but here's what the Android documentation has to say about it:

Same as bindService(android.content.Intent,android.content.ServiceConnection,int), but with an explicit userHandle argument for use by system server and other multi-user aware code.

The multi-user support was added in Android 4.2 (API: 17), read about it HERE. In my understanding it'll be mostly used by device manufacturers, releasing special devices for the Enterprise world for example. The best doc for multi-users I've found is THIS one, along with all referenced links there.

0
On

As Vesko said, in most android devices multi user is disabled. Some device manufacturers enable it. Foe example you have to bind a service with AIDl and disable a feature for a user in your privileged app. Here you need to know bind service as which user. We can invoke bindServiceAsUser using reflection.

  UserManager um = (UserManager) getSystemService(Context.USER_SERVICE);
        UserHandle owner = null;
                    owner = um.getUserForSerialNumber(0L);
                  try {
            MethodUtils.invokeMethod(getApplicationContext(), "bindServiceAsUser", new Object[]{i, serviceConnection, Context.BIND_AUTO_CREATE, owner});
        } catch (NoSuchMethodException | IllegalAccessException | InvocationTargetException e) {
            e.printStackTrace();
        }