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

前端 未结 6 1921
说谎
说谎 2020-12-03 03:17

I have a service in an application, and I can reach this service from different applications. And when applications are tried to bind this service I want to know which appli

6条回答
  •  遥遥无期
    2020-12-03 04:04

    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

提交回复
热议问题