세이박스

php를 이용한 gcm 푸시 예제

모바일앱개발

- php 를 사용한 gcm 푸시예제입니다.

- 안드로이드 폰에 RegistrationId 를 mysql 서버에 저장하고 서버에서 gcm 메시지를 전송하는 예제입니다.


1. mysql에 gcm_table 이라는 테이블을 만들고 reg_id,phone_num 칼럼을 만들어 줍니다(phone_num 은 폰번호인데..폰번호를 함부로 수집하면 안되겠죠^^;, 쓸데없는 칼럼이지만 그냥 만들어봤습니다;) -> 이건 생략하겠습니다


2. 앱 시작 시 RegistrationId를 만들고 php를 이용해 서버에 인서트 해줍니다.

---------------------------------------------------------------------------------------------------------

앱시작시 RegistrationId 등록 클래스 : MainActivity .java


public class MainActivity extends Activity {

AsyncTask<?, ?, ?> regIDInsertTask;

TextViewmessage;

ProgressDialog loagindDialog;

String regId ;

String myResult ;

@Override

public void onCreate(Bundle savedInstanceState){

super.onCreate(savedInstanceState);

setContentView(R.layout.activity_main);


message=(TextView)findViewById(R.id.re_message);

if(GCMIntentService.re_message!=null){

message.setText(GCMIntentService.re_message);

}else{

registerGcm();

}

}

public void registerGcm() {

GCMRegistrar.checkDevice(this);

GCMRegistrar.checkManifest(this);


regId = GCMRegistrar.getRegistrationId(this);


if (regId.equals("")) {

GCMRegistrar.register(this, "프로젝트ID");

} else {

Log.e("reg_id", regId);

}

sendAPIkey();

}

private void sendAPIkey() {

String myNum="폰번호에요";

regIDInsertTask = new regIDInsertTask().execute(regId, myNum);

}


private class regIDInsertTask extends AsyncTask<String, Void, Void> {

@Override

protected void onPreExecute() {

super.onPreExecute();

loagindDialog = ProgressDialog.show(MainActivity.this, "키 등록 중입니다..",

"Please wait..", true, false);

}


@Override

protected Void doInBackground(String... params) {

HttpPostData(params[0] , params[1]);

return null;

}

protected void onPostExecute(Void result) {

loagindDialog.dismiss();

}

}


public void HttpPostData(String reg_id , String pnum) {

try {

URL url = new URL("http://서버URL/gcm_reg_insert.php"); // URL 설정

HttpURLConnection http = (HttpURLConnection) url.openConnection(); // 접속

//--------------------------

// 전송 모드 설정 - 기본적인 설정이다

//--------------------------

http.setDefaultUseCaches(false);

http.setDoInput(true);

http.setDoOutput(true);

http.setRequestMethod("POST");


http.setRequestProperty("content-type", "application/x-www-form-urlencoded");

StringBuffer buffer = new StringBuffer();

buffer.append("reg_id").append("=").append(reg_id).append("&"); // php 변수에 값 대입

buffer.append("pnum").append("=").append(pnum);

OutputStreamWriter outStream = new OutputStreamWriter(http.getOutputStream(), "EUC-KR");

PrintWriter writer = new PrintWriter(outStream);

writer.write(buffer.toString());

writer.flush();

InputStreamReader tmp = new InputStreamReader(http.getInputStream(), "EUC-KR");

BufferedReader reader = new BufferedReader(tmp);

StringBuilder builder = new StringBuilder();

String str;

while ((str = reader.readLine()) != null) {

builder.append(str + "\n");

}

myResult = builder.toString();

} catch (MalformedURLException e) {

//

} catch (IOException e) {

//

} // try

} // HttpPostData


}


---------------------------------------------------------------------------------------------------------

activity_main.xml


<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"

xmlns:tools="http://schemas.android.com/tools"

android:layout_width="match_parent" android:orientation="vertical"

android:layout_height="match_parent" >

<Button android:id="@+id/btn1"

