【发布时间】:2013-07-31 15:22:23
【问题描述】:
我在使用 AsyncTask 时遇到屏幕方向问题,即使它在 Service 中也是如此。
我的服务看起来像:
public class RequestService extends Service {
private MyBinder binder;
public RequestService(){
binder = new MyBinder(RequestService.this);
}
@Override
public IBinder onBind(Intent intent) {
return binder;
}
public class MyBinder extends Binder{
private final RequestService service;
public MyBinder(RequestService service){
this.service = service;
}
public RequestService getService(){
return this.service;
}
}
public <T> void sendRequest(Request<T> task, INotifyRequest<T> notify){
// Call excute the asynctask and notify result in onPostExcute
new TaskExecutor<T>(task, notify).execute();
}
}
更新:我这样使用我的服务:
// start the service
final Intent intent = new Intent(context, serviceClass);
context.startService(intent);
// then bound the service:
final Intent intentService = new Intent(context, serviceClass);
// Implement the Service Connection
serviceConnection = new RequestServiceConnection();
context.getApplicationContext().bindService(intentService, serviceConnection,
Context.BIND_AUTO_CREATE);
当方向改变时,服务被解除绑定然后重新绑定,AsyncTask 不会通知更新 UI。 我想知道为什么即使 AsyncTask 在 Service 中也会发生这种情况?
我读过this post,但我不想锁定屏幕方向或类似的东西。我更喜欢Service 而不是IntentService 因为Service 的灵活性,我可以将它与Binder 一起使用来获取Service 实例。
所以,问题是,有没有办法在Service 而不是AsyncTask 中实现线程安全?
【问题讨论】:
-
如果您使用
Context.startService()明确启动服务会怎样? -
@Karakuri 我使用bindService通过Service Connection中的binder获取服务实例
-
@Karakuri 抱歉,我只是重新检查了我的代码。它同时使用两种情况:startService 和 bindService,我在活动 onStart() 中启动服务,因此当方向改变时服务可以存活
标签: android android-asynctask android-service