应用程序后台运行时需要推送通知

时间:2016-10-19 16:56:44

标签: java android push-notification google-cloud-messaging

我使用广播接收器和关联的IntentService实现了基于GCM的推送通知服务。当应用程序完全由用户关闭或在前面运行时,推送工作正常。但是,当我对应用程序进行后台处理,即它已暂停并且在后台时,直到应用程序被预设或恢复后才会收到推送通知。有什么可以解决这个问题?

我正在使用以下

意图服务:

public class GCMIntentService extends IntentService
{


    private static final int NOTIFICATION_NEW_MESSAGE = 0;

    public GCMIntentService()
    {
        super(GCMIntentService.class.getSimpleName());
    }

    @Override
    protected void onHandleIntent(Intent intent)
    {
        Bundle extras = intent.getExtras();
        GoogleCloudMessaging gcm = GoogleCloudMessaging.getInstance(this);

        Log.d("Push Opened","Push Opened");
        String messageType = gcm.getMessageType(intent);

        if (!extras.isEmpty())
        {
            if (!GoogleCloudMessaging.MESSAGE_TYPE_MESSAGE.equals(messageType))
            {
                return;
            }

            int newUnreadCount = MessagingController.getInstance().getUnreadCount() + 1;
            MessagingController.getInstance().prepareStream();
            MessagingController.getInstance().setUnreadCount(newUnreadCount);

            final boolean isUserAuthenticated = !TextUtils.isEmpty(AuthenticationController.getInstance().getAuthToken());

            if (isUserAuthenticated)
            {
                new Handler(Looper.getMainLooper()).post(new Runnable()
                {
                    @Override
                    public void run()
                    {
                        App.from(GCMIntentService.this).fire(MessagingEvent.NEW_MESSAGE);
                    }
                });
            }
            else
            {
                displayNotification(newUnreadCount + " New Message" + (newUnreadCount > 1 ? "s" : ""), newUnreadCount);
            }
        }
        GCMBroadcastReceiver.completeWakefulIntent(intent);
    }



    private void displayNotification(CharSequence message, int eventCount)
    {
        SharedPreferences preferences = PreferenceManager.getDefaultSharedPreferences(getApplicationContext());
        boolean shouldDisplayMessages = preferences.getBoolean("notifications_new_message", true);

        if (!shouldDisplayMessages)
        {
            return;
        }

        NotificationManager notificationManager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);

        Intent openMessagingScreen = new Intent(this, LandingActivity.class);
        openMessagingScreen.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TASK);
        openMessagingScreen.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
        openMessagingScreen.putExtra("analytics_push",1);

        preferences.edit().putBoolean(MessagingFragment.PREF_MESSAGE_WAITING, true).apply();

        PendingIntent notificationAction = PendingIntent.getActivity(this, 0, openMessagingScreen, PendingIntent.FLAG_CANCEL_CURRENT);

        NotificationCompat.Builder notificationBuilder = new NotificationCompat.Builder(this)
                .setSmallIcon(R.drawable.ic_notification)
                .setContentTitle(getString(R.string.app_name))
                .setStyle(new NotificationCompat.BigTextStyle().bigText(message))
                .setContentText(message)
                .setAutoCancel(true)
                .setContentIntent(notificationAction)
                .setNumber(eventCount);

        Notification notification = notificationBuilder.build();
        notification.defaults |= Notification.DEFAULT_ALL;

        try
        {
            notificationManager.notify(NOTIFICATION_NEW_MESSAGE, notification);
        }
        catch (SecurityException ex)
        {
            // This is required due to a bug in android
            // http://stackoverflow.com/questions/13602190/java-lang-securityexception-requires-vibrate-permission-on-jelly-bean-4-2
            Log.e("xxxxxx", ex.getLocalizedMessage());
        }

    }
}

广播接收器:

public class GCMBroadcastReceiver extends WakefulBroadcastReceiver
{
    @Override
    public void onReceive(Context context, Intent intent)
    {
        ComponentName messageProcessingService = new ComponentName(context.getPackageName(), GCMIntentService.class.getName());
        context.startService(intent.setComponent(messageProcessingService));
        startWakefulService(context,(intent.setComponent(messageProcessingService)));
        setResultCode(Activity.RESULT_OK);
    }

}

权限:

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

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

GCM的清单声明:

<receiver android:name=".core.push.receiver.GCMBroadcastReceiver" android:exported="true" 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.SEND" />
                <category android:name="com.ppfa.stdtestca" />
            </intent-filter>
        </receiver>
        <service android:name=".core.push.service.GCMIntentService" />

0 个答案:

没有答案