Where The Streets Have No Name

android c2dm 예제 본문

Developement/Mobile

android c2dm 예제

highheat 2011. 12. 30. 14:33
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="net.neocorea.moim"
    android:versionCode="1"
    android:versionName="1.0" >

    <uses-sdk android:minSdkVersion="8" />

    <application
        android:icon="@drawable/ic_launcher"
        android:label="@string/app_name" >
        <activity
            android:name=".C2DMreceiverActivity"
            android:label="@string/app_name" >
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />

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

        <receiver
            android:name=".C2dmReceiver"
            android:permission="com.google.android.c2dm.permission.SEND" >

            <!-- Receive the actual message -->
            <intent-filter>
                <action android:name="com.google.android.c2dm.intent.RECEIVE" />

                <category android:name="앱페키지명" />
            </intent-filter>
            <!-- Receive the registration id -->
            <intent-filter>
                <action android:name="com.google.android.c2dm.intent.REGISTRATION" />

                <category android:name="앱페키지명" />
            </intent-filter>
        </receiver>
    </application>

    <permission
        android:name="앱페키지명.permission.C2D_MESSAGE"
        android:protectionLevel="signature" />

    <uses-permission android:name="앱페키지명.permission.C2D_MESSAGE" />

    <!-- This app has permission to register and receive message -->
    <uses-permission android:name="com.google.android.c2dm.permission.RECEIVE" />

    <!-- Send the registration id to the server -->
    <uses-permission android:name="android.permission.INTERNET" />
    <uses-permission android:name="android.permission.GET_ACCOUNTS" />
    <uses-permission android:name="android.permission.USE_CREDENTIALS" />

</manifest>
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.preference.PreferenceManager;
import android.util.Log;
import android.view.Gravity;
import android.widget.Toast;

public class C2dmReceiver extends BroadcastReceiver {

	static String registration_id = null;
	static String c2dm_msg = "";

	@Override
	public void onReceive(Context context, Intent intent) {
		// 리시버로 받은 데이터가 Registration ID이면
		if (intent.getAction().equals("com.google.android.c2dm.intent.REGISTRATION")) {

			handleRegistration(context, intent);
		}
		// 리시버가 받은 데이터가 메세지이면
		else if (intent.getAction().equals("com.google.android.c2dm.intent.RECEIVE")) {

			// 추출
			c2dm_msg = intent.getStringExtra("msg");

			// 출력
			Log.v("C2DM", "C2DM Message : " + c2dm_msg);
			Toast toast = Toast.makeText(context, c2dm_msg, Toast.LENGTH_SHORT);
			toast.setGravity(Gravity.TOP | Gravity.CENTER, 0, 150);
			toast.show();
		}
	}

	public void handleRegistration(Context context, Intent intent) {

		registration_id = intent.getStringExtra("registration_id");

		Log.v("C2DM", "Get the Registration ID From C2DM");
		Log.v("C2DM", "Registration ID : " + registration_id);

		// 받은 메세지가 error일 경우
		if (intent.getStringExtra("error") != null) {
			Log.v("C2DM", "C2DM REGISTRATION : Registration failed," + "should try again later");
		}
		// 받은 메세지가 unregistered일 경우
		else if (intent.getStringExtra("unregistered") != null) {
			Log.v("C2DM", "C2DM REGISTRATION : unregistration done, " + "new messages from the authorized "
					+ "sender will be rejected");
		}
		// 받은 메세지가 Registration ID일 경우
		else if (registration_id != null) {
			Log.v("C2DM", "Registration ID complete!");

			// Registration ID 저장
			SharedPreferences shrdPref = PreferenceManager.getDefaultSharedPreferences(context);

			SharedPreferences.Editor editor = shrdPref.edit();
			editor.putString("registration_id", registration_id);
			editor.commit();
		}
	}

}

 

import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.URL;

import android.app.Activity;
import android.app.PendingIntent;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.preference.PreferenceManager;
import android.util.Log;

public class C2DMreceiverActivity extends Activity {

