调用了GCMINTENTSERVICE onRegistered但是onMessage不是

时间:2015-01-25 15:27:45

标签: android

大家好(请原谅我的英语,因为我说西班牙语)。我是Android的新手,我在使用谷歌云消息传递的项目中工作。

但是我们遇到了一个问题,在类GCMINTENTSERVICE中从未调用onMessage方法,我们尝试使用此处找到的不同解决方案,但没有运气。我们注意到,在debbuging中,onRegistered的方法被称为ok并返回和google ID。

这是我的代码 包名= com.snappy

public class GCMReceiver extends GCMBroadcastReceiver {

    @Override
    protected String getGCMIntentServiceClassName(Context context) {
        return "com.snappy.GCMIntentService";
    }

GCMINTENTSERVICE

public class GCMIntentService extends GCMBaseIntentService {

    private static int mNotificationCounter = 1;
    public final static String PUSH = "com.snappy.GCMIntentService.PUSH";
    private static final Intent mPushBroadcast = new Intent(PUSH);

    public GCMIntentService() {
        super(Const.PUSH_SENDER_ID);
    }

    private final String TAG = "=== GCMIntentService ===";

    /**
     * Method called on device registered
     **/
    @Override
    protected void onRegistered(Context context, String registrationId) {

        if (!registrationId.equals(null)) {
            savePushTokenAsync(registrationId, Const.ONLINE, context);
        }
    }

    /**
     * Method called on device unregistered
     * */
    @Override
    protected void onUnregistered(Context context, String registrationId) {

        if (!registrationId.equals(null)) {
            removePushTokenAsync(context);
        }
    }

    /**
     * Method called on Receiving a new message
     * */
    @Override
    protected void onMessage(Context context, Intent intent) {
        Bundle pushExtras = intent.getExtras();
        String pushMessage = intent.getStringExtra(Const.PUSH_MESSAGE);
        String pushFromName = intent.getStringExtra(Const.PUSH_FROM_NAME);
        try {
            boolean appIsInForeground = new SpikaApp.ForegroundCheckAsync()
                    .execute(getApplicationContext()).get();

            boolean screenLocked = ((KeyguardManager) getSystemService(Context.KEYGUARD_SERVICE))
                    .inKeyguardRestrictedInputMode();


            if (appIsInForeground && !screenLocked) {
                mPushBroadcast.replaceExtras(pushExtras);
                LocalBroadcastManager.getInstance(this).sendBroadcast(mPushBroadcast);
                generateNotification(this, pushMessage, pushFromName, pushExtras);
            } else {
                triggerNotification(this, pushMessage, pushFromName, pushExtras);
                generateNotification(this, pushMessage, pushFromName, pushExtras);
            }
        } catch (InterruptedException e) {
            e.printStackTrace();
        } catch (ExecutionException e) {
            e.printStackTrace();
        }


    }

    /**
     * Method called on Error
     * */
    @Override
    protected void onError(Context arg0, String errorId) {
        Logger.error(TAG, "Received error: " + errorId);
    }

    @Override
    protected boolean onRecoverableError(Context context, String errorId) {
        return super.onRecoverableError(context, errorId);
    }

    @SuppressWarnings("deprecation")
    public void triggerNotification(Context context, String message,
            String fromName, Bundle pushExtras) {

        if (fromName != null) {
            final NotificationManager notificationManager = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);

            Notification notification = new Notification(
                    R.drawable.icon_notification, message,
                    System.currentTimeMillis());

            notification.number = mNotificationCounter + 1;
            mNotificationCounter = mNotificationCounter + 1;

            Intent intent = new Intent(this, SplashScreenActivity.class);
            intent.replaceExtras(pushExtras);
            intent.putExtra(Const.PUSH_INTENT, true);
            intent.setAction(Long.toString(System.currentTimeMillis()));
            intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK
                    | Intent.FLAG_FROM_BACKGROUND
                    | Intent.FLAG_ACTIVITY_TASK_ON_HOME);

            PendingIntent pendingIntent = PendingIntent.getActivity(this,
                    notification.number, intent,
                    PendingIntent.FLAG_UPDATE_CURRENT);

            notification.setLatestEventInfo(this,
                    context.getString(R.string.app_name), message,
                    pendingIntent);

