注意:这仅适用于进程中的服务和活动,而不是像问题一样远程.
使用服务与活动进行通信涉及创建可以从活动传递到服务的侦听器.
您需要创建绑定到活动的服务.
第一步是提供服务.在服务中,确保您有一个Binder对象和返回绑定对象的方法.下面是我在我的服务中用来检索我的活页夹的示例.另请注意,此绑定程序有一个设置侦听器的方法,该侦听器将作为BoundServiceListener类型字段保存在服务中.
/**
* Class used for the client Binder. Because we know this service always
* runs in the same process as its clients,we don't need to deal with IPC.
*/
public class DownloadBgBinder extends Binder {
public DownloadBgService getService() {
// Return this instance of LocalService so clients can call public methods
return DownloadBgService.this;
}
public void setListener(BoundServiceListener listener) {
mListener = listener;
}
}
@Override
public IBinder onBind(Intent intent) {
return mBinder;
}
现在,您需要创建某种接口,您可以将其传递给服务可用于发送更新的binder对象.下面是我的BoundServiceListener.
public interface BoundServiceListener {
public void sendProgress(double progress);
public void finishedDownloading();
}
现在,在您的活动中,您需要创建一个用于绑定到服务的ServiceConnection对象.所以添加这样的东西.
/** Defines callbacks for service binding,passed to bindService() */
private ServiceConnection mConnection = new ServiceConnection() {
@Override
public void onServiceDisconnected(ComponentName arg0) {
mBound = false;
}
@Override
public void onServiceConnected(ComponentName name,IBinder service) {
// We've bound to LocalService,cast the IBinder and get LocalService instance
DownloadBgBinder binder = (DownloadBgBinder) service;
mService = binder.getService();
binder.setListener(new BoundServiceListener() {
@Override
public void sendProgress(double progress) {
// Use this method to update our download progress
}
@Override
public void finishedDownloading() {
}
});
mBound = true;
}
现在要注意的关键是
binder.setListener(new BoundServiceListener() {
@Override
public void sendProgress(double progress) {
// Use this method to update our download progress
}
@Override
public void finishedDownloading() {
}
});
这部分是我实际将BoundServiceListener接口发送到服务类的地方.然后,服务类在此处使用该侦听器对象
if (mListener!=null)
mListener.finishedDownloading();
if (mListener!=null)
mListener.sendProgress(percent);
现在,您可以将它放在服务类中的任何位置,您的活动将收到进度更新.
还要确保在您的活动中包含以下内容以实际绑定和启动服务.
Intent intent = new Intent(this,DownloadBgService.class);
startService(intent);
bindService(intent,mConnection,Context.BIND_AUTO_CREATE);
请记住,即使您绑定到服务,它也不会实际启动,直到您调用启动服务.绑定到服务只是将服务连接到活动. startService()方法调用服务
onStartCommand(Intent intent,int flags,int startId)
同时在清单中声明您的服务
在活动离开时也取消绑定服务
@Override
protected void onStop() {
super.onStop();
// Unbind from the service
if (mBound) {
unbindService(mConnection);
mBound = false;
}
}
希望这可以帮助.