Example: Communication between Activity and Service using Messaging

前端 未结 9 645
既然无缘
既然无缘 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 00:42

    Great tutorial, fantastic presentation. Neat, simple, short and very explanatory. Although, notification.setLatestEventInfo(this, getText(R.string.service_label), text, contentIntent); method is no more. As trante stated here, good approach would be:

    private static final int NOTIFICATION_ID = 45349;
    
    private void showNotification() {
        NotificationCompat.Builder builder =
                new NotificationCompat.Builder(this)
                        .setSmallIcon(R.mipmap.ic_launcher)
                        .setContentTitle("My Notification Title")
                        .setContentText("Something interesting happened");
    
        Intent targetIntent = new Intent(this, MainActivity.class);
        PendingIntent contentIntent = PendingIntent.getActivity(this, 0, targetIntent, PendingIntent.FLAG_UPDATE_CURRENT);
        builder.setContentIntent(contentIntent);
        _nManager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
        _nManager.notify(NOTIFICATION_ID, builder.build());
    }
    
    @Override
    public void onDestroy() {
        super.onDestroy();
        if (_timer != null) {_timer.cancel();}
        _counter=0;
        _nManager.cancel(NOTIFICATION_ID); // Cancel the persistent notification.
        Log.i("PlaybackService", "Service Stopped.");
        _isRunning = false;
    }
    

    Checked myself, everything works like a charm (activity and service names may differ from original).

    0 讨论(0)
  • 2020-11-22 00:43

    Look at the LocalService example.

    Your Service returns an instance of itself to consumers who call onBind. Then you can directly interact with the service, e.g. registering your own listener interface with the service, so that you can get callbacks.

    0 讨论(0)
  • 2020-11-22 00:43

    Seems to me you could've saved some memory by declaring your activity with "implements Handler.Callback"

    0 讨论(0)
  • 2020-11-22 00:48

    Everything is fine.Good example of activity/service communication using Messenger.

    One comment : the method MyService.isRunning() is not required.. bindService() can be done any number of times. no harm in that.

    If MyService is running in a different process then the static function MyService.isRunning() will always return false. So there is no need of this function.

    0 讨论(0)
  • 2020-11-22 00:51

    I have seen all answers. I want tell most robust way now a day. That will make you communicate between Activity - Service - Dialog - Fragments (Everything).

    EventBus

    This lib which i am using in my projects has great features related to messaging.

    EventBus in 3 steps

    1. Define events:

      public static class MessageEvent { /* Additional fields if needed */ }

    2. Prepare subscribers:

    Declare and annotate your subscribing method, optionally specify a thread mode:

    @Subscribe(threadMode = ThreadMode.MAIN) 
    public void onMessageEvent(MessageEvent event) {/* Do something */};
    

    Register and unregister your subscriber. For example on Android, activities and fragments should usually register according to their life cycle:

    @Override
    public void onStart() {
        super.onStart();
        EventBus.getDefault().register(this);
    }
    
    @Override
    public void onStop() {
        super.onStop();
        EventBus.getDefault().unregister(this);
    }
    
    1. Post events:

      EventBus.getDefault().post(new MessageEvent());

    Just add this dependency in your app level gradle

    compile 'org.greenrobot:eventbus:3.1.1'
    
    0 讨论(0)
  • 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
         * <var>handler</var> 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

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