Revision 2: How to pass data from a background Service/thread to some other activity than the MainActivity that created the background service

后端 未结 1 577
深忆病人
深忆病人 2020-12-05 21:27

I\'ve created a simple Android application for testing how to use a handler or handlers to pass data from a background Service/thread to some other activity other t

相关标签:
1条回答
  • 2020-12-05 21:59

    The Handler is associated with specific thread, so for as long as you create it in UI thread all you need to do is to share the handler. I would put your handler in my Application class. And you can put the whole Messenger there, if you want. Then you can access handler in any activity via ((MyApplication)getApplication()).getHandler(). When activity starts or pauses, you can register it as a callback.

    So something like this

    public class MyApplication extends Application {
       Handler h = new Handler() {
          public void handleMessage(Message m) {
            if (realCallback!=null) {
               realCallback.handleMessage(m);
            }
          }
       };
       Handler.Callback realCallback=null;
       ......
       public Handler getHandler() {
          return h;
       }
    
       public void setCallback(Handler.Callback c) {
          realCallback = c;
       }
    }
    

    In any activity that needs to do receive requests via messenger

    public class MyActivity extends Activity implements Handler.Callback
    
    ......
    
    public void onStart() {
       ((MyApplication)getApplication()).setCallback(this);
    }
    
    public void onPause() {
       ((MyApplication)getApplication()).setCallback(null);
    }
    
    public void handleMessage(Message msg) {
      //.... Do stuff ....
    }
    

    }

    This is just an idea. You may need to tune it to your needs.

    And don't forget to set MyApplication name in AndroidManifest.xml

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