Example: Communication between Activity and Service using Messaging

前端 未结 9 678
既然无缘
既然无缘 2020-11-22 00:06

I couldn\'t find any examples of how to send messages between an activity and a service, and I have spent far too many hours figuring this out. Here is an example project fo

9条回答
  •  遥遥无期
    2020-11-22 01:02

    This is how I implemeted Activity->Service Communication: on my Activity i had

    private static class MyResultReciever extends ResultReceiver {
         /**
         * Create a new ResultReceive to receive results.  Your
         * {@link #onReceiveResult} method will be called from the thread running
         * handler if given, or from an arbitrary thread if null.
         *
         * @param handler
         */
         public MyResultReciever(Handler handler) {
             super(handler);
         }
    
         @Override
         protected void onReceiveResult(int resultCode, Bundle resultData) {
             if (resultCode == 100) {
                 //dostuff
             }
         }
    

    And then I used this to start my Service

    protected void onCreate(Bundle savedInstanceState) {
    MyResultReciever resultReciever = new MyResultReciever(handler);
            service = new Intent(this, MyService.class);
            service.putExtra("receiver", resultReciever);
            startService(service);
    }
    

    In my Service i had

    public int onStartCommand(Intent intent, int flags, int startId) {
        if (intent != null)
            resultReceiver = intent.getParcelableExtra("receiver");
        return Service.START_STICKY;
    }
    

    Hope this Helps

提交回复
热议问题