应用终止后发布通知

时间:2018-08-13 15:19:43

标签: android android-service android-notifications

大约一周以来,我一直在尝试为日历日计划应用发出通知。只要该应用程序处于“最近任务”中,通知就可以正常工作,但是将其删除后根本无法正常工作。

最初,我尝试使用简单的AlarmManager来调用BroadcastReciever,但我知道它不提供此功能,所以我决定学习并使用Service。

起初,我尝试了IntentService,现在尝试了Service。我没有任何日志错误,所以我猜测我对该系统的了解存在一个根本性的问题,因此,如果您能启发我,我将不胜感激。

这是我的班级整体处理通知的地方:

package com.example.android.calendar.Helpers;

import android.app.AlarmManager;
import android.app.IntentService;
import android.app.Notification;
import android.app.NotificationChannel;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.app.Service;
import android.content.Context;
import android.content.Intent;
import android.os.IBinder;
import android.support.annotation.Nullable;
import android.support.v4.app.NotificationCompat;
import com.example.android.calendar.Model.Event;
import com.example.android.calendar.R;
import java.util.Calendar;
import java.util.HashMap;
import java.util.UUID;

public class NotificationService extends Service {

    private static Context mContext;
    private static final String NOTIFICATION_CHANNEL_ID = "notificationChannelId";
    private static final String NOTIFICATION_CHANNEL_NAME = "eventsNotificationChannel";

    public static final String EX_ID = "extraId";
    public static final String ACTION_START_SERVICE = "startService";
    public static final String ACTION_NOTIFY_ON_TIME = "notifyOnTime";

    private static HashMap<UUID, Notification> notifications = new HashMap<>();
    public static int mCounter = 0;

    public NotificationService(){
        super();
    }

    @Override
    public void onCreate(){
        super.onCreate();
        createNotificationChannel(this.getApplicationContext());
    }

    @Override
    public int onStartCommand(final Intent intent, int flags, int startId){
        super.onStartCommand(intent, flags, startId);

        new Thread(new Runnable() {
            @Override
            public void run() {
                if(intent.getAction() == ACTION_NOTIFY_ON_TIME){
                    UUID id = (UUID) intent.getSerializableExtra(EX_ID);
                    Notification notification = notifications.get(id);
                    NotificationManager notificationManager = (NotificationManager) mContext.getSystemService(Context.NOTIFICATION_SERVICE);
                    notificationManager.notify(mCounter++, notification);
                }
                try{
                    Thread.sleep(1000);
                } catch (InterruptedException e){
                    e.printStackTrace();
                }
            }
        }).start();

        return IntentService.START_REDELIVER_INTENT;
    }

    @Nullable
    @Override
    public IBinder onBind(Intent intent) {
        return null;
    }

    public void createNotificationChannel(Context context){
        mContext = context;
        NotificationManager mNM = (NotificationManager) mContext.getSystemService(NOTIFICATION_SERVICE);
        NotificationChannel notificationChannel = new NotificationChannel(NOTIFICATION_CHANNEL_ID,
                NOTIFICATION_CHANNEL_NAME, NotificationManager.IMPORTANCE_HIGH);
        notificationChannel.enableVibration(true);
        notificationChannel.setVibrationPattern(new long[]{100, 200, 300, 400, 500, 400, 300, 200, 100});
        notificationChannel.enableLights(true);
        mNM.createNotificationChannel(notificationChannel);
    }

    public void createNotification(int minutesBefore, Event event){
        NotificationCompat.Builder mBuilder = new NotificationCompat.Builder(mContext, NOTIFICATION_CHANNEL_ID).
                setSmallIcon(R.drawable.ic_launcher_foreground).setContentTitle(event.getLabel()).
                setContentText(event.getComment()).setAutoCancel(true);

        // If an event is edited, remove existing notification
        if(notifications.get(event.getId()) != null)
            notifications.remove(event.getId());

        Calendar mCalendar = Calendar.getInstance();
        notifications.put(event.getId(), mBuilder.build());
        mCalendar.setTime(event.getTime());
        mCalendar.set(Calendar.SECOND, 0);

        Intent intent = new Intent(mContext, NotificationService.class);
        intent.putExtra(EX_ID, event.getId());
        intent.setAction(ACTION_NOTIFY_ON_TIME);
        PendingIntent notificationIntent = PendingIntent.getService(mContext, (int)System.currentTimeMillis(),
                intent, PendingIntent.FLAG_CANCEL_CURRENT);
        long triggerInMills = mCalendar.getTimeInMillis() - Calendar.getInstance().getTimeInMillis();
        AlarmManager alarmManager = (AlarmManager) mContext.getSystemService(Context.ALARM_SERVICE);
        alarmManager.setExact(AlarmManager.RTC, System.currentTimeMillis() + triggerInMills, notificationIntent);
    }

    public void cancelNotification(Event event, PendingIntent notificationIntent){
        AlarmManager alarmManager = (AlarmManager) mContext.getSystemService(Context.ALARM_SERVICE);
        alarmManager.cancel(notificationIntent);
        notifications.remove(event.getId());
    }
}

可以肯定这是不相关的,但是在这里我创建并启动该服务:

notificationService = new NotificationService();
Intent startServiceIntent = new Intent(getActivity(), NotificationService.class);
startServiceIntent.setAction(NotificationService.ACTION_START_SERVICE);
getActivity().startService(startServiceIntent);

1 个答案:

答案 0 :(得分:1)

在Android Oreo中,background execution limits have changed,因此,如果您在> = Api 26上进行测试,这就是为什么您可能会遇到此行为的原因。我会先检查一下。

除了后台执行限制外,您似乎正在启动一项服务,以使用Notification发送AlarmManager

为什么不只是安排AlarmManager来启动该服务,并通过服务中的NotificationManager#notify (int id, Notification notification)使用Notification通过As per the documentation发布NotificationManager

此外,由于这是一项已启动的服务,因此您可能会或可能不会在启动该服务的同一Fragment或Activity中调用stopService。

enter image description here,您应该对已启动的服务执行此操作,或者在完成服务工作时致电服务中的stopSelf()。我希望这可以为您的问题提供一些见识。

祝你好运,编码愉快!