Android IntentService 상세 설명

오리지널 글, 전재 출처 주의:http://blog.csdn.net/ruils/article/details/17251935
IntentService 는 매우 재 미 있 는 유형 으로 명령 설계 모델 로 볼 수 있다.
안 드 로 이 드 핸들 러, 루 퍼 모델 에 익숙 하 다 면 인 텐 트 서 비 스 는 잘 이해 할 수 있 을 것 이다.
IntentService 는 Service 에서 계승 합 니 다. 보 낸 요청 을 메시지 대기 열 에 두 고 대기 열 순서에 따라 HandlerThread 에서 하나씩 처리 하고 처리 가 끝나 면 자신 을 중지 합 니 다.
IntentService 의 용법 은 간단 합 니 다. 하위 클래스 를 계속 쓰 고 onHandle Intent 방법 을 다시 쓰 고 죽 어 가 는 start 라 는 서 비 스 를 쓰 면 됩 니 다.
다음 단계 분석:
1. IntentService 가 시 작 될 때 HandlerThread 를 만 들 고 시작 한 다음 이 HandlerThread 의 looper 로 ServiceHandler 를 만 듭 니 다. onCreate 는 IntentService 의 수명 주기 에 한 번 만 호출 됩 니 다.
@Override
    public void onCreate() {
        // TODO: It would be nice to have an option to hold a partial wakelock
        // during processing, and to have a static startService(Context, Intent)
        // method that would launch the service & hand off a wakelock.

        super.onCreate();
        HandlerThread thread = new HandlerThread("IntentService[" + mName + "]");
        thread.start();

        mServiceLooper = thread.getLooper();
        mServiceHandler = new ServiceHandler(mServiceLooper);
    }

2. 새로운 명령 이 오 면 이 Intent 를 메시지 줄 에 놓 습 니 다.onStartCommand 는 IntentService 수명 주기 에서 한 번 또는 여러 번 호출 됩 니 다.
 @Override
    public int onStartCommand(Intent intent, int flags, int startId) {
        onStart(intent, startId);
        return mRedelivery ? START_REDELIVER_INTENT : START_NOT_STICKY;
    }
  @Override
    public void onStart(Intent intent, int startId) {
        Message msg = mServiceHandler.obtainMessage();
        msg.arg1 = startId;
        msg.obj = intent;
        mServiceHandler.sendMessage(msg);
    }

3. 보 내 온 모든 요청 을 여기에 보 내 처리 합 니 다. 어떻게 처리 하 는 지 에 대해 서 는 onHandle Intent 라 는 허 법 을 스스로 다시 써 야 합 니 다.처리 가 끝 난 후에 stopSelf (msg. arg 1) 라 는 방법 을 호출 합 니 다. 여기 서 주의해 야 할 것 은 하나의 Intent 를 처리 할 때마다 한 번 씩 멈 추 지만 IntentService 가 반드시 멈 추 는 것 은 아 닙 니 다. 이 stop 방법 은 매개 변 수 를 가지 고 있 기 때문에 메시지 대기 열 에 처리 할 Intent 가 없어 야 IntentService 가 진정 으로 멈 출 수 있 습 니 다.
    private final class ServiceHandler extends Handler {
        public ServiceHandler(Looper looper) {
            super(looper);
        }

        @Override
        public void handleMessage(Message msg) {
            onHandleIntent((Intent)msg.obj);
            stopSelf(msg.arg1);
        }
    }
 protected abstract void onHandleIntent(Intent intent);

4. 끝 날 때 메시지 순환 을 종료 합 니 다.
 @Override
    public void onDestroy() {
        mServiceLooper.quit();
    }

마지막 으로 IntentService 는 Redelivery 모드 가 있 습 니 다. 기본적으로 닫 혀 있 습 니 다. Redelivery 모드 를 열 면 마지막 으로 보 낸 Intent 명령 이 완전히 실 행 될 수 있 습 니 다. IntentService 가 끊 겨 도 다시 실행 할 수 있 습 니 다.
    public void setIntentRedelivery(boolean enabled) {
        mRedelivery = enabled;
    
    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {
        onStart(intent, startId);
        return mRedelivery ? START_REDELIVER_INTENT : START_NOT_STICKY;
    }

좋은 웹페이지 즐겨찾기