即使所有消息都成功从服务器发送,某些设备也不会收到 GCM 推送

2024-04-16

我们正在开发一个使用 GCM 的应用程序。它在大多数手机上运行良好,但是,我们有两部手机(galaxy note 2 和 Galaxy s plus)收不到消息。或者可能只是广播接收器没有被调用。

服务器端推送:

$data = array(
        'data' => array('message' => $messageData),
        'delay_while_idle' => false,
        'type' => 'New',
        'flag' => 1,
        'registration_ids' => $registrationIdsArray
    );

    $ch = curl_init();

    curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
    curl_setopt($ch, CURLOPT_URL, "https://android.googleapis.com/gcm/send");
    curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 1);
    curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, 1);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
    curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($data));

    $response = curl_exec($ch);
    curl_close($ch);

发送推送时的响应接收者:

{
   "multicast_id":4735518740307255391,
   "success":4,
   "failure":0,
   "canonical_ids":0,
   "results":[
      {
         "message_id":"0:1390919813717906%2d15d04af9fd7ecd"
      },
      {
         "message_id":"0:1390919813717694%2d15d04af9fd7ecd"
      },
      {
         "message_id":"0:1390919813717290%2d15d04af9fd7ecd"
      },
      {
         "message_id":"0:1390919813717907%2d15d04af9fd7ecd"
      }
   ]
}

清单.xml

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.innocreate.app"
    android:versionCode="2"
    android:versionName="0.1.1" >

    <uses-sdk
        android:minSdkVersion="9"
        android:targetSdkVersion="17" />

    <uses-permission android:name="android.permission.INTERNET" />
    <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
    <uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
    <uses-permission android:name="android.permission.GET_ACCOUNTS" />
    <uses-permission android:name="com.google.android.c2dm.permission.RECEIVE" />

    <permission android:name="com.innocreate.app.permission.C2D_MESSAGE"
        android:protectionLevel="signature" />
    <uses-permission android:name="com.innocreate.app.permission.C2D_MESSAGE" />
    <uses-permission android:name="android.permission.VIBRATE"/>
    <uses-permission android:name="android.permission.WAKE_LOCK"/>

    <application
        android:allowBackup="true"
        android:icon="@drawable/ic_launcher"
        android:label="@string/app_name"
        android:logo="@drawable/menu"
        android:theme="@style/Theme.Styled" >
        <meta-data
            android:name="AA_DB_VERSION"
            android:value="3" />
        <meta-data android:name="com.google.android.gms.version"
           android:value="@integer/google_play_services_version" />

        <activity
            android:name="com.innocreate.app.NavigationParent"
            android:label="@string/app_name"
            android:screenOrientation="portrait"
            android:theme="@style/Theme.Styled"
            android:launchMode="singleTop" >
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />

                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
        <activity android:name="com.innocreate.app.DibsPaymentActivity" >
        </activity>

        <service
            android:name="com.octo.android.robospice.GsonSpringAndroidSpiceService"
            android:exported="false" />

        <receiver
            android:name="com.innocreate.app.gcm.GCMBroadcastReceiver"
            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="com.app.muf_appen" />
            </intent-filter>
        </receiver>
        <service android:name="com.innocreate.app.gcm.GCMIntentService" />
        <service android:name="com.innocreate.app.gcm.GCMRegistrationService" />

    </application>

</manifest>

GcmIntentService.java

public class GCMIntentService extends IntentService {

    public GCMIntentService(String name) {
        super(name);
        // TODO Auto-generated constructor stub
    }

    public static final int NOTIFICATION_ID = 1;
    private NotificationManager mNotificationManager;
    NotificationCompat.Builder builder;

    public GCMIntentService() {
        super("GCMIntentService");
    }

