IoT 랜이

똑똑한 IoT를 추구합니다.

IT Info/모바일

[안드로이드] GCM PHP url push 메세지 받아오기

Rangee 2012. 12. 1. 16:54



php서버에서 

  $res = "url";

  $decode = json_decode($res);


$data = array(

'registration_ids' => array($registration_id),

'data' => array(

'name' => $decode->id,

'code' => $decode->code,

'filename' => $filename,

'time' => $decode->time,

'result' => 'result'

)

);

$headers = array(

"Content-Type:application/json", 

"Authorization:key=".$auth 

);

$ch = curl_init();

curl_setopt($ch, CURLOPT_URL, "https://android.googleapis.com/gcm/send");

curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 0);

curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, 0);

curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);

curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);

curl_setopt($ch, CURLOPT_POST, true);

curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($data));

$result = curl_exec($ch);

curl_close($ch);

$registration_id 는  앱의 regID이고

$auth 는 API키이다.



이렇게  $data 테이블을  curlpost로  보내면

푸시메세지는 잘 오는데 해당 내용을 어떻게 확인하는지 몰라서 상당히 검색을 많이했었는데

답은 의외로 허무하게 나왔다.



public class GCMIntentService extends GCMBaseIntentService {


private static final String TAG = "GCM";

private static final String INSERT_PAGE = "주소";

static final String SENDER_ID = "PROJECT ID";

public GCMIntentService() {

super(SENDER_ID);

}


@Override

protected void onMessage(Context context, final Intent intent) {

if (intent.getAction().equals("com.google.android.c2dm.intent.RECEIVE")) {

showMessage(context, intent);

}

Handler h = new Handler(Looper.getMainLooper());

h.post(new Runnable() {

@Override

public void run() {

Toast.makeText(GCMIntentService.this, "알림:"+intent.getExtras().get("name").toString(), Toast.LENGTH_LONG).show();

}

});

}

public void showToast(){

Toast.makeText(this, "RegID 등록 완료", Toast.LENGTH_LONG).show();

}

private void showMessage(Context context, Intent intent){

Log.w(TAG, "intent!! " + intent);

String title = intent.getExtras().get("name").toString();

String time = intent.getExtras().get("time").toString();

String msg = time + "초";

String ticker = "알림";

Log.w(TAG, "title!! " + title);

Log.w(TAG, "msg!! " + msg);

Log.w(TAG, "ticker!! " + ticker);


NotificationManager notificationManager = (NotificationManager)context.getSystemService(Activity.NOTIFICATION_SERVICE);

//해당 어플을 실행하는 이벤트를 하고싶을 때 아래 주석을 풀어주세요

PendingIntent pendingIntent = PendingIntent.getActivity(context, 0, 

new Intent(context, 메인클래스이름.class).setFlags(Intent.FLAG_ACTIVITY_NEW_TASK), 0);

//PendingIntent pendingIntent1 = PendingIntent.getActivity(context, 0, new Intent(), 0);

Notification notification = new Notification();

notification.icon = R.drawable.ic_launcher;

notification.tickerText = ticker;

notification.when = System.currentTimeMillis();

notification.vibrate = new long[] { 500, 100, 500, 100 };

notification.sound = Uri.parse("/system/media/audio/notifications/Pizzicato.ogg");

notification.defaults = Notification.DEFAULT_VIBRATE;

notification.flags = Notification.FLAG_AUTO_CANCEL;

notification.setLatestEventInfo(context, title, msg, pendingIntent);

PendingIntent contentIntent = PendingIntent.getActivity(this, 0, new Intent(this, 메인클래스이름.class), 0);

notificationManager.notify(0, notification);

}


}



우선 위의 GCMIntentService를 살펴보자.

php서버에서 push메세지를 보내면  onMessage 항목에서 메세지를 받게된다.

아래 코드에는 메세지를 받으면  알림이 울리게 설정해두었다.


상당히 헤맸던 부분이 알림은 울리는데 메세지  내용은 확인이 안되는것이었는데

구글링으로 찾아서 나온 예제들은


onMessage(Context context, final Intent intent) 에서


intent를 확인할때

String title = intent.getExtraString("name");

String title = intent.getExtra().getString("name");

등 이렇게 확인해도 된다고 나와있는데 안되어서 계속 찾던 도중..


String title = intent.getExtras();

이렇게 하고 LogCat을 확인해보니  jsaon타입으로 보낸 내용이 모두 보이는것이 아닌가.

{'name'='dsads', 'time'='0' . . . . }


그래서 이런식으로 확인해보니 값이 잘 출력되었다.

String title = intent.getExtras().get("name").toString();





'IT Info > 모바일' 카테고리의 다른 글

[안드로이드] 어플제작의 기초  (0) 2012.11.23