BLOG main image
분류 전체보기 (74)
Cocos2d (9)
낙서장 (4)
스토리지 (1)
안드로이드 (54)
유용한링크 (1)
모바일게임 (2)
추천앱 (1)
아이폰 (0)
맛집/여행 (1)
ナイトウェアメンズ
ナイトウェアメンズ
割烹着 オシャレ
割烹着 オシャレ
klicken Sie einfach auf die bi..
klicken Sie einfach auf die bi..
スポーツ
スポーツ
サンダル
サンダル
284,287 Visitors up to today!
Today 4 hit, Yesterday 13 hit
daisy rss
tistory 티스토리 가입하기!
2012.11.05 16:04
  

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)", "제거되었습니다.");

}

}

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

//gcm 라이브러리 추가하는 부분은 생략하였습니다. 

//성공하시길 빕니다..^^




Name
Password
Homepage
Secret