    @Override
    protected void onHandleIntent(Intent intent) {
        Bundle extras = intent.getExtras();
        GoogleCloudMessaging gcm = GoogleCloudMessaging.getInstance(this);
        // The getMessageType() intent parameter must be the intent you received
        // in your BroadcastReceiver.
        String messageType = gcm.getMessageType(intent); 

        if (!extras.isEmpty()) {  // has effect of unparcelling Bundle
            /*
             * Filter messages based on message type. Since it is likely that GCM
             * will be extended in the future with new message types, just ignore
             * any message types you're not interested in, or that you don't
             * recognize.
             */
            if (GoogleCloudMessaging.
                    MESSAGE_TYPE_SEND_ERROR.equals(messageType)) {
//                sendNotification("Send error: " + extras.toString());
            } else if (GoogleCloudMessaging.
                    MESSAGE_TYPE_DELETED.equals(messageType)) {
//                sendNotification("Deleted messages on server: " +
//                        extras.toString());
            // If it's a regular GCM message, do some work.
            } else if (GoogleCloudMessaging.
                    MESSAGE_TYPE_MESSAGE.equals(messageType)) {

//                Log.i(TAG, "Completed work @ " + SystemClock.elapsedRealtime());
                // Post notification of received message.
                sendNotification(extras.getString("message"));
//                Log.i(TAG, "Received: " + extras.toString());
            }
        }
        // Release the wake lock provided by the WakefulBroadcastReceiver.
//        GCMBroadcastReceiver.completeWakefulIntent(intent);
    }

    // Put the message into a notification and post it.
    // This is just one simple example of what you might choose to do with
    // a GCM message.
    private void sendNotification(String msg) {
        mNotificationManager = (NotificationManager)
                this.getSystemService(Context.NOTIFICATION_SERVICE);

        PendingIntent contentIntent = PendingIntent.getActivity(this, 0,
                new Intent(this, NavigationParent.class), PendingIntent.FLAG_UPDATE_CURRENT);

        Uri soundUri = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION);

        long[] vibration = {0, 200, 50, 200};
        Builder mBuilder =
                new NotificationCompat.Builder(this)
        .setSmallIcon(R.drawable.ic_launcher)
        .setContentTitle("MUF - Nyhet")
        .setContentText(msg)
        .setVibrate(vibration);

        mBuilder.setContentIntent(contentIntent);

        Notification notification =  mBuilder.build();
        notification.flags |= Notification.FLAG_AUTO_CANCEL;


        mNotificationManager.notify(NOTIFICATION_ID, notification);
    }

}

GcmBroadcastreceiver.java

public class GCMBroadcastReceiver extends BroadcastReceiver {

    @Override
    public void onReceive(Context context, Intent intent) {
        // Explicitly specify that GcmIntentService will handle the intent.
        ComponentName comp = new ComponentName(context.getPackageName(),
                GCMIntentService.class.getName());

        // Start the service, keeping the device awake while it is launching.
        SharedPreferences p = context.getSharedPreferences(
                GCMRegistrationService.class.getSimpleName(),
                Context.MODE_PRIVATE);
        if (p.getBoolean("ENABLE_GCM", true)) {
            context.startService(intent.setComponent(comp));
        }
        setResultCode(Activity.RESULT_OK);
    }

}

GcmRegistrationService.java

public class GCMRegistrationService extends Service {

    public static final String REGISTRATION_ID_EXTRA = "REGISTRATION_ID_EXTRA";
    public static final String BACKOFF_TIME_EXTRA = "BACKOFF_TIME_EXTRA";
    public static final String PROPERTY_REG_ID = "PROPERTY_REG_ID";
    public static final String PROPERTY_APP_VERSION = "PROPERTY_APP_VERSION";
    private static final String BACKEND_REGISTRATION_URL = "MY URL (REMOVED)";
    private static final String SENDER_ID = "MY SENDER ID (REMOVED)";



    private String mRegistrationId;
    private GoogleCloudMessaging mGCM;

    private Handler mHandler = new Handler();

    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {
        // TODO Auto-generated method stub

        // try request
        Thread registerThread = new Thread(new Runnable() {

            @Override
            public void run() {
                long currentBackoffTime = 1000;
                int iterationCounter = 0; // maximum number of iterations 11 => 4095 seconds
                while(!tryRegistration() && iterationCounter < 11) {
                    try {
                        Thread.sleep(currentBackoffTime);
                    } catch (InterruptedException e) {
                        // TODO Auto-generated catch block
                        e.printStackTrace();
                    }
                    currentBackoffTime *= 2;
                    iterationCounter++;
                }
                stopSelf();
            }
        });

        registerThread.start();

        return super.onStartCommand(intent, flags, startId);
    }



    @Override
    public IBinder onBind(Intent intent) {
        // TODO Auto-generated method stub
        return null;
    }