            notification.flags |= Notification.FLAG_AUTO_CANCEL;
            notification.defaults |= Notification.DEFAULT_VIBRATE;
            notification.defaults |= Notification.DEFAULT_SOUND;
            notification.defaults |= Notification.DEFAULT_LIGHTS;
            String notificationId = Double.toString(Math.random());
            notificationManager.notify(notificationId, 0, notification);

        }
    }

    /**
     * Issues a notification to inform the user that server has sent a message.
     */
    private void generateNotification(Context context, String message,
            String fromName, Bundle pushExtras) {

        // Open a new activity called GCMMessageView
                Intent intento = new Intent(this, SplashScreenActivity.class);
                intento.replaceExtras(pushExtras);
                // Pass data to the new activity
                intento.putExtra(Const.PUSH_INTENT, true);

                // Starts the activity on notification click
                PendingIntent pIntent = PendingIntent.getActivity(this, 0, intento,
                                PendingIntent.FLAG_UPDATE_CURRENT);

                // Create the notification with a notification builder
                        Notification notification = new Notification.Builder(this)
                                .setSmallIcon(R.drawable.icon_notification)
                                .setWhen(System.currentTimeMillis())
                                .setContentTitle("Android GCM Tutorial")
                                .setContentText(message).setContentIntent(pIntent)
                                .getNotification();

                // Remove the notification on click
                        notification.flags |= Notification.FLAG_AUTO_CANCEL;
                        NotificationManager manager = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
                        manager.notify(R.string.app_name, notification);
                        {
                            // Wake Android Device when notification received
                            PowerManager pm = (PowerManager) context
                                    .getSystemService(Context.POWER_SERVICE);
                            final PowerManager.WakeLock mWakelock = pm.newWakeLock(
                                    PowerManager.FULL_WAKE_LOCK
                                            | PowerManager.ACQUIRE_CAUSES_WAKEUP, "GCM_PUSH");
                            mWakelock.acquire();
                            // Timer before putting Android Device to sleep mode.
                            Timer timer = new Timer();
                            TimerTask task = new TimerTask() {
                                public void run() {
                                    mWakelock.release();
                                }
                            };
                            timer.schedule(task, 5000);
                        }
    }

    private void savePushTokenAsync (String pushToken, String onlineStatus, Context context) {
        new SpikaAsyncTask<Void, Void, Boolean>(new SavePushToken(pushToken, onlineStatus), new SavePushTokenListener(pushToken), context, false).execute();
    }

    private class SavePushToken implements Command<Boolean>{

        String pushToken;
        String onlineStatus;

        public SavePushToken (String pushToken, String onlineStatus) {
            this.pushToken = pushToken;
            this.onlineStatus = onlineStatus;
        }

        @Override
        public Boolean execute() throws JSONException, IOException,
                SpikaException, IllegalStateException, SpikaForbiddenException {

            /* set new androidToken and onlineStatus */
            UsersManagement.getLoginUser().setOnlineStatus(onlineStatus);
            SpikaApp.getPreferences().setUserEmail(UsersManagement.getLoginUser().getEmail());
            SpikaApp.getPreferences().setUserPushToken(pushToken);
            return CouchDB.updateUser(UsersManagement.getLoginUser());
        }
    }

    private class SavePushTokenListener implements ResultListener<Boolean>{

        String currentPushToken;

        public SavePushTokenListener (String currentPushToken) {
            this.currentPushToken = currentPushToken;
        }

        @Override
        public void onResultsSucceded(Boolean result) {
            if (result) {
            } else {
                SpikaApp.getPreferences().setUserPushToken(currentPushToken);
            }
        }

        @Override
        public void onResultsFail() {
        }

    }

    private void removePushTokenAsync (Context context) {
        SpikaApp.getPreferences().setUserPushToken("");
        if (UsersManagement.getLoginUser() != null) {
            CouchDB.unregisterPushTokenAsync(UsersManagement.getLoginUser().getId(), new RemovePushTokenListener(), context, false);
        }
    }

    private class RemovePushTokenListener implements ResultListener<String> {
        @Override
        public void onResultsSucceded(String result) {
            if (result != null && result.contains("OK")) {
                SpikaApp.getPreferences().setUserEmail("");
                SpikaApp.getPreferences().setUserPassword("");
            }
        }
        @Override
        public void onResultsFail() {
        }
    }
}

清单

