在Android上使用GCM推送通知

don*_*ias 6 android push-notification google-cloud-messaging

我正在尝试在我的Android应用程序上实现推送通知.所以没有比Googles Developers页面更好的起点了.

我想在这里学习这个教程:GCM演示应用程序.教程建议使用通过SDK Manager提供的示例代码.执行此操作并尝试发送推送通知后,当应用程序运行时,我会在屏幕上看到正在写入新推送已到达.

但是,当应用程序在后台或未运行时,我没有得到推送通知.如果我打开应用程序,屏幕上会再次显示消息.但我从来没有通过弹出和声音通知的形式.

我手动必须在android中执行此操作吗?我认为它与iOS类似,平台负责向您显示通知.

我有什么想法可以实现它吗?

Dee*_*ala 5

但我从来没有通过弹出和声音通知的形式.

触发通知时,声音可以编程到代码中.用这样的话说.

Notification notification = new Notification(icon, tickerText, when);
notification.sound = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION);
Run Code Online (Sandbox Code Playgroud)

但是,当应用程序在后台或未运行时,我没有得到推送通知

我手动必须在android中执行此操作吗?我认为它与iOS类似,平台负责向您显示通知.

您的应用程序始终会发送GCM数据(推送通知).您如何处理这些数据取决于您.GCM意向服务负责向您提供数据,就是这样.您需要使用通知服务向用户显示相应的通知.

这种方法有优点/缺点.当您收到推送通知时,应用程序代码将在Android上运行,而iPhone上并非如此.您还可以灵活地根据推送通知的类型进行更新或通知用户.

在应用启动时向您的设备注册发件人ID,您应该按预期收到通知.所有推送通知都将在protected void onMessage(Context context, Intent intent)您选择的GCMIntentService上传递给此方法.


Yah*_*r10 3

尝试取消注册并重新注册您的设备。在DemoActivity.java中放入

final String regId = GCMRegistrar.getRegistrationId(this);
        GCMRegistrar.unregister(this);
Run Code Online (Sandbox Code Playgroud)

然后, 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();
    }
}
Run Code Online (Sandbox Code Playgroud)

然后放

<application
           android:name=".DemoApplication"
        android:icon="@drawable/ic_launcher"
        android:label="@string/app_name" > 
Run Code Online (Sandbox Code Playgroud)

在 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);
    }
Run Code Online (Sandbox Code Playgroud)

作为替代情况,您可以在清单、活动或前台服务中注册广播接收器