私はAndroidのプッシュ通知に取り組んでいます.Google APIコンソールでアプリを作成しました:
また、すべての権限を提供しますが、まだ空の登録 ID を取得しています。
これが私のコードです:
public void registerGCMNotifications(){
GCMRegistrar.checkDevice(this);
GCMRegistrar.checkManifest(this);
String regId = GCMRegistrar.getRegistrationId(this);
if (regId.equals("")) {
GCMRegistrar.register(this, "sender_id");//sender id
Constants.REGISTRATION_ID = GCMRegistrar.getRegistrationId(this);
} else {
System.out.println(regId);
}
}
このコードは、空の registrationId を返します。
GCMIntentService のコードは次のとおりです。
package com.interactive.pushnotification;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import android.app.Notification;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.content.Context;
import android.content.Intent;
import android.util.Log;
import com.example.interactiveapp.R;
import com.google.android.gcm.GCMBaseIntentService;
import com.interactiveapp.Constants;
public class GCMIntentService extends GCMBaseIntentService {
public GCMIntentService() {
super("sender_id");
}
@Override
protected void onRegistered(Context arg0, String registrationId) {
Constants.REGISTRATION_ID=registrationId;
System.out.println("ID: "+registrationId);
}
@Override
protected void onUnregistered(Context arg0, String arg1) {
}
@Override
protected void onMessage(Context arg0, Intent arg1) {
String message = arg1.getStringExtra("message");
//displayNotification(message);
}
@Override
protected void onError(Context arg0, String errorId) {
Log.i(TAG, "Received error: " + errorId);
}
@Override
protected boolean onRecoverableError(Context context, String errorId) {
return super.onRecoverableError(context, errorId);
}
@SuppressWarnings("deprecation")
public void displayNotification(String message)
{
//int count=Constant.pushNotificationsCount++;
// this
NotificationManager mNotificationManager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
// Get Device Date Time...
Calendar cl = Calendar.getInstance();
SimpleDateFormat sdf = new SimpleDateFormat("dd-MM-yyyy HH:mm a");
String Strtdates = sdf.format(cl.getTime());
long when = System.currentTimeMillis();
Context context = getApplicationContext();
CharSequence contentTitle = "";
Intent notificationIntent = new Intent(this, GCMIntentService.class);
PendingIntent contentIntent = PendingIntent.getActivity(this, 0, notificationIntent, 0);
Notification notification = new Notification(R.drawable.ic_launcher, "H",0);
notification.defaults |= Notification.DEFAULT_SOUND;
notification.defaults |= Notification.DEFAULT_VIBRATE;
notification.setLatestEventInfo(context, contentTitle, message, contentIntent);
// and this
mNotificationManager.notify(0, notification);
//System.out.println(count);
}
}