onHandleIntent в GcmIntentService не вызывается

Я следил за демонстрацией GCM от разработчиков Android. Получил следующую ситуацию. Мой OnHandleIntent внутри GCMIntentService не вызывается. Кто-нибудь может помочь?

package com.xyz.ads;


import com.google.android.gms.gcm.GoogleCloudMessaging;

import android.app.IntentService;
import android.content.Intent;
import android.os.Bundle;
import android.util.Log;

public class GcmIntentService extends IntentService {
    public GcmIntentService() {
        super("GcmIntentService");
        //super.onCreate();
        //super.onHandleIntent();
    }

    public void onCreate() {
        super.onCreate();

    }

    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {
        super.onStartCommand(intent, startId, startId);
        Log.i("LocalService", "Received start id " + startId + ": " + intent);

        return START_STICKY;
    }
    public static final String TAG = "GCM Demo";

    @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);

        // Release the wake lock provided by the WakefulBroadcastReceiver.
        GcmBroadcastReceiver.completeWakefulIntent(intent);
    }
}

Вот мой BroadCastReceiver

package com.xyz.ads;

import android.app.Activity;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.support.v4.content.WakefulBroadcastReceiver;


public class GcmBroadcastReceiver extends WakefulBroadcastReceiver {

    @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());

        startWakefulService(context, (intent.setComponent(comp)));
        setResultCode(Activity.RESULT_OK);
    }
}

и мой манифест

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.xyz.ads"
    android:versionCode="1"
    android:versionName="1.0" >

    <uses-sdk
        android:minSdkVersion="11"
        android:targetSdkVersion="19" />
    <!-- For Google Cloud Services -->
    <uses-permission android:name="com.google.android.c2dm.permission.RECEIVE" />
    <uses-permission android:name="android.permission.INTERNET" />
    <uses-permission android:name="android.permission.GET_ACCOUNTS" />
    <uses-permission android:name="android.permission.WAKE_LOCK" />

    <!-- location -->
    <uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />

    <permission
        android:name="com.xyz.ads.permission.C2D_MESSAGE"
        android:protectionLevel="signature" />
    <uses-permission android:name="com.xyz.ads.permission.C2D_MESSAGE" />
    <application
        android:name="ADS"
        android:allowBackup="true"
        android:debuggable="true"
        android:icon="@drawable/ic_launcher"
        android:theme="@style/Theme.AppCompat"
        >
        <meta-data
            android:name="com.google.android.gms.version"
            android:value="@integer/google_play_services_version" />

        <activity
            android:name=".ui.DummyActivity"
            android:label="@string/title_activity_dummy" >
        </activity>


        <!-- For Google Cloud Services -->
        <receiver
            android:name=".GcmBroadcastReceiver"
            android:permission="com.google.android.c2dm.permission.SEND" >
            <intent-filter>
                <action android:name="com.google.android.c2dm.intent.RECEIVE" />
                <category android:name="com.xyz.ads" />
            </intent-filter>
        </receiver>

        <service
            android:name="GcmIntentService"
            android:enabled="true" >
        </service>

    </application>

</manifest>

onReceive внутри получателя вызывается и конструктор службы намерений.


person lintu    schedule 07.01.2014    source источник
comment
Решается ли это... я столкнулся с той же проблемой... пожалуйста, поделитесь решением...   -  person somenath mukhopadhyay    schedule 22.08.2014


Ответы (3)


Я бы сказал, что вам не хватает точки в названии класса.

<service
    android:name=".GcmIntentService"
    android:enabled="true" >
</service>

Точка обозначает имя пакета вашего приложения.
Допустим, имя вашего пакета com.example.app. Тогда запись .GcmIntentService имеет тот же эффект, что и запись com.example.app.GcmIntentService.

person gabriel14    schedule 01.07.2014

попробуй это

<receiver
            android:name="com.xyz.ads.GcmBroadcastReceiver"
            android:permission="com.google.android.c2dm.permission.SEND" >
            <intent-filter>

                <!-- Receives the actual messages. -->
                <action android:name="com.google.android.c2dm.intent.RECEIVE" />

                <category android:name="com.xyz.ads" />
            </intent-filter>
        </receiver>

 <service
            android:name="com.xyz.ads.GcmIntentService"
            android:enabled="true" >
        </service>
person Mourice    schedule 07.01.2014

У меня была та же проблема, но это был не код (все было похоже на ваше, как говорится в документе: http://developer.android.com/google/gcm/client.html), это был проект Eclipse.

Проверьте это, если это может вам помочь:

Проведите рефакторинг и переместите службу из одного пакета в другой. Проверьте, не изменяет ли пакет androidManifest.xml автоматически. Если нет, то у вас та же проблема, что и у меня.

Я решил это, удалив класс ServiceIntent и создав новый (с тем же содержимым). Похоже, мой сервис был отключен или что-то в этом роде, и на время я понял, что сошел с ума, сравнив код.

С новым, если вы проверите еще раз, вы увидите изменение пакета в androidmanifest.xml и вашу службу, вызываемую GcmBroadcastReceiver!! :)

person Ignacio Rubio    schedule 01.05.2014