如何将意图传递给广播接收器并启动android服务

mec1mxoz  于 2021-06-29  发布在  Java
关注(0)|答案(0)|浏览(238)

java目标api 30,最小api 19
我有由前台服务中的处理程序线程创建的警报。我有基于用户输入在处理程序中设置的警报。我可以确认传递给警报器的时间是正确的。以下是报警对象类:

public class StartAlarmObject  {
    private String name;
    private Context context;
    private int index;
    private int day;
    private long time;
    private NotificationManagerCompat notificationManager;
    private ArrayList<RestrictionObject> restrictions = new ArrayList<>();
    private ReadAndWriteRestrictions readAndWriteRestrictions = new ReadAndWriteRestrictions();
    private AlarmManager alarmManager;
    private PendingIntent pendingIntent;

    public StartAlarmObject (String name, Context context, int index, int day, long time)
    {
        this.name = name;
        this.context = context;
        this.index = index;
        this.day = day;
        this.time = time;
    }

    public void startAlarm() {
        System.out.println("starting alarm/alarm setting...");
        alarmManager = (AlarmManager) context.getSystemService(Context.ALARM_SERVICE);

        Intent intent = new Intent(context, AlertReceiver.class);
        intent.putExtra("index", index);
        pendingIntent = PendingIntent.getBroadcast(context, (index * 100) + (day * 10), intent, 0);

        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
                alarmManager.setExactAndAllowWhileIdle(AlarmManager.RTC_WAKEUP, time, pendingIntent);
                System.out.println("setting exact and allowing while idle");
            } else {
                alarmManager.setExact(AlarmManager.RTC_WAKEUP, time, pendingIntent);
                System.out.println("setting exact");
                }
        } else {
            alarmManager.set(AlarmManager.RTC_WAKEUP, time, pendingIntent);
            System.out.println("just setting");
        }
    }

    public void cancelAlarm()
    {
        if (alarmManager!= null) {
            alarmManager.cancel(pendingIntent);
        }
    }

    public String getName() {
        return name;
    }
}

我得到了我期望的“setting exact and allowing while idle”println语句,但我从未看到广播接收器类的任何React,我将意图传递给:

package com.example.gotimejavaversion;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;

public class AlertReceiver extends BroadcastReceiver {
    @Override
    public void onReceive(Context context, Intent intent) {
        System.out.println("alert received");
        Intent serviceIntent = new Intent(App.getContext(), TheRestrictor.class);
        serviceIntent.putExtra("caller", "alarm");
        System.out.println("The alarm reached the receiver");
        context.stopService(serviceIntent);
        context.startService(serviceIntent);
    }
}

当警报响起时,我需要什么才能到达广播接收器或重新启动服务?希望我错过了一些简单的东西。
谢谢您!

暂无答案!

目前还没有任何答案,快来回答吧!

相关问题