问题
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