我正在构建一个Android应用,目前正致力于通知。我正在使用Google Cloud Messaging服务,我为此编写了以下PHP代码:
<?php
define('API_ACCESS_KEY', 'blablabla');
$registrationIds = array($this->deviceId);
$data = array
(
'title' => 'My Title',
'message' => 'My message',
'subtitle' => 'This is a subtitle. subtitle',
'tickerText' => 'Ticker text here...Ticker text here...',
'vibrate' => 1,
'sound' => 1
);
$fields = array
(
'registration_ids' => $registrationIds,
'data' => $data
);
$headers = array
(
'Authorization: key=' . API_ACCESS_KEY,
'Content-Type: application/json'
);
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, 'https://android.googleapis.com/gcm/send');
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($fields));
curl_exec($ch);
curl_close($ch);
当我执行这个php文件时,我会在我的Android设备上收到通知,如下面的屏幕截图所示。消息文本没问题。 android screenshot 但问题是,通知的标题不是我在有效载荷中写的“我的标题”,而是“GCM消息”(看起来像默认的GCM标题)。 尝试过很多不同的事情,但没想出来。
我错的任何想法?感谢
--------解决方案--------
我完全忘记了必须在android端处理...解决方案是在MyGcmListenerService中自定义sendNotification()方法来处理额外的数据:
private void sendNotification(String title, String message) {
Intent intent = new Intent(this, MainActivity.class);
intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
PendingIntent pendingIntent = PendingIntent.getActivity(this, 0, intent, PendingIntent.FLAG_ONE_SHOT);
Uri defaultSoundUri = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION);
NotificationCompat.Builder notificationBuilder = new NotificationCompat.Builder(this)
.setSmallIcon(R.drawable.ic_launcher)
.setContentTitle(title)
.setContentText(message)
.setAutoCancel(true)
.setSound(defaultSoundUri)
.setContentIntent(pendingIntent);
NotificationManager notificationManager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
notificationManager.notify(0 /* ID of notification */, notificationBuilder.build());
}
感谢您的回答!
答案 0 :(得分:1)
为了设置自定义通知标题,您应该在GcmListenerService类的onMessageReceived(String form,Bundle data)方法中创建自己的通知...我在创建自定义通知时所做的工作在以下代码中描述:
public class MyGcmListenerService extends GcmListenerService {
private PendingIntent resultPendingIntent;
@Override
public void onMessageReceived(String from, Bundle data) {
NotificationCompat.Builder nBuilder = new NotificationCompat.Builder(this)
.setSmallIcon(R.drawable.app_logo)
.setContentTitle(data.getString(getResources().getString(R.string.notification_title)))
.setContentText(data.getString(getResources().getString(R.string.notification_body)))
.setDefaults(Notification.DEFAULT_VIBRATE)
.setContentIntent(resultPendingIntent);
int mNotificationId = 001;
NotificationManager mNotifyMgr = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
mNotifyMgr.notify(mNotificationId, nBuilder.build());
}
}
在setContentTitle中设置自定义通知标题。