<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.snappy"
    android:versionCode="14"
    android:versionName="1.31" >

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

    <uses-feature
        android:name="android.hardware.camera"
        android:required="false" />
    <uses-feature
        android:name="android.hardware.camera.autofocus"
        android:required="false" />

    <uses-permission android:name="android.permission.INTERNET" />
    <uses-permission android:name="android.permission.CAMERA" />
    <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
    <uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />
    <uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
    <uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" />
    <uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
    <uses-permission android:name="android.permission.ACCESS_LOCATION_EXTRA_COMMANDS" />
    <uses-permission android:name="android.permission.ACCESS_MOCK_LOCATION" />
    <uses-permission android:name="android.permission.GET_TASKS" />
    <uses-permission android:name="android.permission.RECORD_AUDIO" />
    <uses-permission android:name="android.permission.VIBRATE" />
    <uses-permission android:name="android.permission.READ_LOGS" />
    <uses-permission android:name="android.permission.CLEAR_CACHE" />
    <uses-permission android:name="com.google.android.providers.gsf.permission.READ_GSERVICES" />



    <permission
        android:name="com.snappy.permission.C2D_MESSAGE"
        android:protectionLevel="signature" />

    <uses-permission android:name="com.snappy.permission.C2D_MESSAGE" />

    <permission
        android:name="com.snappy.permission.MAPS_RECEIVE"
        android:protectionLevel="signature" />

    <uses-permission android:name="com.snappy.permission.MAPS_RECEIVE" />

    <!-- App receives GCM messages. -->
    <uses-permission android:name="com.google.android.c2dm.permission.RECEIVE" />
    <!-- GCM requires a Google account. -->
    <uses-permission android:name="android.permission.GET_ACCOUNTS" />
    <!-- Keeps the processor from sleeping when a message is received. -->
    <uses-permission android:name="android.permission.WAKE_LOCK" />

    <application
        android:name=".SpikaApp"
        android:allowBackup="true"
        android:icon="@drawable/icon"
        android:label="@string/app_name"
        android:largeHeap="true"
        android:theme="@style/android:Theme.Light.NoTitleBar" >
        <meta-data
            android:name="com.google.android.maps.v2.API_KEY"
            android:value="AIzaSyBH1T5IsUDDeA0EDwRByyK58D9xn3OjcGs" />
        <meta-data
            android:name="com.google.android.gms.version"
            android:value="@integer/google_play_services_version" />

        <activity
            android:name="com.snappy.SplashScreenActivity"
            android:label="@string/app_name"
            android:screenOrientation="portrait" >
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />
                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
            <intent-filter>
                <data
                    android:host="user"
                    android:scheme="spikademo" />

                <action android:name="android.intent.action.VIEW" />

                <category android:name="android.intent.category.DEFAULT" />
                <category android:name="android.intent.category.BROWSABLE" />
            </intent-filter>
            <intent-filter>
                <data
                    android:host="group"
                    android:scheme="spikademo" />

                <action android:name="android.intent.action.VIEW" />

                <category android:name="android.intent.category.DEFAULT" />
                <category android:name="android.intent.category.BROWSABLE" />
            </intent-filter>
        </activity>
        <activity
            android:name="com.snappy.SignInActivity"
            android:label="@string/app_name"
            android:launchMode="singleTop"
            android:screenOrientation="portrait" >
        </activity>
        <activity
            android:name="com.snappy.WallActivity"
            android:launchMode="singleTask"
            android:screenOrientation="portrait"
            android:windowSoftInputMode="adjustResize" >
        </activity>
        <activity
            android:name="com.snappy.extendables.SideBarActivity"
            android:screenOrientation="portrait" >
        </activity>
        <activity
            android:name="com.snappy.extendables.HookUpActivity"
            android:screenOrientation="portrait" >
        </activity>
        <activity
            android:name="com.snappy.extendables.HookUpFragmentActivity"
            android:screenOrientation="portrait" >
        </activity>
        <activity
            android:name="com.snappy.PasscodeActivity"
            android:launchMode="singleTop"
            android:screenOrientation="portrait" >
        </activity>
        <activity
            android:name="com.snappy.UsersActivity"
            android:launchMode="singleTop"
            android:screenOrientation="portrait" >
        </activity>
        <activity
            android:name="com.snappy.GroupsActivity"
            android:launchMode="singleTop"
            android:screenOrientation="portrait" >
        </activity>
        <activity
            android:name="com.snappy.PhotoActivity"
            android:launchMode="singleTask"
            android:screenOrientation="portrait" >
        </activity>
        <activity
            android:name="com.snappy.CreateGroupActivity"
            android:launchMode="singleTask"
            android:screenOrientation="portrait" >
        </activity>
        <activity
            android:name="com.snappy.CameraCropActivity"
            android:screenOrientation="portrait" >
        </activity>
        <activity
            android:name="com.snappy.MyProfileActivity"
            android:launchMode="singleTask"
            android:screenOrientation="portrait" >
        </activity>
        <activity
            android:name="com.snappy.UserProfileActivity"
            android:launchMode="singleTop"
            android:screenOrientation="portrait" >
        </activity>
        <activity
            android:name="com.snappy.GroupProfileActivity"
            android:launchMode="singleTop"
            android:screenOrientation="portrait" >
        </activity>
        <activity
            android:name="com.snappy.MembersActivity"
            android:launchMode="singleTop"
            android:screenOrientation="portrait" >
        </activity>
        <activity
            android:name="com.snappy.LocationActivity"
            android:launchMode="singleTask"
            android:screenOrientation="portrait" >
        </activity>
        <activity
            android:name="com.snappy.RecordingActivity"
            android:launchMode="singleTask"
            android:screenOrientation="portrait" >
        </activity>
        <activity
            android:name="com.snappy.VoiceActivity"
            android:launchMode="singleTask"
            android:screenOrientation="portrait" >
        </activity>
        <activity
            android:name="com.snappy.InformationActivity"
            android:launchMode="singleTask"
            android:screenOrientation="portrait" >
        </activity>
        <activity
            android:name="com.snappy.SettingsActivity"
            android:launchMode="singleTask"
            android:screenOrientation="portrait" >
        </activity>
        <activity
            android:name="com.snappy.VideoActivity"
            android:configChanges="keyboardHidden|orientation|screenSize"
            android:launchMode="singleTask"
            android:screenOrientation="portrait" >
        </activity>
        <activity
            android:name="com.snappy.RecordingVideoActivity"
            android:configChanges="keyboardHidden|orientation|screenSize"
            android:screenOrientation="portrait" >
        </activity>
        <activity
            android:name="com.snappy.RecentActivityActivity"
            android:launchMode="singleTask"
            android:screenOrientation="portrait"
            android:windowSoftInputMode="stateAlwaysHidden" >
        </activity>
        <activity
            android:name="com.snappy.dialog.Tutorial"
            android:screenOrientation="portrait"
            android:theme="@style/TransparentDialogTheme" >
        </activity>
        <activity
            android:name="com.snappy.ServersListActivity"
            android:label="@string/app_name"
            android:screenOrientation="portrait"
            android:windowSoftInputMode="adjustPan" >
        </activity>

        <receiver
            android:name=".GCMReceiver"
            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.snappy" />
            </intent-filter>
        </receiver>
        <service android:name=".GCMIntentService" android:enabled="true"/>
        <receiver android:name="com.snappy.management.ConnectionChangeReceiver" >
            <intent-filter>
                <action android:name="android.net.conn.CONNECTIVITY_CHANGE" />
                <action android:name="android.net.ConnectivityManager.CONNECTIVITY_ACTION" />
            </intent-filter>
        </receiver>
        <receiver android:name="com.snappy.management.LogoutReceiver" >
            <intent-filter>
                <action android:name=".management.LogoutReceiver.LOGOUT" >
                </action>
            </intent-filter>
        </receiver>
    </application>

