我正在尝试在我的 Android 应用中实现 GCM。服务器和客户端的设置似乎是正确的,因为当我从服务器端“推送”一个字符串时会调用 onMessage 方法。我可以从意图中读取额外内容,但是,使用通知或 Toast 消息不起作用。即使应用程序正在运行,手机也没有显示任何内容,所以我猜想我在回调中使用的上下文对象有些不对劲。这是 manifest.xml 的相关部分,其中 PACKAGE 是基本包。
<receiver
android:name="PACKAGE.gcm.GCMReceiver"
android:enabled="true"
android:permission="com.google.android.c2dm.permission.SEND" >
<intent-filter>
<action android:name="com.google.android.c2dm.intent.RECEIVE" />
<action android:name="com.google.android.c2dm.intent.REGISTRATION" />
<category android:name="PACKAGE" />
</intent-filter>
</receiver>
<service
android:name="PACKAGE.gcm.GCMIntentService"
android:enabled="true" />
</application>
<permission
android:name="PACKAGE.permission.C2D_MESSAGE"
android:protectionLevel="signature" />
<uses-permission android:name="PACKAGE.C2D_MESSAGE" />
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
<uses-permission android:name="android.permission.CALL_PHONE" />
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
<!-- App receives GCM messages. -->
<uses-permission android:name="com.google.android.c2dm.permission.RECEIVE" />
<!-- GCM requires a Google account. -->
<uses-permission android:name="android.permission.GET_ACCOUNTS" />
<!-- Keeps the processor from sleeping when a message is received. -->
<uses-permission android:name="android.permission.WAKE_LOCK" />
</manifest>
现在 onMessage 方法:
@Override
protected void onMessage(Context context, Intent intent)
{
if (DEBUG)
{
System.out.println("[GCMIntentService] Message Received! " + intent.getStringExtra("message"));
}
Toast.makeText(context, intent.getStringExtra("message"), Toast.LENGTH_SHORT).show();
String ns = Context.NOTIFICATION_SERVICE;
NotificationManager mNotificationManager = (NotificationManager) getSystemService(ns);
// int icon = R.drawable.notification_icon;
CharSequence tickerText = intent.getStringExtra("message");
long when = System.currentTimeMillis();
Notification notification = new Notification(0, tickerText, when);
CharSequence contentTitle = "Some Notification";
CharSequence contentText = tickerText + " some more text";
notification.setLatestEventInfo(context, contentTitle, contentText, null);
final int HELLO_ID = 1;
mNotificationManager.notify(HELLO_ID, notification);
}
Toast 和通知不起作用。我在第一个 Activity 的 onCreate 中调用服务和注册例程,它用作 Splash 并在几秒钟后关闭。这可能与它有关吗?