2016년 4월 10일 일요일

GCM 4. GcmRegistrationIntentService.java, GcmInstanceIDListenerService.java

1. GcmRegistrationIntentService.java

Instance ID를 가지고 토큰을 가져오는 작업을 수행.

토큰을 가져오는 과정에 ProgressBar를 동작시키고,
토큰이 획득되면 TextView에 토큰 정보를 업데이트하기 위한
LocalBoardcast 액션을 추가함

package com.example.rock.opregcheck;

import android.annotation.SuppressLint;
import android.app.IntentService;
import android.content.Intent;
import android.support.v4.content.LocalBroadcastManager;
import android.util.Log;

import com.google.android.gms.gcm.GoogleCloudMessaging;
import com.google.android.gms.iid.InstanceID;

import java.io.IOException;

/**
 * Created by rock on 2016-04-05.
 */
public class GcmRegistrationIntentService extends IntentService {

    private static final String TAG = "GcmRegistrationIntentService";

    public GcmRegistrationIntentService() {
        super(TAG);
    }

    @SuppressLint("LongLogTag")
    @Override
    protected void onHandleIntent(Intent intent) {

        // GCM Instance ID의 토큰을 가져오는 작업이 시작되면
        // LocalBoardcast로 GENERATING 액션을 알려 ProgressBar가 동작

        LocalBroadcastManager.getInstance(this)
                .sendBroadcast(new Intent(QuickstartPreferences.REGISTRATION_GENERATING));

        // GCM을 위한 Instance ID를 가져온다.
        InstanceID instanceID = InstanceID.getInstance(this);
        String token = null;

        try {
            synchronized (TAG) {
                // GCM 앱을 등록하고 획득한 설정파일인 google-services.json을 기반으로 SenderID를 자동으로 가져온다.
                String default_senderId = getString(R.string.gcm_defaultSenderId);

                // GCM 기본 scope는 "GCM"이다.
                String scope = GoogleCloudMessaging.INSTANCE_ID_SCOPE;

                // Instance ID에 해당하는 토큰을 생성하여 가져온다.
                token = instanceID.getToken(default_senderId, scope, null);

                Log.d(TAG, "GCM Registration Token: " + token);
            }
        } catch (IOException e) {
            e.printStackTrace();
        }

        // GCM Instance ID에 해당하는 토큰을 획득하면 LocalBoardcast에 COMPLETE 액션을 알린다.
        // 이때 토큰을 함께 넘겨주어서 UI에 토큰 정보를 활용할 수 있도록 했다.

        Intent registrationComplete = new Intent(QuickstartPreferences.REGISTRATION_COMPLETE);
        registrationComplete.putExtra(QuickstartPreferences.INSTANCE_ID_TOKEN, token);
        LocalBroadcastManager.getInstance(this).sendBroadcast(registrationComplete);
    }
}



2. GcmInstanceIDListenerService.java

Instance ID를 획득하기 위한 리스너를 상속받아서 토큰을 갱신하는 코드를 추가한다.

package com.example.rock.opregcheck;

import android.content.Intent;

import com.google.android.gms.iid.InstanceIDListenerService;

/**
 * Created by rock on 2016-04-05.
 */
public class GcmInstanceIDListenerService extends InstanceIDListenerService {
    @Override
    public void onTokenRefresh() {
        // super.onTokenRefresh();
        Intent intent = new Intent(this, GcmRegistrationIntentService.class);
        startService(intent);
    }
}



댓글 없음 :

댓글 쓰기