我正尝试在我的 Android 应用中实现 GCM。服务器端和客户端设置似乎是正确的,因为当我从服务器端“推送”一个字符串时调用了 onMessage 方法。我可以从 Intent 中读取额外内容,但是,使用通知或 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 并在几秒钟后关闭。这可能与它有关吗?
最佳答案
这不是上下文
问题。
GCM 接收器在一个 Intent 服务中运行,该服务本身在一个单独的线程上运行。
要显示 toast ,只需从 UIThread 内部调用即可。你可以这样做:
Handler h = new Handler(Looper.getMainLooper());
h.post(new Runnable(){
Toast.makeText(context, intent.getStringExtra("message"), Toast.LENGTH_SHORT).show();
});
这现在将发布到您的 UI 线程上,然后您将看到 toast !
(您需要使局部变量的 final
才能由匿名类执行)
干杯!
关于Android GCMIntentService onMessage 上下文问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12163822/