How to get application package name or UID which is trying to bind my service from onBind function?

You can use the following to determine the calling application.

 String callingApp = context.getPackageManager().getNameForUid(Binder.getCallingUid());

It's important to note the JavaDoc for getCallingUid() which says:

Return the Linux uid assigned to the process that sent you the current transaction that is being processed. This uid can be used with higher-level system services to determine its identity and check permissions. If the current thread is not currently executing an incoming transaction, then its own uid is returned.


You can't do this.

onBind() is called from the Android "lifecycle manager" (making up a helpful name), and will only be called once for each Intent (so it can learn which Binder should be returned for that Intent).

The calls to your service then come in over that Binder, and you can do Binder.getCallingUid() in any one of those methods.


The above accepted answer did not worked for me. But a small modification did the trick. This works quite well with Messenger based communication.

public class BoundService extends Service {

    public static final int TEST = 100;
    private final Messenger messenger = new Messenger(new MessageHandler());

    class MessageHandler extends Handler {
        @Override
        public void handleMessage(Message msg) {

            String callerId = getApplicationContext().getPackageManager().getNameForUid(msg.sendingUid);
            Toast.makeText(getApplicationContext(), "Calling App: " + callerId, Toast.LENGTH_SHORT).show();

            switch (msg.what) {
                case TEST:
                    Log.e("BoundService", "Test message successfully received.")
                    break;
                default:
                    super.handleMessage(msg);
            }
        }
    }

    @Override
    public IBinder onBind(Intent intent) {
        return messenger.getBinder();
    }
}

From the above answer, you only need to change from Binder.getCallingUid() to msg.sendingUid

Tags:

Android