应用程序 class 与 Android 中的服务之间的通信

Communication between an Application class and Service in Android

我有一个要求,我已经在我的 Android 项目中扩展了一个 "Application" class。

例如:

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

我可以使用我的 "Message.obtain" 通过 "Service" 进行通信吗?还是我应该使用其他东西?请指教

我还想将数据传递到我的服务,这是一个 String/constant 值。我可以这样做吗:

 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);  

             }  
         }  
     }  

试试这个: 在扩展应用程序 class 中创建一个内部 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   
            }
        }
    }

通过 Messenger 启动服务

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

在服务 onStartCommand 中获取信使

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

如果您想将数据从服务发送到 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)