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

我试图在每天早上 5 点设置一个触发器,以使手机为 USER_PRESENT 广播做好准备,但是一旦服务启动,触发器就会关闭。服务 (PAService) 通过使用stopServicestartService打开主活动来关闭和打开。此代码在模拟器中运行良好,但不适用于实际的 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;

    }


}


Qyouu
浏览 141回答 1
1回答

临摹微笑

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 LINEcalendar.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);}
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Java