Warning: file_get_contents(/data/phpspider/zhask/data//catemap/3/android/225.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Android 如何设置每5秒重复报警以显示消息_Android_Alarmmanager - Fatal编程技术网

Android 如何设置每5秒重复报警以显示消息

Android 如何设置每5秒重复报警以显示消息,android,alarmmanager,Android,Alarmmanager,下面是我在oncreate方法内的应用程序类中的代码:但我看不到来自我的应用程序的任何消息。有人能帮我做这件事吗 意向alarmIntent=新意向此,AlarmReceiver.class; PendingEvent=PendingEvent.getBroadcastthis,0,alarmIntent,0; 公共空星武器{ manager=AlarmManagergetSystemServiceContext.ALARM\u服务; 整数区间=5000; manager.setRepeatin

下面是我在oncreate方法内的应用程序类中的代码:但我看不到来自我的应用程序的任何消息。有人能帮我做这件事吗

意向alarmIntent=新意向此,AlarmReceiver.class; PendingEvent=PendingEvent.getBroadcastthis,0,alarmIntent,0; 公共空星武器{ manager=AlarmManagergetSystemServiceContext.ALARM\u服务; 整数区间=5000; manager.setRepeatingAlarmManager.RTC_唤醒,System.currentTimeMillis,interval,pendingent; Toast.makeTextthis、报警集、Toast.LENGTH\u SHORT.show; } 在广播接收器类中,我有以下代码

公共类AlarmReceiver扩展了BroadcastReceiver{ @凌驾 ReceiveContext arg0、意图arg1上的公共无效{ //对于定期任务,我们只显示一条消息 Toast.makeTextarg0,我正在跑步,Toast.LENGTH\u SHORT.show; } } 编辑答案:

使用setInexactRepeating而不是setRepeating。setRepeating仅采用设定的间隔,最短的间隔为十五分钟。setInexactRepeating是将重复间隔设置为1000毫秒或5000毫秒的唯一方法

更改:

 manager.setRepeating(AlarmManager.RTC_WAKEUP, System.currentTimeMillis(), interval, pendingIntent);


如果您没有获得所需的精确5秒延迟,则需要使用处理程序。任何类型的5秒延迟的警报都不能正常工作,因为从Android 5.x开始,基本上所有重复的警报都不精确,以节省电池寿命

我已修改您的代码以使用处理程序:

星形臂

public void startAlarm() {
    final Handler h = new Handler();
    final int delay = 5000; //milliseconds

    h.postDelayed(new Runnable(){
        public void run(){
            //do something

            Intent alarmIntent = new Intent(getApplicationContext(), AlarmReceiver.class);
            sendBroadcast(alarmIntent);

            h.postDelayed(this, delay);
        }
    }, delay);
}

该报警方法将与您当前的BroadcastReceiver一起工作,并实际延迟5秒

@Nick Friskel,谢谢你的回复。但是我声明了AlarmManger,但没有包括它。我的问题是使用AlarmManager在logcat上每5秒获取一次消息,而不使用service类。我用定时器和处理器做了,但没有效果。我照你说的做了,但没有任何改变:。祝酒词有没有显示出来?通过在控制台中键入“adb shell dumpster alarm”检查您的警报,并搜索您的包名,然后让我知道警报是否在那里。谢谢,它工作正常。在升级Android studio之后,我遇到了麻烦。现在我检查过了,工作正常
public void startAlarm() {
    final Handler h = new Handler();
    final int delay = 5000; //milliseconds

    h.postDelayed(new Runnable(){
        public void run(){
            //do something

            Intent alarmIntent = new Intent(getApplicationContext(), AlarmReceiver.class);
            sendBroadcast(alarmIntent);

            h.postDelayed(this, delay);
        }
    }, delay);
}