【问题标题】:AsynTask inside service: dealing with Screen Orientation服务内部的 AsyncTask:处理屏幕方向
【发布时间】: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。 我想知道为什么即使 AsyncTaskService 中也会发生这种情况?
我读过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


【解决方案1】:

如果您使用绑定的服务,请记住,如果没有绑定任何活动,该服务将被销毁。我不知道您是否在 onPause() 中取消绑定,但这会在方向更改时破坏您的服务。

因此,您将失去服务和对 AsyncTask 的引用。此外,没有可用于服务的 onRetainInstanceState() 来保存 AsyncTask 并再次获取它。

考虑在这种情况下使用 IntentService 是正确的方法。或者,如果您想保留服务,请使用 startService(),以便在未绑定任何 Activity 时使其保持活动状态。然后你仍然可以按照你想要的方式绑定和取消绑定服务。

下一点是保留 AsyncTask 的引用。因为如果 Activity 被销毁,您必须再次设置回调。因为回调引用仍然会设置为旧的 Activity。

希望这会有所帮助。

编辑:

如果你读到了,也许你会考虑使用 IntentService 之类的......

在服务中保留一个 AsyncTask 的实例,并在您的任务中为您的回调定义一个设置器。 如果您的 Activity 在方向更改检查后绑定到服务,则 AsyncTask 是否正在运行。如果它正在运行更新回调。你可以使用你的活页夹。

【讨论】:

  • 抱歉,我没有在我的代码中发布 startService。我同时使用 startService 和 bindService 并在活动的 onStart() 中启动服务,因此我可以保持服务处于活动状态。您能给我详细说明“保留 AsyncTask 的参考”吗?我必须保持它作为服务变量?那么当Activity重新创建时我会怎么做呢?
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2011-06-13
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多