coolsharp의 놀이터

C2DM이란 안드로이드 2.2 프로요 버전 부터 푸시 서버를 제공해 주는 기능이다.

 

이하 소스는 http://www.androidside.com/bbs/board.php?bo_table=B46&wr_id=14705

 

에서 소스를 받아 수정 하였다.

 

푸시서버를 사용하기 위해서는 다음과 같은 절차가 필요하다.

 

  1. 구글에 해당 서버 사용 인증 요청
    http://code.google.com/intl/ko-KR/android/c2dm/signup.html에서 등록 요청
  2. 메일로 승인 확인
  3. 소스 코딩

 

C2dm_BroadcastReceiver.java

package com.coolsharp.push;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.util.Log;
import android.view.Gravity;
import android.widget.Toast;

public class C2dm_BroadcastReceiver extends BroadcastReceiver {

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

    /* 메시지 도착
     * (non-Javadoc)
     * @see android.content.BroadcastReceiver#onReceive(android.content.Context, android.content.Intent)
     */
    @Override
    public void onReceive(Context context, Intent intent) {
        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.getExtras().getString("msg");

            System.out.println("c2dm_msg======>" + c2dm_msg);
            Toast toast = Toast.makeText(context, "메시지 도착!\n" + c2dm_msg, Toast.LENGTH_SHORT);
            toast.setGravity(Gravity.TOP | Gravity.CENTER, 0, 150);
            toast.show();

        }
    }

    /**
     * @param context
     * @param intent
     */
    private void handleRegistration(Context context, Intent intent) {

        registration_id = intent.getStringExtra("registration_id");

        System.out.println("registration_id====>" + registration_id);

        if (intent.getStringExtra("error") != null) {

            Log.v("C2DM_REGISTRATION", ">>>>>" + "Registration failed, should try again later." + "<<<<<");

        } else if (intent.getStringExtra("unregistered") != null) {

            Log.v("C2DM_REGISTRATION", ">>>>>" + "unregistration done, new messages from the authorized sender will be rejected" + "<<<<<");

        } else if (registration_id != null) {

            System.out.println("registration_id complete!!");
        }
    }

}

 

Coolsharp_pushActivity.java

package com.coolsharp.push;

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

import android.app.Activity;
import android.app.PendingIntent;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;

public class Coolsharp_pushActivity extends Activity {

    // 아래 문자는 수정하면 안됨.
    // 구글에서 필요한 변수명.
    private static final String S_APP = "app";
    private static final String S_SENDER = "sender";
    private static final String S_REGISTRATION_ID_KEY = "S_AUTH_TOKEN";
    private static final String S_AUTH_TOKEN_KEY = "S_REGISTRATION_ID";
    private static String S_REGISTRATION_ID = "";
    private static String S_AUTH_TOKEN = "";
    EditText msg_text;
    Button msg_send;

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

        // 마지막 저장된 인증
        S_AUTH_TOKEN = Util.getSharedPreferencesValue(getApplicationContext(), "coolsharp", MODE_PRIVATE, S_AUTH_TOKEN_KEY);
        // 마지막 저장된 레지스트레이션 아이디
        S_REGISTRATION_ID = Util.getSharedPreferencesValue(getApplicationContext(), "coolsharp", MODE_PRIVATE, S_REGISTRATION_ID_KEY);
        if (S_REGISTRATION_ID.equals("")) {
            // C2DM 등록ID 발급
            Intent registrationIntent = new Intent("com.google.android.c2dm.intent.REGISTER");
            registrationIntent.putExtra(S_APP, PendingIntent.getBroadcast(this, 0, new Intent(), 0)); // 어플리케이션ID
            registrationIntent.putExtra(S_SENDER, "xxxx@gmail.com"); // 개발자ID
            startService(registrationIntent); // 서비스 시작(등록ID발급받기)
        }

        msg_text = (EditText) findViewById(R.id.msg_text);
        msg_send = (Button) findViewById(R.id.msg_send);