	private static String authToken = null;

	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.main);

		// C2DM 으로부터 Registration ID와 AuthToken을 발급 받는다.
		try {
			requestRegistrationId();
			authToken = getAuthToken();
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	/**
	 * Request for RegistrationID to C2DM Activity 시작시 구글 C2DM으로 Registration ID
	 * 발급을 요청한다. Registration ID를 발급받기 위해서는 Application ID, Sender ID가 필요.
	 * Registration ID는 Device를 대표하는 ID로써 한번만 받아서 저장하면 되기 때문에 매번 실행시 체크.
	 */
	public void requestRegistrationId() throws Exception {

		SharedPreferences shrdPref = PreferenceManager.getDefaultSharedPreferences(this);
		String registration_id = shrdPref.getString("registration_id", null);
		shrdPref = null;

		if (registration_id == null) {
			Intent registrationIntent = new Intent("com.google.android.c2dm.intent.REGISTER");

			// Application ID(Package Name)
			registrationIntent.putExtra("app", PendingIntent.getBroadcast(this, 0, new Intent(), 0));

			// Developer ID
			registrationIntent.putExtra("sender", "개발자구글계정");

			// Start request.
			startService(registrationIntent);
		} else {
			C2dmReceiver.registration_id = registration_id;
			Log.v("C2DM", "Registration ID is Exist!");
			Log.v("C2DM", "Registration ID : " + C2dmReceiver.registration_id);
		}
	}

	/**
	 * C2DM을 이용하기 위해서는 보안상 authToken(인증키)이 필요하다. authToken도 역시 한 번만 받아놓고 저장한다음
	 * 쓰면 된다.
	 */
	public String getAuthToken() throws Exception {

		SharedPreferences shrdPref = PreferenceManager.getDefaultSharedPreferences(this);
		String authToken = shrdPref.getString("authToken", null);

		Log.v("C2DM", "AuthToken : " + authToken);

		if (authToken == null) {
			StringBuffer postDataBuilder = new StringBuffer();

			postDataBuilder.append("accountType=HOSTED_OR_GOOGLE");
			postDataBuilder.append("&Email=개발자구글계정");
			postDataBuilder.append("&Passwd=비밀번호");
			postDataBuilder.append("&service=ac2dm");
			postDataBuilder.append("&source=테스트");

			byte[] postData = postDataBuilder.toString().getBytes("UTF-8");

			URL url = new URL("https://www.google.com/accounts/ClientLogin");
			HttpURLConnection conn = (HttpURLConnection) url.openConnection();

			conn.setDoOutput(true);
			conn.setUseCaches(false);
			conn.setRequestMethod("POST");
			conn.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
			conn.setRequestProperty("Content-Length", Integer.toString(postData.length));

			// 출력스트림을 생성하여 서버로 송신
			OutputStream out = conn.getOutputStream();
			out.write(postData);
			out.close();

			// 서버로부터 수신받은 스트림 객체를 버퍼에 넣어 읽는다.
			BufferedReader br = new BufferedReader(new InputStreamReader(conn.getInputStream()));

			String sIdLine = br.readLine();
			String lsIdLine = br.readLine();
			String authLine = br.readLine();

			Log.v("C2DM", sIdLine);
			Log.v("C2DM", lsIdLine);
			Log.v("C2DM", authLine);

			authToken = authLine.substring(5, authLine.length());

			SharedPreferences.Editor editor = shrdPref.edit();
			editor.putString("authToken", authToken);
			editor.commit();
		}

		shrdPref = null;
		return authToken;
	}
}
<?php
$accountType = 'HOSTED_OR_GOOGLE';
$Email = '개발자구글계정';
$Passwd = '비밀번호';
$source = 'Test';
$service = 'ac2dm';

$ch = curl_init();   

curl_setopt($ch, CURLOPT_URL, "https://www.google.com/accounts/ClientLogin");
curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, 0);
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);

$account_info = array('accountType' => $accountType, 'Email' => $Email, 'Passwd' => $Passwd, 'source' => $source, 'service' => $service);

curl_setopt($ch, CURLOPT_POSTFIELDS, $account_info);

$response = curl_exec($ch);
$auth_tmp = substr(strstr($response, "Auth="), 5);
$auth = substr($auth_tmp, 0, strlen($auth_tmp)-1);

curl_setopt($ch, CURLOPT_URL, "https://android.apis.google.com/c2dm/send");

$registration_id = '디바이스별로 발급되는 아이디';
$collapse_key = 1;
$msg = '안녕하세요 C2DM 테스트 입니다';

$data = 'registration_id='.$registration_id.'&collapse_key='.$collapse_key.'&data.msg='.urlencode($msg);
curl_setopt($ch, CURLOPT_POSTFIELDS, $data);

$headers = array(
    "Content-Type: application/x-www-form-urlencoded", 
    "Content-Length: ".strlen($data), 
    "Authorization: GoogleLogin auth=$auth" 
);

curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
$result = curl_exec($ch);
curl_close($ch);

echo $result;
?>

 

참고 : http://sellogger.com/go/206109   
         http://warmz.tistory.com/570