Service call backs to activity in android

后端 未结 1 843
北荒
北荒 2020-12-28 19:09

I have a background service running and a client which interacts with the service.

When the client requests for some operation, the service performs it and it should

相关标签:
1条回答
  • 2020-12-28 19:44

    Here is the flow
    Create your intent to call a service. You can either startService() or BindService() with BIND_AUTO_CREATE

    Once the service is bond, it will create a tunnel to talk with it clients which is the IBinder Interface. This is used by your AIDL Interface implementation and return the IBinder in

    private final MyServiceInterface.Stub mBinder = new MyServiceInterface.Stub() {
        public int getNumber() {
            return new Random().nextInt(100);
        }
    };
    
    public IBinder onBind(Intent intent) {
        // TODO Auto-generated method stub
        Toast.makeText(this, "Service OnBind()", Toast.LENGTH_LONG).show();
        return mBinder;
    }
    

    Once it returns the mBinder, ServiceConnection that you created in the client will be called back and you will get the service interface by using this

               mConnection = new ServiceConnection() {
    
            public void onServiceDisconnected(ComponentName name) {
                // TODO Auto-generated method stub
    
            }
    
            public void onServiceConnected(ComponentName name, IBinder service) {
                // TODO Auto-generated method stub
    
                mService = MyServiceInterface.Stub.asInterface(service);
    
    
        };
    

    Now you got the mService interface to call and retreive any service from that

    0 讨论(0)
提交回复
热议问题