Communication between an Application class and Service in Android

白昼怎懂夜的黑 提交于 2019-12-23 06:04:10

问题


I have a requirement where I have already extended an "Application" class in my Android Project.

eg:

  public class myApp extends Application implements
    myReceiver.Receiver {...}

Is it possible for me to communicate through a "Service" using my - "Message.obtain" or should I use other things? Please advice.

I also want to pass data to my Service which is a String/constant value. Can I do it like this :

 private void sendMsg(int arg1, int arg2) {  
        if (mBound) {  
            Message msg = Message.obtain(null, MyService.Hello,
                arg1, arg2);  
            try {  
                mService.send(msg);  
             } catch (RemoteException e) {  
                Log.e(TAG, "Error sending a message", e);  

             }  
         }  
     }  

回答1:


try this: in the extends Application class create one inner class

private class MyMessageHandler extends Handler {
    @Override
    public void handleMessage(Message msg) {
        super.handleMessage(msg);
        Bundle bundelData = msg.getData();
        if (bundelData != null) {
            String mString = (String) bundelData.get(IConstants.HOME_SCREEN_LISTUPDATE);
            if (mString != null) {
             // your logic   
            }
        }
    }

starting the service by passing the Messenger

Intent serviceIntent = new Intent(this, WatchService.class);
serviceIntent.putExtra(IConstants.MYMESSAGE_HANDLER, new Messenger(new MyMessageHandler));
startService(serviceIntent);

in the service onStartCommand get the messenger

if (intent != null) {
Bundle mExtras = intent.getExtras();
if (mExtras != null) {
Messenger innrMessenger = (Messenger)mExtras.get(IConstants.MYMESSAGE_HANDLER);
}
}

if you want to send data from service to that class

Message message = Message.obtain();
Bundle bundle = new Bundle();
bundle.putString(IConstants.HOME_SCREEN_LISTUPDATE, state);
message.setData(bundle);
innrMessenger.send(message);//get call back for handleMessage(Message msg)


来源:https://stackoverflow.com/questions/27794109/communication-between-an-application-class-and-service-in-android

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!