[英]Multiple activities binding to a service
我有一个服务组件(我所有应用程序的共同任务),可以由任何应用程序调用。 我正在尝试从所有活动访问服务对象,我注意到创建服务[startService(intent)]的对象具有正确的信息。 但是休息并不能获得所需的信息。 我的代码如下:
// Activity.java
public void onCreate(Bundle savedInstanceState) {
...
Intent intent = new Intent (this.context, Service.class) ;
this.context.startService(intent) ;
this.context.bindService(intent, this, Context.BIND_AUTO_CREATE) ;
...
String result = serviceObj.getData() ;
}
public void onServiceConnected(ComponentName name, IBinder service) {
serviceObj = ((Service.LocalBinder)service).getService();
timer.scheduleAtFixedRate(task, 5000, 60000 ) ;
}
// Service.java
private final IBinder mBinder = new LocalBinder();
public class LocalBinder extends Binder {
Service getService() {
return Service.this;
}
}
public void onCreate() {
super.onCreate();
context = getApplicationContext() ;
}
public void onStart( Intent intent, int startId ) {
... some processing is done here...
}
public IBinder onBind(Intent intent) {
return mBinder;
}
如果我调用startService(intent)。 它创建一个新服务并与其他服务并行运行。
如果我不调用startService(intent),则serviceObj.getData()重新调整null值。
任何人都可以启发我哪里做错了。
任何一种指针都将非常有用。
感谢和问候,Vinay
如果我调用startService(intent)。 它创建一个新服务并与其他服务并行运行。
不,不是的。 您的服务最多将运行一个实例。
如果我不调用startService(intent),则serviceObj.getData()重新调整null值。
根据我对代码的阅读, startService()
与它无关。 您正在尝试在onCreate()
使用serviceObj
。 那永远都行不通。 bindService()
是一个异步调用。 在调用onServiceConnected()
之前,不能使用serviveObj
。 直到onCreate()
返回后的某个时间才会调用onServiceConnected()
。
也:
startService()
和bindService()
,但在通常情况下并不需要。 getApplicationContext()
。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.