[英]GCM push notification not received from the backend
我正在開發一個包含推送通知的新應用。 這是我到目前為止所做的:
public class C2DMMessageReceiver extends IntentService {
public static final int NOTIFICATION_ID = 1;
private NotificationManager mNotificationManager;
private final String TAG = "GCM Notification receiver..";
NotificationCompat.Builder builder;
public C2DMMessageReceiver() {
super("GcmIntentService");
}
@Override
protected void onHandleIntent(Intent intent) {
Bundle extras = intent.getExtras();
GoogleCloudMessaging gcm = GoogleCloudMessaging.getInstance(this);
// The getMessageType() intent parameter must be the intent you received
// in your BroadcastReceiver.
String messageType = gcm.getMessageType(intent);
if (!extras.isEmpty()) { // has effect of unparcelling Bundle
/*
* Filter messages based on message type. Since it is likely that GCM
* will be extended in the future with new message types, just ignore
* any message types you're not interested in, or that you don't
* recognize.
*/
if (GoogleCloudMessaging.
MESSAGE_TYPE_SEND_ERROR.equals(messageType)) {
sendNotification("Send error: " + extras.toString());
} else if (GoogleCloudMessaging.
MESSAGE_TYPE_DELETED.equals(messageType)) {
sendNotification("Deleted messages on server: " +
extras.toString());
// If it's a regular GCM message, do some work.
} else if (GoogleCloudMessaging.
MESSAGE_TYPE_MESSAGE.equals(messageType)) {
// This loop represents the service doing some work.
for (int i=0; i<5; i++) {
Log.i(TAG, "Working... " + (i+1)
+ "/5 @ " + SystemClock.elapsedRealtime());
try {
Thread.sleep(5000);
} catch (InterruptedException e) {
}
}
Log.i(TAG, "Completed work @ " + SystemClock.elapsedRealtime());
// Post notification of received message.
sendNotification("Received: " + extras.toString());
Log.i(TAG, "Received: " + extras.toString());
}
}
// Release the wake lock provided by the WakefulBroadcastReceiver.
C2DMRegistrationReceiver.completeWakefulIntent(intent);
}
// Put the message into a notification and post it.
// This is just one simple example of what you might choose to do with
// a GCM message.
private void sendNotification(String msg) {
mNotificationManager = (NotificationManager)
this.getSystemService(Context.NOTIFICATION_SERVICE);
PendingIntent contentIntent = PendingIntent.getActivity(this, 0,
new Intent(this, MainActivity.class), 0);
NotificationCompat.Builder mBuilder =
new NotificationCompat.Builder(this)
.setSmallIcon(R.drawable.ic_launcher)
.setContentTitle("עדכוני TGSpot")
.setStyle(new NotificationCompat.BigTextStyle()
.bigText(msg))
.setContentText(msg);
mBuilder.setContentIntent(contentIntent);
mNotificationManager.notify(NOTIFICATION_ID, mBuilder.build());
}
}
這是處理從第三方服務器后端代碼從GCM接收數據的代碼。
設備的令牌已成功保存在服務器上,並通過常規HTTP Post請求將其推送到服務器。
這是Android清單:
<permission android:name="com.tgspot.android.permission.C2D_MESSAGE"
android:protectionLevel="signature"/>
<uses-permission android:name="com.tgspot.android.permission.C2D_MESSAGE"/>
<uses-permission android:name="com.google.android.c2dm.permission.RECEIVE"/>
<uses-permission android:name="android.permission.INTERNET"/>
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE"/>
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.WAKE_LOCK" />
<uses-permission android:name="android.permission.GET_ACCOUNTS" />
<uses-permission android:name="android.permission.USE_CREDENTIALS" />
<application
android:allowBackup="true"
android:icon="@drawable/ic_launcher"
android:theme="@style/Theme.Base.AppCompat.Light.DarkActionBar"
android:label="@string/app_name">
<receiver
android:name=".C2DMRegistrationReceiver"
android:permission="com.google.android.c2dm.permission.SEND"
android:enabled="true">
<intent-filter>
<action android:name="com.google.android.c2dm.intent.REGISTRATION" >
</action>
<category android:name="com.tgspot.android" />
</intent-filter>
</receiver>
<service android:name=".C2DMMessageReceiver">
<intent-filter>
<action android:name="com.google.android.c2dm.intent.RECEIVE" />
</intent-filter>
</service>
<activity
android:name="com.tgspot.android.MainActivity"
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>
C2DMRegistrationReceiver.class
public class C2DMRegistrationReceiver extends WakefulBroadcastReceiver {
@Override
public void onReceive(Context context, Intent intent) {
String action = intent.getAction();
Log.w("C2DM", "Registration Receiver called");
if ("com.google.android.c2dm.intent.REGISTRATION".equals(action)) {
Log.w("C2DM", "Received registration ID");
final String registrationId = intent
.getStringExtra("registration_id");
String error = intent.getStringExtra("error");
Log.d("C2DM", "dmControl: registrationId = " + registrationId
+ ", error = " + error);
String deviceId = Settings.Secure.getString(context.getContentResolver(),
Settings.Secure.ANDROID_ID);
sendRegistrationIdToServer(deviceId, registrationId);
// Also save it in the preference to be able to show it later
saveRegistrationId(context, registrationId);
} else if ("com.google.android.c2dm.intent.RECEIVE".equals(action)) {
ComponentName comp = new ComponentName(context.getPackageName(),
C2DMMessageReceiver.class.getName());
startWakefulService(context, (intent.setComponent(comp)));
setResultCode(Activity.RESULT_OK);
}
}
private void saveRegistrationId(Context context, String registrationId) {
SharedPreferences prefs = PreferenceManager
.getDefaultSharedPreferences(context);
SharedPreferences.Editor edit = prefs.edit();
edit.putString("C2DMM_AUTH", registrationId);
edit.commit();
}
public void sendRegistrationIdToServer(String deviceId,
String registrationId) {
Log.d("C2DM", "Sending registration ID to my application server");
final HttpClient client = new DefaultHttpClient();
final HttpPost post = new HttpPost("http://www.tgspot.co.il/register/");
// set up the POST data
List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(1);
// Get the deviceID
nameValuePairs.add(new BasicNameValuePair("os", "Android"));
nameValuePairs.add(new BasicNameValuePair("token",
registrationId));
// encode the POST data
try {
post.setEntity(new UrlEncodedFormEntity(nameValuePairs));
} catch (UnsupportedEncodingException e1) {
//e1.printStackTrace();
}
// execute the HTML POST call to hit the server
new Thread(new Runnable() {
public void run() {
try {
HttpResponse response = client.execute(post);
} catch (ClientProtocolException e) {
//e.printStackTrace();
} catch (IOException e) {
//e.printStackTrace();
}
}
}).start();
}
}
在清單中,您缺少<action android:name="com.google.android.c2dm.intent.RECEIVE" />
是C2DMRegistrationReceiver
的意圖過濾器。 沒有它,GCM消息廣播將無法到達該應用程序。
您沒有在清單中包括清單的權限部分,因此我無法確定您是否缺少其他內容。
您的C2DMRegistrationReceiver
僅處理REGISTRATION意圖。 它還應處理com.google.android.c2dm.intent.RECEIVE
。 這些是接收GCM消息的意圖。
實際上,如果您將新的同步注冊方法與GoogleCloudMessaging.register一起使用,那么C2DMRegistrationReceiver根本不需要處理REGISTRATION意圖(我看到您已經在使用該類了)。
您的onReceive
方法應更改為:
public void onReceive(Context context, Intent intent) {
String action = intent.getAction();
Log.w("C2DM", "Registration Receiver called");
if ("com.google.android.c2dm.intent.REGISTRATION".equals(action)) {
Log.w("C2DM", "Received registration ID");
final String registrationId = intent
.getStringExtra("registration_id");
String error = intent.getStringExtra("error");
Log.d("C2DM", "dmControl: registrationId = " + registrationId
+ ", error = " + error);
String deviceId = Settings.Secure.getString(context.getContentResolver(),
Settings.Secure.ANDROID_ID);
sendRegistrationIdToServer(deviceId, registrationId);
// Also save it in the preference to be able to show it later
saveRegistrationId(context, registrationId);
} else if ("com.google.android.c2dm.intent.RECEIVE".equals(action)) {
ComponentName comp = new ComponentName(context.getPackageName(),
C2DMMessageReceiver.class.getName());
startWakefulService(context, (intent.setComponent(comp)));
setResultCode(Activity.RESULT_OK);
}
}
這樣, com.google.android.c2dm.intent.RECEIVE
廣播將觸發C2DMMessageReceiver
服務,該服務顯示通知。
如果您正在使用新的注冊方法,則完全不需要第一個條件。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.