When to use Messanger Approach
If you need your service to communicate with remote processes, then you can use a Messenger to provide the interface for your service. This technique allows you to perform interprocess communication (IPC) without the need to use AIDL.
Create one Class and extend Service. Register this inside android manifest.
Not make necessary changes to your service class. Create one handler class for Messanger. Handler class will handle communication with Activity.
import android.app.Service;
import android.content.Intent;
import android.os.Handler;
import android.os.IBinder;
import android.os.Message;
import android.os.Messenger;
import android.widget.Toast;
public class UsingMessanger extends Service {
final public static int Msg = 1;
@Override
public void onCreate() {
super.onCreate();
}
@Override
public IBinder onBind(Intent arg0) {
Messenger mssMessenger = new Messenger(new HandlerMessag());
return mssMessenger.getBinder();
}
public class HandlerMessag extends Handler {
@Override
public void handleMessage(Message msg) {
switch (msg.what) {
case Msg:
Toast.makeText(getApplicationContext(), "Service: I got your message",
Toast.LENGTH_SHORT).show();
break;
default:
super.handleMessage(msg);
}
}
}
}
Now change the activity to handle Service connection. import android.app.Activity;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.ServiceConnection;
import android.os.Bundle;
import android.os.IBinder;
import android.os.Message;
import android.os.Messenger;
import android.os.RemoteException;
public class MessangerActivity extends Activity {
Messenger messenger;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
bindService();
}
public void bindService() {
Intent intent = new Intent(this, UsingMessanger.class);
bindService(intent, new ConnectService(), Context.BIND_AUTO_CREATE);
}
public void stoppingService() {
Intent intent = new Intent(this, UsingMessanger.class);
stopService(intent);
}
public class ConnectService implements ServiceConnection {
@Override
public void onServiceConnected(ComponentName name, IBinder service) {
messenger = new Messenger(service);
Message msg = Message.obtain(null, UsingMessanger.Msg, 0, 0);
try {
messenger.send(msg);
} catch (RemoteException e) {
e.printStackTrace();
}
}
@Override
public void onServiceDisconnected(ComponentName name) {
/**
* Called when service disconnected
*/
}
}
}
[...] Binding service is used when you want to communicate with service either it for updating UI with the work you are doing in service or using values of service’s current instance. See binding service using Messanger [...]
ReplyDelete[...] Binding service using Messenger in android [...]
ReplyDelete