首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >AsynTask内部服务:处理屏幕方向

AsynTask内部服务:处理屏幕方向
EN

Stack Overflow用户
提问于 2013-07-31 15:22:23
回答 1查看 188关注 0票数 0

我在使用AsyncTask时遇到了屏幕定位问题,即使它是inside服务。

我的服务看起来像是:

代码语言:javascript
复制
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();
}
}

更新:我这样使用我的服务:

代码语言:javascript
复制
 // 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__中也会发生呢?

我读过这个职位,但我不想锁定屏幕方向或类似的东西。我更喜欢Service而不是IntentService,因为Service是灵活的,我可以与Binder一起使用它来获取服务实例。

因此,问题是,是否有任何方法可以在Service内部而不是AsyncTask中实现线程安全?

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2013-07-31 16:00:25

如果使用绑定服务,请记住,如果没有绑定活动,则服务将被销毁。我不知道您是否在onPause()中解除了绑定,但是这会破坏您的服务在方向上的改变。

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

考虑一下IntentService,在这种情况下,这将是正确的方法。或者,如果您希望保持服务,请使用startService(),以便在没有绑定活动的情况下保持它的活力。然后,您仍然可以以您想要的方式从服务中绑定和解除绑定。

下一点是保留对AsyncTask的引用。因为如果活动被破坏,您必须再次设置回调。因为回调引用仍将设置为旧活动。

希望这能有所帮助。

编辑:

嗯,如果你读到这篇文章,也许你会考虑使用IntentService之类的。

在服务中保留一个AsyncTask实例,并在任务中为回调定义一个setter。如果您的活动在更改方向后绑定到服务,则检查AsyncTask是否正在运行。如果它正在运行,更新回调。你可以用你的粘合剂。

票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/17974432

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档