▼Androidメモ▼
C2DMの利用
C2DMを利用するプログラムを作成する。
![]()
D2CMのアカウント登録
GoogleのサイトでD2CMを利用するためのアカウント登録を行い、コードの[登録したアカウント]に埋め込む。
バックアップのテスト手順
- C2DMExを起動し、デバイス登録IDを取得。
CatLogに出力されるので、AppServerに埋め込む。
本番ではHTTP通信で通知してアプリケーションサーバで保持。
- 他の端末でAppServerを起動し、メッセージの送信ボタンを押す。
- C2DMExをインストールした端末でトーストが表示される。
アプリのソースコード
C2DMEx.java package net.npaka.c2dmex; import android.app.Activity; import android.app.PendingIntent; import android.content.Intent; import android.graphics.Color; import android.os.Bundle; import android.view.View; import android.view.Window; import android.widget.Button; import android.widget.LinearLayout; //C2DMの利用 public class C2DMEx extends Activity implements View.OnClickListener { private final static int WC=LinearLayout.LayoutParams.WRAP_CONTENT; public static Intent regIntent;//登録インテント @Override public void onCreate(Bundle bundle) { super.onCreate(bundle); requestWindowFeature(Window.FEATURE_NO_TITLE); //登録インテントの生成 regIntent=new Intent("com.google.android.c2dm.intent.REGISTER"); regIntent.putExtra("app",PendingIntent.getBroadcast(this,0,new Intent(),0)); regIntent.putExtra("sender","[登録したアカウント]"); //レイアウトの生成 LinearLayout layout=new LinearLayout(this); layout.setBackgroundColor(Color.rgb(255,255,255)); layout.setOrientation(LinearLayout.VERTICAL); setContentView(layout); //ボタンの生成 layout.addView(makeButton("デバイス登録IDの取得","0")); } //ボタンの生成 private Button makeButton(String text,String tag) { Button button=new Button(this); button.setText(text); button.setTag(tag); button.setOnClickListener(this); button.setLayoutParams(new LinearLayout.LayoutParams(WC,WC)); return button; } //ボタンクリック時に呼ばれる public void onClick(View view) { startService(regIntent); } }
C2DMReceiver.java package net.npaka.c2dmex; import android.content.BroadcastReceiver; import android.content.Context; import android.content.Intent; import android.widget.Toast; //C2DMのブロードキャストレシーバ public class C2DMReceiver extends BroadcastReceiver { //受信時に呼ばれる @Override public void onReceive(Context context,Intent intent) { //デバイス登録IDの受信 if (intent.getAction().equals("com.google.android.c2dm.intent.REGISTRATION")) { String regID=intent.getStringExtra("registration_id"); //登録失敗 if (intent.getStringExtra("error")!=null) { toast(context,"error"); } //登録解除完了 else if (intent.getStringExtra("unregistered")!=null) { toast(context,"unregistered"); } //登録完了 else if (regID!=null) { toast(context,"regID>"+regID); android.util.Log.e("","regID>"+regID); //本番アプリではココでデバイス登録IDをアプリサーバに通知 } } //メッセージの受信 else if (intent.getAction().equals("com.google.android.c2dm.intent.RECEIVE")) { toast(context,"message>"+intent.getStringExtra("testdata")); } } //トーストの表示 public static void toast(Context context,String text) { Toast.makeText(context,text,Toast.LENGTH_LONG).show(); } }
AndroidManifest.xml <?xml version="1.0" encoding="utf-8"?> <manifest xmlns:android="http://schemas.android.com/apk/res/android" package="net.npaka.c2dmex" android:versionCode="1" android:versionName="1.0"> <application android:icon="@drawable/icon" android:label="@string/app_name"> <activity android:name=".C2DMEx" 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"> <intent-filter> <action android:name="com.google.android.c2dm.intent.RECEIVE" /> <category android:name="net.npaka.c2dmex" /> </intent-filter> <intent-filter> <action android:name="com.google.android.c2dm.intent.REGISTRATION" /> <category android:name="net.npaka.c2dmex" /> </intent-filter> </receiver> </application> <uses-sdk android:minSdkVersion="8" /> <permission android:name="net.npaka.c2dmex.permission.C2D_MESSAGE" android:protectionLevel="signature" /> <uses-permission android:name="net.npaka.c2dmex.permission.C2D_MESSAGE" /> <uses-permission android:name="com.google.android.c2dm.permission.RECEIVE" /> <uses-permission android:name="android.permission.INTERNET" /> </manifest>
アプリケーションサーバのソースコード
AppServer.java package net.npaka.appserver; import java.io.ByteArrayOutputStream; import java.io.InputStream; import java.io.OutputStream; import java.net.HttpURLConnection; import java.net.URL; import android.app.Activity; import android.content.Context; import android.graphics.Color; import android.os.Bundle; import android.view.View; import android.view.Window; import android.widget.Button; import android.widget.LinearLayout; import android.widget.Toast; //C2DMのアプリケーションサーバー //(練習用にAndroidアプリで作成してるが本番ではサーバーサイドアプリとして作成) public class AppServer extends Activity implements View.OnClickListener { private final static int WC=LinearLayout.LayoutParams.WRAP_CONTENT; private static String account ="[登録したアカウント]"; private static String password="[登録したアカウントのパスワード]"; private static String regID ="[デバイス登録ID]"; private static String auth; //アクティビティ起動時に呼ばれる @Override public void onCreate(Bundle bundle) { super.onCreate(bundle); requestWindowFeature(Window.FEATURE_NO_TITLE); //レイアウトの生成 LinearLayout layout=new LinearLayout(this); layout.setBackgroundColor(Color.rgb(255,255,255)); layout.setOrientation(LinearLayout.VERTICAL); setContentView(layout); //ボタンの生成 layout.addView(makeButton("メッセージの送信","0")); } //ボタンの生成 private Button makeButton(String text,String tag) { Button button=new Button(this); button.setText(text); button.setTag(tag); button.setOnClickListener(this); button.setLayoutParams(new LinearLayout.LayoutParams(WC,WC)); return button; } //ボタンクリック時に呼ばれる public void onClick(View view) { try { //ログイン情報の取得 String str=clientLogin(account,password); android.util.Log.e("","clientLogin>"+str+";"); //認証トークンの取得 int start=str.indexOf("Auth="); str=str.substring(start+5); int end=str.indexOf("\n"); auth=str.substring(0,end); android.util.Log.e("","Auth>"+auth); //メッセージの送信 str=sendMessage("hello!"); android.util.Log.e("","sendMessage>"+str); toast(this,"Done"); } catch (Exception e) { toast(this,e.toString()); } } //認証トークンの取得 private String clientLogin(String account,String password) throws Exception { String path="https://www.google.com/accounts/ClientLogin"; String body="accountType=GOOGLE&Email="+account+"&Passwd="+password+ "&source=MyCorp-Myname-Ver&service=ac2dm"; byte[] w=http2data(path,body.getBytes()); return new String(w); } //メッセージの送信 private String sendMessage(String message) throws Exception { String path="https://android.apis.google.com/c2dm/send"; String body="registration_id="+regID+"&collapse_key=1&data.testdata="+message; byte[] w=http2data(path,body.getBytes()); return new String(w); } //HTTP(POST)→バイトデータ public static byte[] http2data(String path,byte[] body) throws Exception { byte[] w=new byte[1024]; HttpURLConnection c=null; InputStream in=null; ByteArrayOutputStream out=null; try { //HTTP接続のオープン URL url=new URL(path); c=(HttpURLConnection)url.openConnection(); c.setRequestMethod("POST"); if (auth!=null) { c.setRequestProperty("Authorization", "GoogleLogin auth="+auth); } //バイト配列の書き込み c.setDoOutput(true); OutputStream bout=c.getOutputStream(); bout.write(body); bout.flush(); bout.close(); //バイト配列の読み込み in=c.getInputStream(); out=new ByteArrayOutputStream(); while (true) { int size=in.read(w); if (size<=0) break; out.write(w,0,size); } out.close(); in.close(); //HTTP接続のクローズ c.disconnect(); byte[] result=out.toByteArray(); return result; } catch (Exception e) { try { if (c !=null) c.disconnect(); if (in !=null) in.close(); if (out!=null) out.close(); } catch (Exception e2) { } throw e; } } //トーストの表示 public static void toast(Context context,String text) { Toast.makeText(context,text,Toast.LENGTH_LONG).show(); } }
AndroidManifest.xml <?xml version="1.0" encoding="utf-8"?> <manifest xmlns:android="http://schemas.android.com/apk/res/android" package="net.npaka.appserver" android:versionCode="1" android:versionName="1.0"> <application android:icon="@drawable/icon" android:label="@string/app_name"> <activity android:name=".AppServer" android:label="@string/app_name"> <intent-filter> <action android:name="android.intent.action.MAIN" /> <category android:name="android.intent.category.LAUNCHER" /> </intent-filter> </activity> </application> <uses-sdk android:minSdkVersion="8" /> <uses-permission android:name="android.permission.INTERNET" /> </manifest>
−戻る−