    private boolean tryRegistration() {
        try {
            if (mGCM == null) {
                mGCM = GoogleCloudMessaging.getInstance(this);
            }
            mRegistrationId = mGCM.register(SENDER_ID);

            // You should send the registration ID to your server over HTTP,
            // so it can use GCM/HTTP or CCS to send messages to your app.
            // The request to your server should be authenticated if your app
            // is using accounts.
            sendRegistrationIdToBackend();

            // For this demo: we don't need to send it because the device
            // will send upstream messages to a server that echo back the
            // message using the 'from' address in the message.

            // Persist the regID - no need to register again.
            storeRegistrationId(this, mRegistrationId);
        } catch (IOException ex) {
            // If there is an error, don't just keep trying to register.
            // Require the user to click a button again, or perform
            // exponential back-off.
            return false;
        }
        return true;
    }

    private void sendRegistrationIdToBackend() throws IOException {
        RestMethod rm = new RestMethod(BACKEND_REGISTRATION_URL);
        rm.appendQueryParameter("gcm", mRegistrationId);
        rm.appendQueryParameter("from", "1");
        rm.execute(Type.POST);
        if(rm.mResponseCode >= 299) {
            throw new IOException();
        }
    }

    /**
     * Stores the registration ID and app versionCode in the application's
     * {@code SharedPreferences}.
     *
     * @param context application's context.
     * @param regId registration ID
     */
    private void storeRegistrationId(Context context, String regId) {
        final SharedPreferences prefs = getGCMPreferences(context);
        int appVersion = getAppVersion(context);
//      Log.i(TAG, "Saving regId on app version " + appVersion);
        SharedPreferences.Editor editor = prefs.edit();
        editor.putString(PROPERTY_REG_ID, regId);
        editor.putInt(PROPERTY_APP_VERSION, appVersion);
        editor.commit();
    }


     /**
     * @return Application's version code from the {@code PackageManager}.
     */
    private static int getAppVersion(Context context) {
        try {
            PackageInfo packageInfo = context.getPackageManager()
                    .getPackageInfo(context.getPackageName(), 0);
            return packageInfo.versionCode;
        } catch (NameNotFoundException e) {
            // should never happen
            throw new RuntimeException("Could not get package name: " + e);
        }
    }


    private SharedPreferences getGCMPreferences(Context context) {
        // This sample app persists the registration ID in shared preferences, but
        // how you store the regID in your app is up to you.
        return getSharedPreferences(GCMRegistrationService.class.getSimpleName(),
                Context.MODE_PRIVATE);
    }



}

我们几乎尝试了所有方法,但似乎都不起作用。 Galaxy Note 2 运行 4.3 版本,无需 Google 帐户且可通过 Wi-Fi 运行。 Galaxy s plus 运行 android 2.3.5,并在 wifi 上使用 google 帐户。

我们了解到某些使用 wifi 的设备无法接收 GCM,因此我们尝试重新启动手机,但没有任何反应。

预先感谢您提供任何线索或答案!

亲切的问候 约翰·里施 西蒙·埃弗森


您的广播接收器中的类别是错误的:

<receiver
    android:name="com.innocreate.app.gcm.GCMBroadcastReceiver"
    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="com.app.muf_appen" />
    </intent-filter>
</receiver>

它应该是您的应用程序的包名称,com.innocreate.app, 代替com.app.muf_appen。 这通常只会在较旧的 Android 版本中引起问题。

本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

