Vin*_*ay 0 service binding android android-activity
我有一个服务组件(我所有应用程序的常见任务),可以由任何应用程序调用.我试图从所有活动中访问服务对象,我注意到创建服务的那个[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;
}
Run Code Online (Sandbox Code Playgroud)
如果我调用startService(intent).它创建一个新服务并与其他服务并行运行.
如果我不调用startService(intent),serviceObj.getData()将返回null值.
任何人都可以告诉我哪里出错了.
任何类型的指针都非常有用..
谢谢和问候,Vinay
如果我调用startService(intent).它创建一个新服务并与其他服务并行运行.
不,不是的.最多只有一个服务实例在运行.
如果我不调用startService(intent),serviceObj.getData()将返回null值.
startService()
从我的代码阅读中与它无关.您正在尝试使用serviceObj
在onCreate()
.那永远不会奏效.bindService()
是异步调用.在被叫serviveObj
之前你不能使用onServiceConnected()
.onServiceConnected()
在onCreate()
返回之后的某个时间才会被调用.
也:
startService()
和bindService()
,他们不都在正常情况下需要.getApplicationContext()
. 归档时间: |
|
查看次数: |
12363 次 |
最近记录: |