我创建了一个在整个应用期间在后台运行的服务
我为此选择了 IntentService
对我来说 intent.putExtra(....)仅在启动服务时起作用
我的问题是,有时我想将数据从活动传递到 IntentService ,不仅仅是在开始时。
谢谢
答案 0 :(得分:0)
只需将数据传输到IntentService
,因为IntentService
将始终在整个应用程序生命周期中只有一个实例。
答案 1 :(得分:0)
您可以使用bind界面与服务公共方法进行交互。
来自文档:
public class LocalService extends Service {
// Binder given to clients
private final IBinder mBinder = new LocalBinder();
// Random number generator
private final Random mGenerator = new Random();
/**
* 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 LocalBinder extends Binder {
LocalService getService() {
// Return this instance of LocalService so clients can call public methods
return LocalService.this;
}
}
@Override
public IBinder onBind(Intent intent) {
return mBinder;
}
/** method for clients */
public int getRandomNumber() {
return mGenerator.nextInt(100);
}
}