android:layout_width="200dip"

android:layout_height="50dip" android:text="받은메시지" />

<TextView

android:id="@+id/re_message"

android:layout_width="match_parent"

android:layout_height="50dip"

android:background="#ffffff"

/>

</LinearLayout>

---------------------------------------------------------------------------------------------------------

RegistrationId 인서트 해주는 php : gcm_reg_insert.php


<?php

$response = array();

if (isset($_POST['reg_id']) && isset($_POST['pnum']) ) {

$reg_id = $_POST['reg_id'];

$pnum = $_POST['pnum'];

echo $reg_id,$pnum;

$connect = mysql_connect("서버URL","아이디","비밀번호") or die("SQL server에 연결할 수 없습니다.");

mysql_select_db("DB명",$connect);


$result = mysql_query("INSERT INTO gcm_table(reg_id, phone_num) VALUES('$reg_id', '$pnum')");


if ($result) {

// successfully inserted into database

$response["success"] = 1;

$response["message"] = "Product successfully created.";

echo json_encode($response);

} else {

// failed to insert row

$response["success"] = 0;

$response["message"] = "Oops! An error occurred.";

echo json_encode($response);

}

} else {

// required field is missing

$response["success"] = 0;

$response["message"] = "Required field(s) is missing";

echo json_encode($response);

}

?>

----------------------------------------------------------------------------------------------

GCMRegistrar.register(this, "프로젝트ID");

-> https://code.google.com/apis/console/b/0/ 로 연결해서 구글 계정으로 로그인하면 project:숫자가 뜹니다

project 옆에 숫자가 프로젝트ID 입니다;


$connect = mysql_connect("서버URL","아이디","비밀번호") or die("SQL server에 연결할 수 없습니다."); mysql_select_db("DB명",$connect);

-> 자신의 서버 정보를 적어주세요...^^;

 

3. db에 저장된 RegistrationId값을 이용해 gcm 메시지를 전송해줍니다.(간단한 폼을 만들었고 내용입력 후 메시지보내기를 클릭하면 폰으로 푸시메시지가 전송됩니다.


---------------------------------------------------------------------------------------------------------

push전송하는 php : gcm_send_message.php



<HTML>

<HEAD>

<TITLE>GuestBook</TITLE>

<meta http-equiv="content-Type" content="text/html" charset="utf-8">

</HEAD>



<BODY BGCOLOR="#006699" LINK="#99CCFF" VLINK="#99CCCC" TEXT="#FFFFFF">

<center>

<br><p>


<?


$apiKey = "apikey";



$message = $_POST['message'];


echo("

<FORM name='form' method='post' action='$PHP_SELF'>

<TABLE border='0' cellspacing='1'>

<TR>

<TD width='109' bgcolor='#5485B6'><P align='center'><FONT face='굴림' size='2' color='#CDDAE4'>

message</FONT></TD>

<TD width='541'><P>&nbsp;<INPUT type='text' name='message' SIZE=25 MAXLENGTHTH='20'></TD>

</TR>

<TR>

<TD><P>&nbsp;</TD>

<TD><P>&nbsp;<INPUT type='submit' name='submit' value='sendMessage'></TD>

</TR>

</TABLE>

<input type=hidden name=mode value='up'>

</FORM>");


if ($mode == 'up') {

$messageData = addslashes($message);

sendNotification($apiKey,$messageData);

}


function sendNotification( $apiKey, $messageData )

{


$headers = array('Content-Type:application/json ; charset=UTF-8', 'Authorization:key=apikey');


$connect = mysql_connect("서버URL","아이디","비밀번호") or die("SQL server에 연결할 수 없습니다.");

mysql_select_db("DB명",$connect);


$result = mysql_query("SELECT reg_id FROM gcm_table");

$conidx=0;



$arr = array();

$arr['data'] = array();

$arr['data']['msg'] = $messageData;

$arr['registration_ids'] = array();




while($row = mysql_fetch_array($result))

{

$arr['registration_ids'][$conidx] = $row['reg_id'] ;

$conidx++;

}

mysql_close($connect);


$ch = curl_init();


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

curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);

curl_setopt($ch, CURLOPT_POST, true);

curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);

curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);

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



