2014-11-22 1 views
2

활동의 AsyncTask에서 IntentService로 이동하려고합니다. 내 주요 목표는 가능한 한 많은 활동을 유지하여 결과를 처리하는 활동에 의존하지 않고 응용 프로그램의 다른 위치에서 서비스를 쉽게 트리거 할 수있게하는 것입니다.IntentService의 경우 onPostExecute와 비슷한 항목이 있습니까?

AsyncTask에서 나는 엄청난 양산 작업이 끝난 후에도 결과를 처리하기 위해 onPostExecute를 사용했지만, IntentService에는 존재하지 않는 것 같습니다. 그 결과 데이터를 소포해야하기 때문에 ResultReceiver를 사용하는 아이디어가 싫다. 주 스레드가 강제로 비 직렬화를 처리해야한다. 거기에 다른 방법을 내가 돌아 다니는 대신 및 ResultReceiver AsyncTask 결과를 deserialize 데 사용하는 다른 누락 된 있어요?

감사합니다.

업데이트

더 나은 아무것도 올 수없는, 그래서 ResultReceiver를 사용하여 끝났다. 내 서비스는 프리미티브 데이터 (문자열)를 수신자에게 반환 한 다음 수신자가 문자열을 파싱하고 Java 객체를 만듭니다. 수신자는 강력한 형식의 개체로 내 활동을 다시 호출합니다. 그것은 훌륭하게 작동하지만 서비스, 수신자 및 내부 수신기 콜백 클래스를 사용하는 데는 어색한 느낌이 듭니다.

+0

onstart 메서드에서 asycntask를 호출 할 수 있습니다. – koutuk

답변

0

Asynctask에서 onPostExecute는 UI 스레드에서 실행됩니다. 따라서 UI 스레드에서 주 작업을 수행하려는 경우 onPostExecute에 대한 결과 처리가 도움이되지 않습니다. 당신은 백그라운드 스레드 자체에서 역 직렬화와 같이 무거운 작업을 수행 할 수 있습니다. 웹 서비스 호출 인 경우 동일한 서비스 스레드에서 서비스 호출 및 결과 처리를 수행하십시오.

+0

그러나 AsyncTask를 사용하면 일반 데이터를 onPostExecute에 다시 전달할 수 있습니다. IntentService에 대한 인상은 소포 할 수있는 데이터를 번들에 넣어야하므로 처리기가 해당 데이터를 최종 형식으로 변환해야합니다. 만약 내가 누락 된 뭔가가 궁금하네요. 그저 돌아 서서 AsyncTask의 doInBackground를 사용하여 ResultReceiver 내부에서 데이터를 파싱해야합니다. (메인 스레드에서 실행하고 싶지 않기 때문입니다.) IntentActivity에서 모든 작업을 수행하기를 바라고 있지만이 작업을 ResultReceiver와 분리해야합니다. 희망이 내 질문을 명확히합니다. – Dennis

0

메인 스레드에 연결된 Handler을 사용하여 직접 구현할 수 있습니다. A Handleris tied to the thread that creates it. 따라서, 주 스레드에 의해 호출되는 코드 블록에 Handler을 생성함으로써. onCreate()의 일부로 메인 스레드 작업 목록에 연결됩니다. 이제 onHandleIntent(Intent intent) 구현의 마지막 단계에서 기본 스레드에서 실행하려는 문 집합을 Handler 인스턴스에 게시하면됩니다.

예제 코드 :

import android.app.IntentService; 
import android.content.Intent; 
import android.os.Handler; 
import android.widget.Toast; 

/** 
* @author Janus Varmarken ([email protected]). 
*/ 
public class ExampleIntentService extends IntentService { 

    // Handler tied to the main thread. 
    private Handler mHandler; 

    public ExampleIntentService() { 
     super(ExampleIntentService.class.getSimpleName()); 
    } 

    @Override 
    public void onCreate() { 
     // Make sure to call super such that IntentService can properly manage its lifecycle 
     // (it needs to create a background thread and manage a job list for this thread) 
     super.onCreate(); 

     // As onCreate is run on the main thread, we can tie a Handler to the main thread by 
     // creating it here. 
     mHandler = new Handler(); 
    } 

    @Override 
    protected void onHandleIntent(Intent intent) { 
     // Do heavy lifting here... 
     // Here we just sleep for the sake of the example. 
     try { 
      Thread.sleep(5000); 
     } catch (InterruptedException e) { 
      e.printStackTrace(); 
     } 

     // When heavy lifting is done: 
     // Create a runnable containing the statements you want to run on the main/UI thread. 
     Runnable uithreadStatements = new Runnable() { 
      @Override 
      public void run() { 
       // main/UI thread statements goes here. 
       Toast.makeText(ExampleIntentService.this, "Toasting on main thread.", Toast.LENGTH_SHORT).show(); 
      } 
     }; 

     // Post the job to the handler instance which is tied to the main thread 
     // so that the job will be executed on the main/UI thread. 
     mHandler.post(uithreadStatements); 
    } 
} 
0

당신은 항상 onHandleIntent의 의도를 방송하고 BroadcastReceiver에서받을 수 있습니다. OnReceiveBroadcastReceiver에서 주 스레드에서 호출됩니다.