        msg_send.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View v) {
                // TODO Auto-generated method stub
                try {
                    // 메시지를 보낼때 sender(발급받은 ID, 토큰인증값, 메시지)
                    // 한번 발급 받은 인증을 다시 발급 받지 않게 하기 위함
                    // 인증을 따로 문자열로 저장하는 것도 좋을 듯 함
                    if (S_AUTH_TOKEN.equals("")) {
                        S_AUTH_TOKEN = getAuthToken();
                        Util.setSharedPreferencesValue(getApplicationContext(), "coolsharp", MODE_PRIVATE, S_AUTH_TOKEN_KEY, S_AUTH_TOKEN);
                    }
                    // 한번 발급 받은 REGISTRATION_ID를 다시 발급 받지 않게 하기 위함
                    if (S_REGISTRATION_ID.equals("")) {
                        S_REGISTRATION_ID = C2dm_BroadcastReceiver.registration_id;
                        Util.setSharedPreferencesValue(getApplicationContext(), "coolsharp", MODE_PRIVATE, S_REGISTRATION_ID_KEY, S_REGISTRATION_ID);
                    }
                    sender(S_REGISTRATION_ID, S_AUTH_TOKEN, msg_text.getText().toString());
                } catch (Exception e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                }
            }
        });
    }

    /**
     * 메시지 전송
     * @param regId
     * @param authToken
     * @param msg
     * @throws Exception
     */
    public void sender(String regId, String authToken, String msg) throws Exception {
        StringBuffer postDataBuilder = new StringBuffer();

        postDataBuilder.append("registration_id=" + regId); // 등록ID
        postDataBuilder.append("&collapse_key=1");
        postDataBuilder.append("&delay_while_idle=1");
        postDataBuilder.append("&data.msg=" + URLEncoder.encode(msg, "UTF-8")); // 태울
                                                                                // 메시지

        byte[] postData = postDataBuilder.toString().getBytes("UTF8");

        URL url = new URL("https://android.apis.google.com/c2dm/send");

        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));
        conn.setRequestProperty("Authorization", "GoogleLogin auth=" + authToken);

        OutputStream out = conn.getOutputStream();
        out.write(postData);
        out.close();

        conn.getInputStream();

    }

    /**
     * 인증 토큰 얻어오기
     * @return
     * @throws Exception
     */
    public String getAuthToken() throws Exception {
        String authtoken = "";

        StringBuffer postDataBuilder = new StringBuffer();
        postDataBuilder.append("accountType=HOSTED_OR_GOOGLE"); // 똑같이 써주셔야 합니다.
        postDataBuilder.append("&Email=xxxx@gmail.com"); // 개발자 구글 id
        postDataBuilder.append("&Passwd=xxxx"); // 개발자 구글 비빌번호
        postDataBuilder.append("&service=ac2dm");
        postDataBuilder.append("&source=test-1.0");

        byte[] postData = postDataBuilder.toString().getBytes("UTF8");

        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();

        System.out.println("sidLine----------->>>" + sidLine);
        System.out.println("lsidLine----------->>>" + lsidLine);
        System.out.println("authLine----------->>>" + authLine);
        System.out.println("AuthKey----------->>>" + authLine.substring(5, authLine.length()));

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

        return authtoken;
    }

}

Util.java

package com.coolsharp.push;

import android.content.Context;
import android.content.SharedPreferences;

public class Util {
    public static String getSharedPreferencesValue(Context context, String name, int mode, String key) {
        SharedPreferences prefs = context.getSharedPreferences(name, mode);
        return prefs.getString(key, "");
    }

    public static boolean setSharedPreferencesValue(Context context, String name, int mode, String key, String value) {
        SharedPreferences prefs = context.getSharedPreferences(name, mode);
        SharedPreferences.Editor editor = prefs.edit();
        editor.putString(key, value);
        return editor.commit();
    }
}

AndroidManifest.xml

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.coolsharp.push"
    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:label="@string/app_name"
            android:name=".Coolsharp_pushActivity" >
            <intent-filter >
                <action android:name="android.intent.action.MAIN" />

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

        <receiver
            android:name=".C2dm_BroadcastReceiver"
            android:permission="com.google.android.c2dm.permission.SEND" >
            <intent-filter >
                <action android:name="com.google.android.c2dm.intent.RECEIVE" />

                <category android:name="com.coolsharp.push" />
            </intent-filter>
            <intent-filter >
                <action android:name="com.google.android.c2dm.intent.REGISTRATION" />

                <category android:name="com.coolsharp.push" />
            </intent-filter>
        </receiver>
    </application>

    <permission
        android:name="com.coolsharp.push.permission.C2D_MESSAGE"
        android:protectionLevel="signature" />

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

</manifest>

Posted by coolsharp_backup