$response = curl_exec($ch);


echo $response;

curl_close($ch);


//return $response;

}


echo("

<p>

</BODY>

</HTML>");

?>

--------------------------------------------------------------------------------------------------------

$headers = array('Content-Type:application/json ; charset=UTF-8', 'Authorization:key=apikey');

->apikey를 정확하게 입력해 주셔야합니다.

https://code.google.com/apis/console/b/0/ 로 가시면 apikey를 얻을 수 있습니다.


$ch = curl_init();

-> curl을 이용해서 구글 서버에 gcm을 요청하고 있습니다.




--------------------------------------------------------------------------------------------------------

안드로이드 매니페스트 파일 : AndroidManifest.xml


<manifest xmlns:android="http://schemas.android.com/apk/res/android"

package="com.appmaker.gcmtest"

android:versionCode="1"

android:versionName="1.0" >


<uses-sdk

android:minSdkVersion="8"

android:targetSdkVersion="15" />


<permission android:name="com.appmaker.gcmtest.permission.C2D_MESSAGE" android:protectionLevel="signature" />

<uses-permission android:name="android.permission.READ_PHONE_STATE" />

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


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

<uses-permission android:name="android.permission.INTERNET" />

<uses-permission android:name="android.permission.GET_ACCOUNTS" />

<uses-permission android:name="android.permission.WAKE_LOCK" />


<application

android:icon="@drawable/ic_launcher"

android:label="@string/app_name"

>

<receiver

android:name="com.google.android.gcm.GCMBroadcastReceiver"

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

<intent-filter>

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

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

<category android:name="com.appmaker.gcmtest" />

</intent-filter>

</receiver>

<activity android:name=".MainActivity" android:screenOrientation="portrait">

<intent-filter>

<action android:name="android.intent.action.MAIN" />

<category android:name="android.intent.category.LAUNCHER" />

</intent-filter>

</activity>

<service android:name=".GCMIntentService" />

</application>


</manifest>


---------------------------------------------------------------------------------------------------------

푸시 받았을때 노티피케이션 해주는 서비스: GCMIntentService .java


public class GCMIntentService extends GCMBaseIntentService {

static String re_message=null;


private static void generateNotification(Context context, String message) {

int icon = R.drawable.ic_action_search;

long when = System.currentTimeMillis();


NotificationManager notificationManager = (NotificationManager) context

.getSystemService(Context.NOTIFICATION_SERVICE);

Notification notification = new Notification(icon, message, when);


String title = context.getString(R.string.app_name);

Intent notificationIntent = new Intent(context, MainActivity.class);

re_message=message;


notificationIntent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP | Intent.FLAG_ACTIVITY_SINGLE_TOP);

PendingIntent intent = PendingIntent.getActivity(context, 0,notificationIntent, 0);


notification.setLatestEventInfo(context, title, message, intent);

notification.flags |= Notification.FLAG_AUTO_CANCEL;

notificationManager.notify(0, notification);

}


@Override

protected void onError(Context arg0, String arg1) {


}


@Override

protected void onMessage(Context context, Intent intent) {

String msg = intent.getStringExtra("msg");

Log.e("getmessage", "getmessage:" + msg);


generateNotification(context, msg);

}


@Override

protected void onRegistered(Context context, String reg_id) {

Log.e("키를 등록합니다.(GCM INTENTSERVICE)", reg_id);

}


@Override

protected void onUnregistered(Context arg0, String arg1) {

Log.e("키를 제거합니다.(GCM INTENTSERVICE)", "제거되었습니다.");

}

}

 

 

출처 :

http://ondestroy.tistory.com/entry/php를-이용한-gcm-푸시-예제1

http://ondestroy.tistory.com/entry/php를-이용한-gcm-푸시-예제2