0

我知道这些方法已被弃用,但由于新的 GCM API 似乎有问题,我将恢复使用这些方法,直到谷歌推出稳定版本。

我们在清单中声明这个接收器。

        <receiver
        android:name="com.google.android.gcm.GCMBroadcastReceiver"
        android:permission="com.google.android.c2dm.permission.SEND" >
        <intent-filter>

            <!-- Receives the actual messages. -->
            <action android:name="com.google.android.c2dm.intent.RECEIVE" />
            <!-- Receives the registration id. -->
            <action android:name="com.google.android.c2dm.intent.REGISTRATION" />
            <category android:name="com.myApp" />
        </intent-filter>
    </receiver>

  <service android:name=".GCMIntentService" />

我们在 GCMIntentService 类中有 onMessage() 方法。

   @Override
protected void onMessage(Context context, Intent intent) 
{
    Log.i(TAG, "Received message");
    String message = intent.getExtras().getString("msg");
}

1. 但是,在收到消息后,永远不会调用此方法。为什么 ?

此外,我遵循的示例使用以下内容。

registerReceiver(mHandleMessageReceiver, new IntentFilter("intent_filter_string"));

与以下类相关联。

private final BroadcastReceiver mHandleMessageReceiver = new BroadcastReceiver() 
   {
    @Override
    public void onReceive(Context context, Intent intent) 
   {
        String newMessage = intent.getExtras().getString("data");
    }
 };

在 onPause 中未注册。

  1. 为什么我们需要创建这个广播接收器?
  2. 我们不能在清单中这样做吗?
  3. GCMIntentService 类中的 onMessage() 不是已经涵盖了这一点吗?
  4. Pending Intent String 起什么作用?

答案表示赞赏。

4

2 回答 2

1

为什么我们需要创建这个广播接收器?

In some cases you might be interested in updating the UI if the app is running.
So you create a broadcast receiver at runtime and unregister it when the app
goes into background.

我们不能在清单中这样做吗?

Yes, you can do it in manifest too.

GCMIntentService 类中的 onMessage() 不是已经涵盖了这一点吗?

GCMIntentService extends GCMBaseIntentService. So any message coming from gcm,
will first be recieved in the onMessage of the GCMIntentService.
Its upto you to decide how you handle the message.
You can create a notification or send a broadcast to your custom broadcast
receivers and update the UI when the app is running.

Pending Intent 起什么作用?

根据文档

A PendingIntent itself is simply a reference to a token maintained by the system 
describing the original data used to retrieve it. This means that, even if its
owning application's process is killed, the PendingIntent itself will remain
usable from other processes that have been given it.
于 2013-08-26T09:05:06.557 回答
0

您是否已将您的应用程序/设备组合注册到您的 GCM 项目?您必须首先在 onRegistered 方法中执行此操作。您是否添加了所有必要的权限?谷歌说你不必在 android 4.0 以上添加自定义权限,但我的应用没有它们就无法工作。如果您正在寻找使用 GCM 的更简单方法,我推荐 apiOmat: http: //www.apiomat.com 我知道它的后端即服务。但是,如果您的应用程序很小,则无需支付任何费用,并且使用起来会容易得多。

于 2013-08-26T08:11:43.850 回答