Androiddd

Android GCM 사용하기 (Push Message)

Prod. No. 7 2016. 9. 6. 12:25

Android 에서 Google Cloud Message (GCM) 를 이용하여 Push 를 보내는 예제

google developer site 에서 app 등록 하고 api_key 먼저 받아놓으시고!!

오타가 있을지도;;; 쿨럭; -_-;


# Activity 단에서 처리하는 코드


// define

private GoogleCloudMessaging gcm;

private String regId;

private final static int PLAY_SERVICES_RESOLUTION_REQUEST = 9000;

public static final String EXTRA_MESSAGE = "message";

public static final String PROPERTY_REG_ID = "registration_id";


//onCreate

if (checkPlayServices()) {

gcm = GoogleCloudMessaging.getInstance(this);

regId = getRegistrationId(context);

if (regId.isEmpty()){

registerInBackground();

}

} else {

Log.d(TAG, "No valid Google Play Services APK found.");

}


private boolean checkPlayServices() {

int resultCode = GooglePlayServiceUtil.isGooglePlayServiceAvailable(this);

if (resultcode != ConnectionResult.SUCCESS) {

if (GooglePlayServicesUtil.isUserRecoverableError(resultCode)) {

GooglePlayServicesUtil.getErrorDialog(resultCode, this, PLAY_SERVICES_RESOLUTION_REQUEST).show();

} else {

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

finish();

}

return false;

}

return true;

}


private String getRegistrationId(Context context) {

final SharedPreferences prefs = getGCMPreferences(context);

String registrationId = prefs.getString(PROPERTY_REG_ID, "");

if (registrationId.isEmpty()) {

Log.d(TAG, "Registration not found.");

return "";

}

return registrationId;

}


private SharedPreferences getGCMPreferences(Context context) {

// Activity Name

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

}


private void registerInBackground() {

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

@Override

protected String doInBackground(Void... params) {

String msg = "";

try {

if (gcm == null) {

gcm = GoogleCloudMessaging.getInstance(context);

}

regId = gcm.register(GCM_SERVER_ID); // ServerId

msg = "Device registered, registration Id = " + regId;

sendRegistrationIdToServer();

// TODO setDevicePreferences(regId);

} catch (IOException e) {

msg = e.getMessage();

}

return msg;

}


@Override

protected void onPostExecute(String msg) {

Log.d(TAG, msg);

}

}.execute(null, null, null);

}


private void sendRegistrationIdToServer() {

// TODO register to server

}


# GCM BroadcastReceiver


public class GcmBroadcastReceiver extends WakefulBroadcastReceiver {

@Override

public void onReceive(Context context, Intent intent) {

// Explicitly specify that GcmIntentService will handle the intent.

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

// Start the service, keeping the device awake while it is launching.

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

setResultCode(Activity.RESULT_OK);

}

}


# GCM Intent Service


public class GcmIntentService extends IntentService {

private NotificationManager mNotificationManager;


public GcmIntentService() {

super("GcmIntentService");

}

@Override

protected void onHandleIntent(Intent intent) {

Bundle extras = intent.getExtras();

GoogleCloudMessaging gcm = GoogleCloudMessaging.getInstance(this);

String messageType = gcm.getMessageType(intent);

if (!extras.isEmpty()) {

if (GoogleCloudMessaging.MESSAGE_TYPE_SEND_ERROR.equals(messageType)) {

setNotification("SEND_ERROR : " + extras.toString());

} else if (GoogleCloudMessaging.MESSAGE_TYPE_DELETED.equals(messageType)) {

setNotification("DELETED_MESSAGE : " + extras.toString());

} else if (GoogleCloudMessaging.MESSAGE_TYPE_MESSAGE.equals(messageType)) {

for (int i = 0; i < 5; i++) {

Log.d(TAG, "... " + (i+1) + "/5 @" + SystemClock.elapsedRealtime());

try{

Thread.sleep(500);

} catch (InterruptedException e) {

e.printStackTrace();

}

}

setNotification("Message Received : " + extras.toString());

}

}


GcmBroadcaseReceiver.completeWakefulIntent(intent);

}

}


private void setNotification(String msg) {

mNotificationManager = (NotificationManager) context.getSystemService(Context.NOTIFICATON_SERVICE);

PendingIntent pendingIntent = PendingIntent.getActivity(context, 0, new Intent(context, Activity.class), 0); // Activity name

Uri notiSound = RingtoneManager.getActualDefaultRingtoneUri(getApplicationContext(), RingtongManager.TYPE_NOTIFICATION);

NotificationCompat.Builder mBuilder = new NotificationCompat.Builder(context)

.setSmallIcon(R.drawable.app_icon).setTicker("title").setWhen(System.currentTimeMillis())

.setAutoCancel(true).setContentTitle("title").setContentText("content")

.setLights(Color.RED, 500, 5000);


// Bigger Style (if big)

NotificationCompat.BigPictureStyle style = new NotificationCompat.BigPictureStyle();

style.setBigContentTitle("title");

style.setSummaryText("content");

style.bigPicture(bitmap)); // using bitmap

mBuilder.setStyle(style);


mBuilder.setContentIntent(pendingIntent);

mBuilder.setSound(pushSound);

mNotificationManager.notify(NOTIFICATION_ID, mBuilder.build());

}


# AndroidManifest.xml


<uses-permission android:name="com.google.android.c2dm.permission.RECEIVE" />

<permission

    android:name="com.package.name.permission.C2D_MESSAGE"

    android:protectionLevel="signature" />

<uses-permission android:name="com.package.name.permission.C2D_MESSAGE" />


<application>

        <receiver

            android:name="com.dlto.topping.GcmBroadcastReceiver"

            android:permission="com.google.android.c2dm.permission.SEND" >

            <intent-filter>

                <action android:name="com.google.android.c2dm.intent.RECEIVE" />


                <category android:name="com.dlto.topping" />

            </intent-filter>

        </receiver>

        <service android:name="com.dlto.topping.GcmIntentService" />

        <meta-data

            android:name="com.google.android.gms.version"

            android:value="@integer/google_play_services_version" />

</application>