我有 c2dm 的注册 ID 和身份验证令牌。然后我通过将这些值存储在 db 中。并使用 php,我可以向 c2dm 服务器发送一条消息。但我的问题是我不知道如何在应用程序中接收消息。我不确定我获取消息的方式是否正确。无论如何,我会在下面给出。
我有一项使用注册意图注册到 c2dm 的活动。和一个接收器来接收 reg_id 和通知消息。它正在注册 c2dm 并且不接收消息。
显现
<intent-filter>
<action android:name="com.google.android.c2dm.intent.REGISTRATION"></action>
<category android:name="my.android.c2dm"></category>
</intent-filter>
<intent-filter>
<action android:name="com.google.android.c2dm.intent.RECEIVE"></action>
<category android:name="my.android.c2dm"></category>
</intent-filter>
</receiver>
</application>
C2dmRegistration.class(活动)
Intent objRegIntnet=new Intent("com.google.android.c2dm.intent.REGISTER");
objRegIntnet.putExtra("app",PendingIntent.getBroadcast(this,0,new Intent(),0));
objRegIntnet.putExtra("sender","mymail@gmail.com");
startService(objRegIntnet);
c2dm接收器
public class c2dmReceiver extends BroadcastReceiver
{
private static String KEY = "c2dmPref";
private static String REGISTRATION_KEY = "registrationKey";
private Context context;
@Override
public void onReceive(Context context, Intent intent)
{
this.context = context;
if (intent.getAction().equals("com.google.android.c2dm.intent.REGISTRATION"))
{
handleRegistration(context, intent);
}
else if (intent.getAction().equals("com.google.android.c2dm.intent.RECEIVE"))
{
handleMessage(context, intent);
}
}
private void handleRegistration(Context context, Intent intent)
{
//handles registeration
}
private void handleMessage(Context context, Intent intent)
{
String title= intent.getStringExtra("title");
String message= intent.getStringExtra("msg");
Toast.makeText(context,"title : "+title+"\n message : "+message,1).show();
//Do whatever you want with the message
}
请告诉我犯了什么错误...
更新
大家好,今天我正在使用相同的代码。我所做的错误是使用 php 代码。我没有将值作为 POST 传递,而是以 GET 形式发送。当我将其更改为 POST 时,将显示 toast 消息。但仍然存在一些问题。
标题和 msg 值在此处为空。我的 php 代码是:
function sendMessageToPhone($authCode, $deviceRegistrationId, $msgType, $messageText)
{
//$messageText="have a nice day";
//$msgtype="important";
$headers = array('Authorization: GoogleLogin auth=' . $authCode);
$data = array(
'registration_id' => $deviceRegistrationId,
'collapse_key' => $msgType,
'data.message' => $messageText
);
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, "https://android.apis.google.com/c2dm/send");
if ($headers)
curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_POSTFIELDS, $data);
$response = curl_exec($ch);
curl_close($ch);
return $response;
}
实际上我不确定collapse_key和data.message变量应该使用什么类型的值。
请帮助我...谢谢...