iOS APNsとandroid GCMのプッシュ通知実装方法の違い
プッシュ通知はアプリをクラウドと連携する際やスマホ同士のピアツーピア通信を実現する際に、とても有用な機能だ。
androidの場合は、サービスというバックグラウンドプロセスを動作させることができるので、自作のスマホ同士の通信を実現することが可能だが、iOSではリアルタイムの通信を実現するにはプッシュ通知を使うほかにその方法はない。
iPhoneもアンドロイドスマホでもAppleとGoogleのクラウドと各OSが直接通信することで、任意の時間にスマホに通知イベントを送付できる。
AppleとGoogleのクラウドを経由させて、スマホ同士が簡単にソケット通信することができる素晴らしい機能だ。
自社クラウドとスマホのソケット通信を実現することももちろん可能だ。
androidは、プッシュ通知受信サービス、トークン受信サービスをアプリが定義実装しなければならない。
iOS APNs
・UIApplicationDelegateにすでにメソッドが定義されている
・デバイストークン受信メソッド
// デバイストークンがAPNsから発行されたとき-(void)application:(UIApplication *)application didRegisterForRemoteNotificationsWithDeviceToken:(NSData *)deviceToken {}・プッシュ通知受信メソッド// push通知を受信したとき- (void)application:(UIApplication *)app didReceiveRemoteNotification:(NSDictionary *)userInfo { NSString *message = aps[@"alert"][@"body"]; // メッセージ // ローカル通知発行 [[UIApplication sharedApplication] presentLocalNotificationNow:localNotification];}
android GCM
・デバイストークン受信とプッシュ通知受信のために次の2つのサービスを定義し別プロセスとして実行する必要がある
1)GcmListenerService
2)InstanceIDListenerService
・デバイストークン受信< GCMトークンを受信リスナ >< service
android:name=".AInstanceIDListenerService"
android:exported="false">
< intent-filter>
< action android:name="com.google.android.gms.iid.InstanceID"/>
< /intent-filter>< /service>public class AInstanceIDListenerService extends InstanceIDListenerService {
// デバイストークン受信メソッド
@Override
public void onTokenRefresh() { }}
・プッシュ通知受信に必要な手続き
< receiver
android:name="com.google.android.gms.gcm.GcmReceiver"
android:exported="true"
android:permission="com.google.android.c2dm.permission.SEND"> < intent-filter>
< action android:name="com.google.android.c2dm.intent.RECEIVE" />
< category android:name="your.package.name" />
< /intent-filter>< /receiver>
< service
android:name=".AGcmListenerService"
android:exported="false" >
< intent-filter> < action android:name="com.google.android.c2dm.intent.RECEIVE" /> < /intent-filter>< /service>public class AGcmListenerService extends GcmListenerService {
// プッシュ通知受信メソッド@Override
public void onMessageReceived(String from, Bundle payloadDict) {
String message = payloadDict.getString("alert"); // GCMメッセージ
String seq = payloadDict.getString("SEQ"); // シーケンス文字 NotificationManager#notify(); // ローカル通知発行}}