我正在尝试在我的Android应用上实现推送通知。所以没有比Googles Developers页面更好的起点了。
我正在尝试按照本教程:GCM Demo App。教程建议使用通过SDK Manager提供的示例代码。执行此操作并尝试发送推送通知后,当应用程序运行时,我会在屏幕上看到正在写入新推送已到达。
然而,当应用程序处于后台或未运行时,我没有获得推送通知。如果我打开应用程序,屏幕上会再次显示消息。但我从来没有通过弹出和声音获得任何通知形式。
我是否必须在Android中手动执行此操作?我认为它与iOS类似,平台负责向您显示通知。
我是如何实现它的?
答案 0 :(得分:5)
但是我从来没有通过弹出窗口和通知的形式得到任何东西 一个声音。
触发通知时,声音可以编程到代码中。用这样的话说。
Notification notification = new Notification(icon, tickerText, when);
notification.sound = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION);
然而,当应用程序处于后台或未运行时,我没有得到推送通知
我是否必须在Android中手动执行此操作?我以为会是 类似于iOS平台负责向您展示的 通知。
您的应用始终已发送GCM数据(推送通知)。您如何处理这些数据取决于您。 GCM意向服务负责向您提供数据,就是这样。您需要使用通知服务向用户显示相应的通知。
这种方法有优点/缺点。当您收到推送通知时,应用程序代码将在Android上运行,而iPhone上并非如此。您还可以灵活地进行更新,或根据推送通知的类型通知用户。
在您的应用启动时使用发件人ID注册您的设备,您应该按预期收到通知。所有推送通知都将在您选择的GCMIntentService上传递给此方法protected void onMessage(Context context, Intent intent)
。
答案 1 :(得分:3)
尝试重新注册并重新注册您的设备。 在DemoActivity.java中添加
final String regId = GCMRegistrar.getRegistrationId(this);
GCMRegistrar.unregister(this);
然后,在第二次启动时删除GCMRegistrar.unregister(this);
。
<强>更新强>
您的申请中的通知:
创建课程
public class DemoApplication extends Application {
private class NotifyReceiver extends BroadcastReceiver{
@Override
public void onReceive(Context context, Intent intent) {
Toast.makeText(context, "RECEIVE MESSAGE", Toast.LENGTH_SHORT).show();
}
}
private NotifyReceiver notifyReceiver = new NotifyReceiver();
@Override
public void onCreate() {
registerReceiver(notifyReceiver, new IntentFilter("GCM_MESSAGE"));
super.onCreate();
}
@Override
public void onTerminate() {
unregisterReceiver(notifyReceiver);
super.onTerminate();
}
}
然后把
<application
android:name=".DemoApplication"
android:icon="@drawable/ic_launcher"
android:label="@string/app_name" >
在AndroidManifest.xml中并在
中发送广播 @Override
protected void onMessage(Context context, Intent intent) {
Log.i(TAG, "Received message");
String message = getString(R.string.gcm_message);
displayMessage(context, message);
context.sendBroadcast(new Intent("GCM_MESSAGE"));
// notifies user
generateNotification(context, message);
}
作为替代案例,您可以在Manifest,Activity或ForeGround Service中注册broadcastReceiver