package test.android.test;
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.content.SharedPreferences;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
public class C2dmTest extends Activity {
/** Called
when the activity is first created. */
EditText msg_text;
Button msg_send;
String REG_ID;
String AUTH_TOKEN;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
Log.d("C2DM_REGISTRATION", "onCreate");
SharedPreferences reg_Id =
getSharedPreferences("c2dm_reg_id", 0);
REG_ID =
reg_Id.getString("REG_ID", null);
SharedPreferences auth_token =
getSharedPreferences("c2dm_auth_token", 0);;
AUTH_TOKEN =
auth_token.getString("AUTH_TOKEN", null);
if (REG_ID == null) {
Log.d("C2DM_REGISTRATION", "REG_ID==null");
// C2DM 등록ID 발급
Intent registrationIntent = new Intent(
"com.google.android.c2dm.intent.REGISTER");
registrationIntent.putExtra("app", PendingIntent.getBroadcast(this,
0, new Intent(), 0)); // 어플리케이션ID
registrationIntent.putExtra("sender", "자기메일주소@gmail.com"); // 개발자ID
startService(registrationIntent);
// 서비스 시작(등록ID발급받기)
// 위에서 지정한 "app"와
"sender"은 맘대로 지정하시는게 아니라 구글에서 필요한 변수명들입니다.
} else {
Log.d("C2DM_REGISTRATION", "REG_ID!=null");
}
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(AUTH_TOKEN==null){
Log.d("C2DM_REGISTRATION", "AUTH==null");
sender(C2dm_BroadcastReceiver.registration_id,
getAuthToken(), msg_text.getText().toString());
}
else {
Log.d("C2DM_REGISTRATION", "AUTH!=null");
if(REG_ID!=null){
sender(REG_ID , AUTH_TOKEN , msg_text.getText().toString());
} else {
sender(C2dm_BroadcastReceiver.registration_id,
AUTH_TOKEN , msg_text.getText().toString());
}
}
msg_text.setText("");
} catch (Exception e) {
// TODO
Auto-generated catch block
e.printStackTrace();
}
}
});
}
public void sender(String regId, String authToken, String msg)
throws Exception {
Log.d("C2DM_REGISTRATION", "==================================");
Log.d("C2DM_REGISTRATION", "regId="+regId);
Log.d("C2DM_REGISTRATION", "authToken="+authToken);
Log.d("C2DM_REGISTRATION", "msg="+msg);
Log.d("C2DM_REGISTRATION", "==================================");
Log.d("C2DM_REGISTRATION", "
");
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();
}
public String
getAuthToken() throws Exception {
String authtoken = "";
StringBuffer postDataBuilder = new StringBuffer();
postDataBuilder.append("accountType=HOSTED_OR_GOOGLE"); // 똑같이 써주셔야 합니다.
postDataBuilder.append("&Email=자기메일주소@gmail.com"); // 개발자 구글 id
postDataBuilder.append("&Passwd=자기메일주소암호"); // 개발자 구글 비빌번호
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();
Log.d("C2DM_REGISTRATION", "sidLine----------->>>" + sidLine);
Log.d("C2DM_REGISTRATION", "lsidLine----------->>>" + lsidLine);
Log.d("C2DM_REGISTRATION", "authLine----------->>>" + authLine);
Log.d("C2DM_REGISTRATION", "AuthKey----------->>>"
+
authLine.substring(5, authLine.length()));
authtoken = authLine.substring(5,
authLine.length());
Log.d("C2DM_REGISTRATION", "authtoken====>" + authtoken);
SharedPreferences auth_token =
getSharedPreferences("c2dm_auth_token", 0);
SharedPreferences.Editor ed =
auth_token.edit();
ed.putString("AUTH_TOKEN", authtoken);
ed.commit();
return authtoken;
}
}
package test.android.test;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.util.Log;
import android.view.Gravity;
import android.widget.Toast;
public class C2dm_BroadcastReceiver extends BroadcastReceiver{
/** Called
when the activity is first created. */
static String registration_id = null;
static String c2dm_msg = "";
@Override
public void onReceive(Context context, Intent intent) {
Log.d("C2DM_REGISTRATION", "onReceive");
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");
Log.d("C2DM_REGISTRATION", "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();
}
}
private void handleRegistration(Context context, Intent intent) {
registration_id = intent.getStringExtra("registration_id");
Log.d("C2DM_REGISTRATION", "registration_id====>"+registration_id);
if (intent.getStringExtra("error") != null) {
Log.d("C2DM_REGISTRATION", ">>>>>" + "Registration
failed, should try again later." + "<<<<<");
} else if (intent.getStringExtra("unregistered") != null) {
Log.d("C2DM_REGISTRATION", ">>>>>" + "unregistration
done, new messages from the authorized sender will be rejected" + "<<<<<");
} else if (registration_id != null) {
Log.d("C2DM_REGISTRATION", "registration_id
complete!!");
SharedPreferences
reg_id = context.getSharedPreferences("c2dm_reg_id", 0);
SharedPreferences.Editor
ed = reg_id.edit();
ed.putString("REG_ID", registration_id);
ed.commit();
}
}
}
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="horizontal"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:background="#ffffff"
android:gravity="center_vertical"
>
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="메세지 보내기"
/>
<EditText
android:id="@+id/msg_text"
android:layout_width="180dip"
android:layout_height="wrap_content"/>
<Button
android:id="@+id/msg_send"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="보내기"/>
</LinearLayout>
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="test.android.test"
android:versionCode="1"
android:versionName="1.0">
<application android:icon="@drawable/icon"
android:label="@string/app_name">
<activity android:name=".C2dmTest"
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=".C2dm_BroadcastReceiver"
android:permission="com.google.android.c2dm.permission.SEND">
<intent-filter>
<action android:name="com.google.android.c2dm.intent.RECEIVE"/>
<category android:name="test.android.test"/>
</intent-filter>
<intent-filter>
<action android:name="com.google.android.c2dm.intent.REGISTRATION"/>
<category android:name="test.android.test"/>
</intent-filter>
</receiver>
</application>
<permission android:name="test.android.test.permission.C2D_MESSAGE"
android:protectionLevel="signature"/>
<uses-permission android:name="test.android.test.permission.C2D_MESSAGE"/>
<uses-permission android:name="com.google.android.c2dm.permission.RECEIVE"/>
<uses-permission android:name="android.permission.INTERNET"/>
<uses-sdk android:minSdkVersion="8"
/>
</manifest>
지금 당장 이걸가지고 멀 만들어 볼 순 없겠다.
아 중요한거!!! GTalk 그지같은거 한번 실행해서 로그인중에 메뉴 버튼 눌러서 로그인 취소 누른후에 동작해야한다...
난 GTalk쓰지도 않는데...지우지도 못하고...