我有一个服务组件(适用于我所有应用程序的常见任务),它可以由任何应用程序调用。我试图从所有活动中访问服务对象,我注意到创建服务[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()会返回空值。
任何人都可以启发我在哪里出错了。
任何类型的指针将是非常有用的..
感谢和问候, 维奈
感谢您的回复。它帮助了我。 关于与其他服务并行运行的服务,我发现这是由于“新的Intent(this.context,Service.class)”。 我用“new Intent(”com.package“,”com.package.service“)替换了这个;” 感谢您的指点.. – Vinay 2010-08-06 06:48:28
您的意思是“不要使用getApplicationContext”。那么,这是否适用于http://stackoverflow.com/questions/3141632/android-service-interacting-with-multiple-activities的接受答案呢?我的答案是“错误”/违反规则吗? – OneWorld 2013-07-04 14:26:58
@OneWorld:我绝对不是“应用程序”中的“活动”来追踪“当前”活动“模式的粉丝。如果没有其他的话,一个静态数据成员的工作就会更好,并且具有更大的灵活性除此之外,防止“活动”被垃圾收集是麻烦的处方。 – CommonsWare 2013-07-04 15:00:04