即使所有消息都成功从服务器发送,某些设备也不会收到 GCM 推送 的相关文章

  • Android:如何从输入流创建 9patch 图像?

    我使用下面的代码实例化 9patch 图像并将其设置为按钮的背景 下图显示了不理想的结果 InputStream MyClass class getResourceAsStream images btn default normal 9 p
  • IntentService、Service 或 AsyncTask

    实现这一点的最佳方法是什么 我有一个 Android 应用程序 它将使用我的 python 服务器来允许两部手机之间进行轮流通信 回合意味着他们在一轮开始之前不能互相交谈 一旦他们发送一条消息 他们就不能发送另一条消息 直到对方做出回应 然
  • 删除 json 对象字符串中的“\”

    如何删除下面字符串中的特殊字符 String x message content toom recipients id 1000001865 room subject room 我使用了 x replaceAll 但它不起作用 您必须转义正
  • Android浏览器上的Web应用程序宽度问题

    所以到目前为止我只在 Android 浏览器上遇到过这个问题 基本上我的网站几乎一直运行良好 而且我还没有在 Dolphin Opera 或 Skyfire 上看到这个问题 但偶尔当我从手机主屏幕之一上的书签重新打开 Android 浏览器
  • Notification.Builder 中 setGroup() 的用途是什么?

    我对目标的理解有些困难setGroup http developer android com reference android app Notification Builder html setGroup java lang String
  • Mesibo 通话 UI 未更新

    我正在尝试更改 Mesibo Call UI 的配置 但它并没有改变 我尝试如下 MesiboCallConfig mesiboCallConfig new MesiboCallConfig mesiboCallConfig backgro
  • Android:拍照后调用裁剪活动

    我在解析拍摄照片的 uri 来裁剪活动时遇到问题 在我的应用程序中 用户可以拍摄一张照片或从图库中选择一张照片 然后裁剪并上传 一切听起来都很简单 从图库中选择时 图库应用程序会返回所选照片的 uri 如下所示 content media
  • 有没有办法替代Android中的标准Log?

    有没有办法以某种方式拦截对 android 中标准 Log 的调用并执行其他操作 在桌面 Java 中 人们通常会得到一些记录器 因此有多种方法可以安装不同的日志处理程序 实现 但是 Android似乎对Log有静态调用 我找不到任何有关替
  • 当编辑文本获得焦点时更改边框颜色

    我想知道当编辑文本聚焦时如何更改它的边框颜色 目前它看起来像这样 我尝试过在SDK中检查源图片 但我无法理解它 我也尝试过使用xml 但无法仅更改边框颜色 如果我找到源图片 我可以在 Photoshop 中编辑以更改颜色 有什么关于如何执行
  • opencv人脸检测示例

    当我在设备上运行应用程序时 应用程序崩溃并显示以下按摩 java lang UnsatisfiedLinkError 无法加载 detector based tracker findLibrary 返回 null 我正在使用 OpenCV
  • Kotlin 和惯用的书写方式,基于可变值“如果不为空,则...”

    假设我们有这样的代码 class QuickExample fun function argument SomeOtherClass if argument mutableProperty null doSomething argument
  • Android 中带有透明背景的 ImageButton [重复]

    这个问题在这里已经有答案了 我已经按照这篇文章在android中制作ImageButton 安卓图像按钮 https stackoverflow com questions 2283444 android image button 图像出现
  • 取消通知

    我使用Onesignal推送通知 需要取消所有onPause和onResume的通知 NotificationManager notificationManager NotificationManager getApplicationCon
  • Proguard - 找不到任何超级类

    我收到此错误 Unexpected error while performing partial evaluation Class org apache log4j chainsaw Main Method
  • 使用 AndroidX ExifInterface 从图像中检索 GPS EXIF 数据?

    我的目标是 Android 13 并使用新的照片选择器 https developer android com training data storage shared photopicker检索图像 例如 val photoPicker
  • 在 Android ADT Eclipse 插件中滚动布局编辑器

    有谁知道当布局编辑器的内容溢出一个 屏幕 时如何滚动这些内容 我说的是在设计时使用 ADT 布局编辑器 而不是在物理设备上运行时滚动 效果很好 关闭 Android 布局编辑器中的剪辑 切换剪辑 按钮位于 Android 布局编辑器的右上角
  • 在上下文操作模式下选择时,ListView 项目不会在视觉上“突出显示”

    我关注了 Android 官方网站创建上下文操作菜单的教程 http developer android com guide topics ui menus html CAB 使用下面的代码 当我长按我的 ListView 项目之一时 它确
  • Android中绑定适配器有什么用?

    我一直在阅读有关Android中绑定适配器的文章 但我似乎不明白它 何时使用绑定适配器 有人可以用一个简单的例子来解释它吗 我读过的一篇文章在主活动中有一个绑定适配器 绑定适配器有一个参数 toastMessage 显然 只要 toastM
  • 在DialogFragment中,onCreate应该做什么?

    我目前正在摆弄 DialogFragment 以学习使用它 我假设相比onCreateView onCreate 可以这样做 public void onCreate Bundle savedInstanceState super onCr
  • 进程被杀死后不会调用 onActivityResult

    我有一个主要活动 Main 和另一个活动 Sub 由 Main 调用 startActivityForResult new Intent this SubActivity class 25 当我在 Sub 时 我终止该进程 使用任务管理器或

随机推荐