gpt4 book ai didi

android - AlarmManager 触发后如何调用 AlarmManager 方法?

转载 作者:搜寻专家 更新时间:2023-11-01 08:32:30 25 4
gpt4 key购买 nike

我想在每次触发 AlarmManager 时额外更改 Intent。这可能吗,我如何在 AlarmManager 触发后立即调用它?

代码:

public void startCollector(){
final int LOOP_REQUEST_CODE = 4;
Intent i = new Intent(getApplicationContext(), DataCollector.class);
PendingIntent sender = PendingIntent.getBroadcast(getApplicationContext(),LOOP_REQUEST_CODE,i,PendingIntent.FLAG_NO_CREATE);
long firstTime = SystemClock.elapsedRealtime();
firstTime += 3*1000;
AlarmManager am = (AlarmManager)getSystemService(ALARM_SERVICE);
//TO CHANGE INTENT EXTRAS DO NOT REMOVE.
if(sender != null){
am.cancel(sender);
}
if(getLocation() != null) {
i.putExtra("JLocation", getLocation());
}
i.putExtra("JLocation",getLocation());
sender = PendingIntent.getBroadcast(getApplicationContext(),LOOP_REQUEST_CODE,i,PendingIntent.FLAG_CANCEL_CURRENT);
am.setRepeating(AlarmManager.ELAPSED_REALTIME_WAKEUP, firstTime, 100000, sender);
}

最佳答案

我建议您使用精确的警报而不是使用 setRepeating() 并在每次触发时重新安排。

(setRepeating() 是不准确的,无论如何都不适用于 Doze)

例如:

Intent intent = new Intent(this, AlarmReceiver.class);
PendingIntent pendingIntent = PendingIntent.getBroadcast(this, 0, intent, 0);

AlarmManager am = (AlarmManager) getSystemService(ALARM_SERVICE);

// if you would like to fire the next alarm very precisely
// put this value in the Intent and use it in your receiver
// to calculate the next time for the alarm
long fireAt = SystemClock.elapsedRealtime() + 5000;

if(Build.VERSION.SDK_INT >= 23) {
am.setExactAndAllowWhileIdle(AlarmManager.ELAPSED_REALTIME_WAKEUP,
fireAt, pendingIntent);
} else if(Build.VERSION.SDK_INT >= 19) {
am.setExact(AlarmManager.ELAPSED_REALTIME_WAKEUP, fireAt, pendingIntent);
} else {
am.set(AlarmManager.ELAPSED_REALTIME_WAKEUP, fireAt, pendingIntent);
}

在你的接收器中:

@Override
public void onReceive(Context context, Intent intent) {

// change the Intent as you wish
intent.putExtra("anExtra", "aValue");
// or create a new one
//Intent newIntent = new Intent(context, this.getClass());

PendingIntent pendingIntent = PendingIntent
.getBroadcast(context, 0, intent, 0);

AlarmManager am = (AlarmManager) context.getSystemService(ALARM_SERVICE);

long fireAt = SystemClock.elapsedRealtime() + 5000;

if(Build.VERSION.SDK_INT >= 23) {
am.setExactAndAllowWhileIdle(AlarmManager.ELAPSED_REALTIME_WAKEUP,
fireAt, pendingIntent);
} else if(Build.VERSION.SDK_INT >= 19) {
am.setExact(AlarmManager.ELAPSED_REALTIME_WAKEUP, fireAt, pendingIntent);
} else {
am.set(AlarmManager.ELAPSED_REALTIME_WAKEUP, fireAt, pendingIntent);
}
}

关于android - AlarmManager 触发后如何调用 AlarmManager 方法?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39507905/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com