在使用Activity与Service交互时,遇到了调用不了Service方法的情况。
在android项目中用到AIDL,在Activity中进行绑定服务,代码如下:
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
if(databaseService == null){
Intent intent = new Intent();
ComponentName componentName = new ComponentName("com.example.service",
"com.example.service.DatabaseService");//第一个参数为包名,第二个为类名
intent.setComponent(componentName);
context.bindService(intent, connection, Service.BIND_AUTO_CREATE);
}
}
private ServiceConnection connection = new ServiceConnection(){
@Override
public void onServiceConnected(ComponentName name, IBinder service) {
// TODO Auto-generated method stub
databaseService = IDatabaseService.Stub.asInterface(service);
}
@Override
public void onServiceDisconnected(ComponentName name) {
// TODO Auto-generated method stub
}
};
通过日志打印,发现在bindService(intent,connection,Service.BIND_AUTO_CREATE)之后一直不调用 connection中的onServiceConnected方法。
在网上查了很久,发现可能出现的原因有:
①服务器端的service声明,要和客户端bindService的参数匹配,不然客户端启动不了这个服务。
<service ? ? ? ? ? ? android:name="com.example.service.DatabaseService" > ? ? ? ? ? ? <intent-filter> ? ? ? ? ? ? ? ? <action android:name="com.example.service" /> ? ? ? ? ? ? </intent-filter> ? </service>
②服务器端service必须 return实现AIDL接口IDatabaseService.Stub 的binder
public IBinder onBind(Intent intent) {
// TODO Auto-generated method stub
return binder;
}
但是我的代码不是以上两个问题,于是我又开始寻找问题的解决方法,最终发现是因为
在bindService后马上调用Service中的方法,结果返回了空指针,因为bindservice是异步操作,有时候没有办法马上绑定服务就可以用。
于是我就在bindService时设置了如果Service返回的是空指针,则进行循环bindService,超过三次后退出循环。
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
int count =0;
try{
while(databaseService == null){
Intent intent = new Intent();
ComponentName componentName = new ComponentName("com.example.service",
"com.example.service.DatabaseService");
context.bindService(intent, connection, Service.BIND_AUTO_CREATE);
if(count == 3){
return;
}
count ++;
Thread.sleep(500);
}
}catch(Exception e){
e.printStackTrace();
}
}
|