为了账号安全,请及时绑定邮箱和手机立即绑定

服务启动后触发警报而不是设置时间

服务启动后触发警报而不是设置时间

Qyouu 2021-10-20 15:01:09
我试图在每天早上 5 点设置一个触发器,以使手机为 USER_PRESENT 广播做好准备,但是一旦服务启动,触发器就会关闭。服务 (PAService) 通过使用stopService和startService打开主活动来关闭和打开。此代码在模拟器中运行良好,但不适用于实际的 Android 手机。public class PAService extends Service {static boolean is_ready_to_speak = false;PendingIntent pendingIntent;public PAService() {}public class ScreenReceiver extends BroadcastReceiver {    @Override    public void onReceive(Context context, Intent intent) {        if(is_ready_to_speak)        {            PASpeak paspeak = new PASpeak();            paspeak.sayit(getApplicationContext(),"You're using your phone for the first time this morning");           is_ready_to_speak = false;        }    }}public static class AlarmReceiver extends BroadcastReceiver {    public AlarmReceiver()    {        Log.d("AlarmReceiver func called","alarm receiver func called");    }    @Override    public void onReceive(Context context, Intent intent) {        Log.d("RECEIVED BROADCAST", "Sometype of ALARM Broadcast received");        PASpeak paspeak = new PASpeak();        paspeak.sayit(context.getApplicationContext(),"ALARM ALARM ALARM");        is_ready_to_speak = true;    }}
查看完整描述

1 回答

?
临摹微笑

TA贡献1982条经验 获得超2个赞

manager.setRepeating(AlarmManager.RTC_WAKEUP,

            calendar.getTimeInMillis(), AlarmManager.INTERVAL_DAY, // for repeating

            // in every 24

            // hours

            pendingIntent);

的2nd parameter,触发时间触发报警器立即如果calendar.getTimeInMillis()是在过去。所以发生的事情是你可能在晚上 7 点打开应用程序。您希望闹钟在第二天早上 5 点响起,但您calendar.getTimeInMillis()会在同一天早上 5 点响起 。所以你需要为此添加一个检查:


Calendar calendar = Calendar.getInstance();

// calendar.setTimeInMillis(System.currentTimeMillis()); // YOU DON'T NEED THIS LINE

calendar.set(Calendar.HOUR_OF_DAY, 5);

calendar.set(Calendar.MINUTE, 0);

calendar.set(Calendar.SECOND, 0);


Calendar current = Calendar.getInstance();


int curTime = current.getTimeInMillis();

int alarmTime = calendar.getTimeInMillis();


if (alarmTime >= curTime){

   manager.setRepeating(AlarmManager.RTC_WAKEUP,

        alarmTime, AlarmManager.INTERVAL_DAY, // for repeating

        // in every 24

        // hours

        pendingIntent);

}else{

   calendar.add(Calendar.DAY_OF_MONTH, 1);

   int alarmTime = calendar.getTimeInMillis();

   manager.setRepeating(AlarmManager.RTC_WAKEUP,

        alarmTime, AlarmManager.INTERVAL_DAY, // for repeating

        // in every 24

        // hours

        pendingIntent);

}


查看完整回答
反对 回复 2021-10-20
  • 1 回答
  • 0 关注
  • 140 浏览

添加回答

举报

0/150
提交
取消
意见反馈 帮助中心 APP下载
官方微信