2013-07-31 29 views
0

當使用AsyncTask時,即使它在服務中,我也遇到了屏幕方向的問題。
我服務的樣子:AsynTask裏面的服務:處理屏幕方向

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。 我想知道爲什麼它可能發生在Service裏面甚至AsyncTask
我已閱讀this post,但我不想鎖定屏幕方向或類似的東西。我比更喜歡IntentService作爲Service的靈活,我可以使用它與Binder來獲取Service實例。
所以,問題是,是否有任何方法可以在Service而不是AsyncTask內部進行線程安全?

+0

如果你使用'Context.startService()'顯式啓動服務會怎麼樣? – Karakuri

+0

@Karakuri我使用bindService通過服務連接中的活頁夾獲取服務實例 – R4j

+0

您可以同時使用兩者。 – Karakuri

回答

0

如果您使用綁定服務請記住,如果沒有綁定活動,服務將被銷燬。我不知道你是否在onPause()中取消綁定,但是這會在方向改變時破壞你的服務。

因此,您將失去服務和對AsyncTask的引用。此外,沒有onRetainInstanceState()可用於服務,以保存AsyncTask並再次獲取它。

想一想IntentService在這種情況下,它將是正確的方法。或者如果你想讓服務使用startService(),在沒有活動綁定的時候保持活動狀態。那麼你仍然可以按照你想要的方式綁定和解除綁定。

下一點是保留AsyncTask的引用。因爲如果活動已被銷燬,則必須再次設置回調。因爲回調引用仍將被設置爲舊的活動。

希望這會有所幫助。

編輯:

那麼,如果你閱讀,也許你考慮使用IntentService或東西..

保持的AsyncTask的實例在服務和定義您的任務制定者回調。 如果活動在方向更改檢查後綁定到服務,則AsyncTask是否正在運行。如果它正在運行,則更新回調。你可以使用你的活頁夾。

+0

對不起,我缺少在代碼中發佈startService。我同時使用startService和bindService,並在activity的onStart()中啓動服務,因此我可以保持該服務的活力。你能否給我詳細的「保持AsyncTask參考」?我必須保持它在服務中的變量?那麼當活動重新創建時我會做什麼? – R4j

+0

我編輯了我的答案。 –