</manifest>

活动中的Google注册方法

private String registerOnGCM() {

        if (Const.PUSH_SENDER_ID == null || Const.PUSH_SENDER_ID.length() == 0) {
            Toast.makeText(this.getApplicationContext(),
                    R.string.recentactivity_nosender_id, Toast.LENGTH_LONG).show();
            return null;
        }

        GCMRegistrar.checkDevice(getApplicationContext());
        GCMRegistrar.checkManifest(getApplicationContext());

         if (GCMRegistrar.isRegistered(this))
         {
             Log.d("Info Registration ID", GCMRegistrar.getRegistrationId(this));
         }

        String registrationId = GCMRegistrar.getRegistrationId(getApplicationContext());
        System.out.println("registration ID is " + registrationId);
       // GCMRegistrar.register(getApplicationContext(), Const.PUSH_SENDER_ID);

        if (registrationId.equals("") || registrationId.equals(null)) {
            System.out.println("Ingresando a registrar ID " + registrationId);
            GCMRegistrar.register(getApplicationContext(), Const.PUSH_SENDER_ID);
            Log.d("Luego de tratar de registrar", GCMRegistrar.getRegistrationId(this));
            System.out.println("Get Reg ID: " + GCMRegistrar.getRegistrationId(this));

        } else {
            // // Device is already registered on GCM
            if (GCMRegistrar.isRegisteredOnServer(getApplicationContext())) {
                Log.d("info", "already registered as" + registrationId);
            } else {

            }
        }
        return GCMRegistrar.getRegistrationId(getApplicationContext());
    }

请帮忙! 最好的问候

0 个答案:

没有答案