我想在 android 应用程序中为好友请求和消息实现推送通知,如果用户收到好友请求或收到消息,它会显示通知与我想做的完全相同的场景,尝试谷歌但没有找到解决方案,(请不要用 GCM 和 PARSE 推送通知回答我)给我合适的教程链接或帮助我提供有价值的答案,在此先感谢...
问问题
4359 次
1 回答
1
新答案已更新
现在,您将不得不使用 Firebase Cloud Messaging 而不是旧的和已弃用的 GCM:https ://firebase.google.com/docs/cloud-messaging/
旧答案:
官方文档和所有问题的答案都在这里:http: //developer.android.com/google/gcm/gs.html
以下部分将指导您完成设置 GCM 实施的过程。在开始之前,请确保设置 Google Play 服务 SDK。您需要此 SDK 才能使用 GoogleCloudMessaging 方法。
请注意,除了应用程序中的客户端实现之外,完整的 GCM 实现还需要服务器端实现。本文档提供了一个包含客户端和服务器的完整示例。
由于您没有具体要求,我现在无法给出更好的答案,请告诉我们您不明白的地方,我们可能会提供帮助...
编辑:根据评论中的要求,即使在后台运行,这也是您显示通知的方式:
/**
* Handling of GCM messages.
*/
public class GcmBroadcastReceiver extends BroadcastReceiver {
static final String TAG = "GCMDemo";
public static final int NOTIFICATION_ID = 1;
private NotificationManager mNotificationManager;
NotificationCompat.Builder builder;
Context ctx;
@Override
public void onReceive(Context context, Intent intent) {
GoogleCloudMessaging gcm = GoogleCloudMessaging.getInstance(context);
ctx = context;
String messageType = gcm.getMessageType(intent);
if (GoogleCloudMessaging.MESSAGE_TYPE_SEND_ERROR.equals(messageType)) {
sendNotification("Send error: " + intent.getExtras().toString());
} else if (GoogleCloudMessaging.MESSAGE_TYPE_DELETED.equals(messageType)) {
sendNotification("Deleted messages on server: " +
intent.getExtras().toString());
} else {
sendNotification("Received: " + intent.getExtras().toString());
}
setResultCode(Activity.RESULT_OK);
}
// Put the GCM message into a notification and post it.
private void sendNotification(String msg) {
mNotificationManager = (NotificationManager)
ctx.getSystemService(Context.NOTIFICATION_SERVICE);
PendingIntent contentIntent = PendingIntent.getActivity(ctx, 0,
new Intent(ctx, DemoActivity.class), 0);
NotificationCompat.Builder mBuilder =
new NotificationCompat.Builder(ctx)
.setSmallIcon(R.drawable.ic_stat_gcm)
.setContentTitle("GCM Notification")
.setStyle(new NotificationCompat.BigTextStyle()
.bigText(msg))
.setContentText(msg);
mBuilder.setContentIntent(contentIntent);
mNotificationManager.notify(NOTIFICATION_ID, mBuilder.build());
}
}
于 2013-07-03T21:07:56.630 回答