注意:这仅适用于正在进行的服务和活动,不适用于远程提问。
使用服务与活动进行通信涉及创建一个侦听器,您可以将其从活动传递给服务。
您需要创建一个与活动绑定的服务。
第一步是提供服务。在服务中确保您有一个 Binder 对象和返回 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;
}
现在您需要创建某种可以传递给服务可以用来向其发送更新的活页夹对象的接口。下面是我的 BoundServiceListener。
public interface BoundServiceListener {
public void sendProgress(double progress);
public void finishedDownloading();
}
现在,在您的活动中,您需要创建一个用于绑定到服务的服务连接对象。添加这样的东西。
/** 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)
还要在清单中声明您的服务
<service android:name=".services.DownloadBgService" />
当活动结束时也解绑服务
@Override
protected void onStop() {
super.onStop();
// Unbind from the service
if (mBound) {
unbindService(mConnection);
mBound = false;
}
}
希望这可以帮助。