我正在运行来自here的Google GCM测试代码,它可以在模拟器和手机上运行,但是当我发送消息时,通知仅适用于模拟器,而不适用于手机。
GCMIntentService Notifcation
import android.support.v4.app.NotificationCompat;
...
// issues a notification to inform the user that server has sent a message
private void generateNotification(Context context, String message) {
NotificationCompat.Builder builder = new NotificationCompat.Builder(context).setSmallIcon(R.drawable.ic_launcher)
.setTicker(context.getString(R.string.app_name)).setContentText(message);
Intent notificationIntent = new Intent(context, Main.class);
notificationIntent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP | Intent.FLAG_ACTIVITY_SINGLE_TOP);
PendingIntent contentIntent = PendingIntent.getActivity(context, 0, notificationIntent, PendingIntent.FLAG_UPDATE_CURRENT);
builder.setContentIntent(contentIntent);
// add notification
NotificationManager manager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
manager.notify(FM_NOTIFICATION_ID, builder.build());
}
PHP发送消息并发送功能
require_once 'push_db_functions.php';
$dbf = new push_db_functions();
$id = '40';
$message = "Test Message";
$response = $dbf->sendMessage($id, $message);
$response = json_decode($response);
print_r($response);
public function sendMessage($id, $message) {
$results = mysql_query("SELECT regid FROM test WHERE id = '$id'");
$processed = mysql_fetch_row($results);
$url = 'https://android.googleapis.com/gcm/send';
$apiKey = "AIzaSyD-xxx";
$fields = array('registration_ids' => $processed, 'data' => array( "message" => $message),);
$headers = array('Authorization: key=' . $apiKey, 'Content-Type: application/json');
// open connection
$ch = curl_init();
// set the url, number of POST vars, POST data
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($fields));
// execute post
$response = curl_exec($ch);
curl_close($ch);
return $response;
}
发送消息回复
stdClass Object ( [multicast_id] => 5036849453049739126 [success] => 1 [failure] => 0 [canonical_ids] => 0 [results] => Array ( [0] => stdClass Object ( [message_id] => 0:1353799902066759%04108f12f9fd7ecd ) ) ) success
我的数据库中有2个regId记录,一个用于模拟器,另一个用于手机$ id 39和40,并相应地更改它们以向任一设备发送消息。
数据库记录
id | regid
39 | APA91bFyMJx4b0ddI........ Emulator
40 | APA91bFhwEhHOClkg........ Phone
手机正在运行Gingerbread,程序会在其上注册并正确运行,除非在收到邮件时没有显示通知。
mDisplay = (TextView) findViewById(R.id.display);
registerReceiver(mHandleMessageReceiver, new IntentFilter(DISPLAY_MESSAGE_ACTION));
final String regId = GCMRegistrar.getRegistrationId(this);
Log.d("registrationID", "::" + regId);
if (regId.equals("")) {
// automatically registers application on startup.
GCMRegistrar.register(this, SENDER_ID);
}
非常感谢任何帮助。
由于
答案 0 :(得分:0)
感谢所有回复此问题的人。
我已经解决了这个问题:
在“帐户”下的手机上同步,常规同步设置,我发现没有勾选后台数据同步框。设置时一切正常。
在问这个问题之前我应该想出来,道歉。
但是我希望这个答案对别人有帮助。