在 Android 5 秒后触发警报

Make alarm trigger after 5 sec in Android

我想在 android 的 5 秒后触发警报,但它不起作用。它在 1 分钟而不是 5 秒后触发。为什么?

@Override
public void onReceive(Context context, Intent intent) {
    PowerManager powerManager=(PowerManager)context.getSystemService(Context.POWER_SERVICE);

    PowerManager.WakeLock wakeLock= powerManager.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK,"Power Manager");

    wakeLock.acquire();
    showNotification("Wake up. Alarm Triggered",context);
}
public void showNotification(String message ,Context context)
{
    Toast.makeText(context, message, Toast.LENGTH_SHORT).show();
}

public void setAlarm(Context context)
{
    Calendar calendar= Calendar.getInstance();
    AlarmManager alarmManager=(AlarmManager) context.getSystemService(Context.ALARM_SERVICE);

    Intent intent=new Intent(context, Alarm.class);
    PendingIntent pendingIntent= PendingIntent.getBroadcast(context,0,intent,0);

    alarmManager.setRepeating(AlarmManager.RTC, calendar.getTimeInMillis(),5000,pendingIntent);

}

}

引用自the docs

Note: Beginning with API 19 (KITKAT) alarm delivery is inexact: the OS will shift alarms in order to minimize wakeups and battery use. There are new APIs to support applications which need strict delivery guarantees; see setWindow(int, long, long, PendingIntent) and setExact(int, long, PendingIntent).

如果您想在您的应用处于 运行 时执行某些操作(我认为间隔 5 秒),请使用 Handler:

Note: The Alarm Manager is intended for cases where you want to have your application code run at a specific time, even if your application is not currently running. For normal timing operations (ticks, timeouts, etc) it is easier and much more efficient to use Handler.

特别是,postDelayedsendMessageDelayed 可能是您申请的正确选择(但是,由于您没有告诉我们您的主要 objective,这只是猜测)。

Praviin,如果你想在 5 秒后触发某些东西,只需使用如下处理程序即可。您不需要将 alarmManager 代码放入处理程序中。

final Handler handler = new Handler();
                        handler.postDelayed(new Runnable() {
                            @Override
                            public void run() {

                                //The code here will run after 5 sec, do what you want

                            }
                        }, 5*1000);