본문 바로가기

Development/Android

[Android] GCM구현하기~!

우선은 Google Service Library가 필요하다 설치방법은 여기에~!


1. 아래의 Permission을 하나씩 추가해주자~!


com.google.android.c2dm.permission.RECEIVE

android.permission.INTERNET

android.permission.GET_ACCOUNTS

android.permission.WAKE_LOCK

applicationPackage + ".permission.C2D_MESSAGE"

com.google.android.c2dm.intent.RECEIVE


4. service와 Broadcast도 등록~!



 <application ...>
       
<receiver
           
android:name=".GcmBroadcastReceiver"
           
android:permission="com.google.android.c2dm.permission.SEND" >
           
<intent-filter>
               
<action android:name="com.google.android.c2dm.intent.RECEIVE" />
               
<category android:name="com.example.gcm" />
           
</intent-filter>
       
</receiver>
       
<service android:name=".GcmIntentService" />
   
</application>


5. GCM id 받는 코드 작성~! 아래의 내용을 Activity에 넣는다. 결론을 말하자면 onCreate에서 this.mGcmRegId 값을 서버로 넘기 서버에서 알아서 푸쉬 메시지를 보내준다.


 private static final String SENDER_ID = "Project Number";

    private static final String PROPERTY_REG_ID = "regId";

    private static final int PLAY_SERVICES_RESOLUTION_REQUEST = 9000;

    

    private GoogleCloudMessaging mGcm;

    private String mGcmRegId;


     private boolean checkPlayServices() {

    

        final int resultCode = GooglePlayServicesUtil.isGooglePlayServicesAvailable(this);

        

        if (resultCode != ConnectionResult.SUCCESS) {

            if (GooglePlayServicesUtil.isUserRecoverableError(resultCode)) {

                GooglePlayServicesUtil.getErrorDialog(resultCode, this,

                        PLAY_SERVICES_RESOLUTION_REQUEST).show();

            } else {

                Log.i(TAG, "This device is not supported.");

                finish();

            }//end if

            

            return false;

        }//end if

        

        return true;

        

    }//end checkPlayServices Method


private SharedPreferences getGCMPreferences(Context context) {

        return getSharedPreferences(MainActivity.class.getSimpleName(), Context.MODE_PRIVATE);

    }

    

    private void registerInBackground() {

    

    final Context context = this.getApplicationContext();

    

        new AsyncTask<Void, Void, String>() {

            @Override

            protected String doInBackground(Void... params) {

                String msg = "";

                try {

                    if (mGcm == null) {

                    mGcm = GoogleCloudMessaging.getInstance(context);

                    }

                    mGcmRegId = mGcm.register(SENDER_ID);

                    msg = "Device registered, registration ID=" + mGcmRegId;

                    sendRegistrationIdToBackend();

                    storeRegistrationId(mGcmRegId);

                } catch (IOException ex) {

                    msg = "Error :" + ex.getMessage();

                }

                return msg;

            }


            @Override

            protected void onPostExecute(String msg) {

                showToast(msg);

            }

        }.execute(null, null, null);

        

    }//end registerInBackground Method



@Override

    protected void onCreate (final Bundle savedInstanceState) {

        super.onCreate(savedInstanceState);

        this.setContentView(R.layout.activity_main);

        

        this.mGcmRegId = getGCMPreferences(this).getString(PROPERTY_REG_ID, null);

        

        if (this.checkPlayServices() && this.mGcmRegId == null) {

        this.registerInBackground();

        }//end if

        

        Log.d(TAG, this.mGcmRegId);

        

    }//end onCreate Method



6.  기본 패키지에 GcmBroadcastReceiver 클래스를 만들어준다.

public class GcmBroadcastReceiver extends WakefulBroadcastReceiver {


@Override

public void onReceive (final Context context, final Intent intent) {

ComponentName comp = new ComponentName(context.getPackageName(), GcmIntentService.class.getName());

            startWakefulService(context, (intent.setComponent(comp)));

            setResultCode(Activity.RESULT_OK);

}//end onReceive Method


}//end GcmBroadcastReceiver Method




7.  GcmIntentService 서비스도 마찬가지로 기본 패키지에 생성~!


public class GcmIntentService extends IntentService {


    public GcmIntentService() {

        

    super("GcmIntentService");

        

    }//end Constructor


    @Override

    protected void onHandleIntent (Intent intent) {

    

        Bundle extras = intent.getExtras();

        GoogleCloudMessaging gcm = GoogleCloudMessaging.getInstance(this);

        String messageType = gcm.getMessageType(intent);


        //메시지를 처리한다.

        GcmBroadcastReceiver.completeWakefulIntent(intent);

        

    }//end onHandleIntent Method


    

}//end GcmIntentService Class