Android中的service是运行在后台的组件,如果其他组件(比如Activity)需要与后台的service交互,有以下三个途径:
一,若参与交互的Service,Activity运行在一个进程中(可简单理解为同一个APP中)。
那么只需要在Service的onBind方法中返回一个你自己实现的Binder对象(这个Binder类是service的内部类),然后就可以通过这个Binder对象与service交互,比如说可以在Binder类中实现一个方法将Service对象引用直接返回,从而可以让Activity直接调用Service的public方法,实例关键代码如下:
Activity端代码:
import com.example.startservicetest.MainService.LocalBinder;
public class MainActivity extends ActionBarActivity implements OnClickListener{
private Button btn_bind_in_same_service;
private ServiceConnection conn = new ServiceConnection() {
@Override
public void onServiceDisconnected(ComponentName name) {
// TODO Auto-generated method stub
}
@Override
public void onServiceConnected(ComponentName name, IBinder service) {
// TODO Auto-generated method stub
LocalBinder binder = (LocalBinder)service;
MainService mainService = binder.getService();
String res = mainService.getString();
Log.i("dazhou", "bind service result:"+res);
}
};
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
btn_bind_in_same_service = (Button)findViewById(R.id.btn_bind_service_in_same_app);
btn_bind_in_same_service.setOnClickListener(this);
}
@Override
public void onClick(View v) {
// TODO Auto-generated method stub
int id = v.getId();
Intent intent;
switch (id) {
case R.id.btn_bind_service_in_same_app:
Log.i("dazhou", "bind service in same app");
intent = new Intent(this, MainService.class);
bindService(intent, conn, Context.BIND_AUTO_CREATE);
break;
default:
break;
}
}
}
Service端代码:
public class MainService extends Service {
private LocalBinder mBinder = new LocalBinder();
@Override
public IBinder onBind(Intent intent) {
// TODO Auto-generated method stub
return mBinder;
}
@Override
public void onCreate() {
// TODO Auto-generated method stub
super.onCreate();
Log.i("dazhou", "MainService onCreate");
}
@Override
public int onStartCommand(Intent intent, int flags, int startId) {
// TODO Auto-generated method stub
Log.i("dazhou", "MainService onStartCommand");
return super.onStartCommand(intent, flags, startId);
}
@Override
public void onDestroy() {
// TODO Auto-generated method stub
super.onDestroy();
}
public String getString(){
return "dazhou";
}
public class LocalBinder extends Binder{
public MainService getService(){
return MainService.this;
}
}
}
二,若Service在进程之间被bind(可以理解为多APP之间)
可以使用Messenger类来实现,方法步骤:首先在Service中构造一个Handler类,用于处理客户端发来的各种消息;其次,在Service中以刚才创建的Handler类的对象为参数创建一个Messenger对象;最后,在Service的onBind方法中返回Messenger.getBinder()。与此同时,也可以在调用Service的Activity中创建Messenger,并将该Messeneger通过Message的replyTo域传给Service,这样就可在Service中向Activity返回消息。这是Google推荐的最简便的IPC方法,因为Messenger将所有的请求放入一堆队列,并使用单线程处理,这么以来开发者就不用考虑自己所实现Service的线程安全问题。实例关键代码如下:
Activity端代码:
public class MainActivity extends ActionBarActivity implements OnClickListener{
private Button btn_bind_in_diff_service;
private ServiceConnection remoteConn = new ServiceConnection() {
@Override
public void onServiceDisconnected(ComponentName name) {
// TODO Auto-generated method stub
}
@Override
public void onServiceConnected(ComponentName name, IBinder service) {
// TODO Auto-generated method stub
Messenger messenger = new Messenger(service);
Message msg = Message.obtain(null, 1, 0, 0);
msg.replyTo = mMessenger;
try {
messenger.send(msg);
} catch (RemoteException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
};
public class IncomingHandler extends Handler{
@Override
public void handleMessage(Message msg) {
// TODO Auto-generated method stub
super.handleMessage(msg);
int what = msg.what;
switch (what) {
case 2:
Log.v("dazhou", "service return value to activity");
break;
default:
break;
}
}
}
private Messenger mMessenger = new Messenger(new IncomingHandler());
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
btn_bind_in_diff_service = (Button)findViewById(R.id.btn_bind_service_in_diff_app);
btn_bind_in_diff_service.setOnClickListener(this);
}
@Override
public void onClick(View v) {
// TODO Auto-generated method stub
int id = v.getId();
Intent intent;
switch (id) {
case R.id.btn_bind_service_in_diff_app:
Log.i("dazhou", "bind service in diff app");
intent = new Intent();
intent.setAction("your action");
//startService(intent);
bindService(intent, remoteConn, Context.BIND_AUTO_CREATE);
break;
default:
break;
}
}
}
Service端代码:
public class RemoteService extends Service {
public Messenger mMessenger = new Messenger(new IncomingHandler());
@Override
public IBinder onBind(Intent intent) {
// TODO Auto-generated method stub
Log.i("dazhou", "remote service onBind");
return mMessenger.getBinder();
}
@Override
public void onCreate() {
// TODO Auto-generated method stub
Log.i("dazhou", "remote service onCreate");
super.onCreate();
}
@Override
public int onStartCommand(Intent intent, int flags, int startId) {
// TODO Auto-generated method stub
Log.i("dazhou", "remote service onStartCommand");
return super.onStartCommand(intent, flags, startId);
}
public class IncomingHandler extends Handler{
@Override
public void handleMessage(Message msg) {
// TODO Auto-generated method stub
super.handleMessage(msg);
switch (msg.what) {
case 1:
Log.i("dazhou", "Remote service incominghandler handlemessage:"+msg.what);
Messenger activityMessenger = msg.replyTo;
if(activityMessenger!=null){
try {
Log.v("dazhou", "remote service has receive the activityMessenger:"+activityMessenger.hashCode());
activityMessenger.send(Message.obtain(null, 2, 0, 0));
} catch (RemoteException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
break;
default:
break;
}
}
}
}