我想创建一个具有推送通知功能的应用。
我所做的是在谷歌注册应用
并从app
存储抵制的设备ID并从服务器发送通知。
一切正常。
我将推送发送到已注册的设备。
我不知道如何在推送时显示推送通知。
答案 0 :(得分:1)
您需要实现GcmListenerService
,下面是一个示例:
/**
* Service used for receiving GCM messages. When a message is received this service will log it.
*/
public class GcmService extends GcmListenerService {
private final int PN_ID = 993;
Booking mBooking;
private static final String TYPE = "type";
private static final String TITLE = "title";
private static final String MESSAGE = "body";
private NotificationManager mNotificationManager;
public GcmService() {
}
@Override
public void onMessageReceived(String from, final Bundle data) {
String type = data.getString(TYPE, "");
final String title = data.getString(TITLE, "");
final String message = data.getString(MESSAGE, "");
if (title.length() > 0 || message.length() > 0) {
sendNotification(PN_ID, title, message);
}
}
@Override
public void onDeletedMessages() {
sendNotification(PN_ID, "Deleted messages on server", "");
}
@Override
public void onMessageSent(String msgId) {
sendNotification(PN_ID, "Upstream message sent. Id=" + msgId, "");
}
@Override
public void onSendError(String msgId, String error) {
sendNotification(PN_ID, "", "Upstream message send error. Id=" + msgId + ", error" + error);
}
// Post a notification indicating whether a doodle was found.
private void sendNotification(int notificationId, String title, 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.mipmap.ic_launcher)
.setContentTitle(title)
.setStyle(new NotificationCompat.BigTextStyle().bigText(msg))
.setContentText(msg)
.setAutoCancel(true);
mBuilder.setContentIntent(contentIntent);
mNotificationManager.notify(notificationId, mBuilder.build());
}
}
在<application>
内的清单中注册,与其他Service
<service
android:name=".services.GcmService"
android:exported="false">
<intent-filter>
<action android:name="com.google.android.c2dm.intent.RECEIVE"/>
</intent-filter>
</service>
您至少需要这些权限,我怀疑您甚至可能需要WAKE_LOCK
。
<!-- PUSH NOTIFICATIONS -->
<uses-permission android:name="com.google.android.c2dm.permission.RECEIVE"/>
<permission
android:name="au.com.myapp.permission.C2D_MESSAGE"
android:protectionLevel="signature"/>
<uses-permission android:name="au.com.myapp.permission.C2D_MESSAGE"/>
在此设置中,您发送到GCM服务的有效负载将如下所示:
{
"registration_ids":[],
"data": {
"title" : "Hello",
"message" : "World",
}
}
registration_ids
是您要向其发送邮件的设备,而data
是Bundle
中将传递给您的内容。