简体   繁体   English

AlarmManager 有时会延迟触发,或者根本不会触发

[英]AlarmManager sometimes fires with a delay, or not at all

I have a simple AlarmManager app which sends me an e-mail every 30 minutes, but it is not working properly.我有一个简单的 AlarmManager 应用程序,它每 30 分钟向我发送一封电子邮件,但它无法正常工作。 Sometimes it delays and sometimes it doesn't send anything at all.有时它会延迟,有时它根本不发送任何东西。 Can someone explain why this is happening?有人可以解释为什么会这样吗?

MainActivity class:主要活动 class:

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    AlarmManager alarmMgr = (AlarmManager) getSystemService(Context.ALARM_SERVICE);
    Intent intent = new Intent(this, MyAlarmReceiver.class);
    PendingIntent pendingIntent = PendingIntent.getBroadcast(this, 0, intent, 0);
    alarmMgr.setInexactRepeating(AlarmManager.ELAPSED_REALTIME_WAKEUP, SystemClock.elapsedRealtime() + AlarmManager.INTERVAL_HOUR, AlarmManager.INTERVAL_HALF_HOUR, pendingIntent);
}

MyAlarmReceiver onReceive method MyAlarmReceiver onReceive 方法

private FusedLocationProviderClient fusedLocationClient;

@Override
public void onReceive(Context context, Intent intent) {
    Toast.makeText(context, "Alarm went off", Toast.LENGTH_SHORT).show();
    fusedLocationClient = LocationServices.getFusedLocationProviderClient(context);
    fusedLocationClient.getLastLocation().addOnSuccessListener(new OnSuccessListener<Location>() {
        @Override
        public void onSuccess(Location location) {
            if(location != null)
            {
                SimpleDateFormat formatter = new SimpleDateFormat("dd.MM.yyyy HH:mm:ss");
                Date date = new Date();
                sendMail(location.getLongitude()+"", location.getLatitude()+"", formatter.format(date));
            }
        }
    });
}

Change the alarmMgr.setInexactRepeating for alarmMgr.setRepeating as you are using inexact alarms:当您使用不精确的警报时,将alarmMgr.setInexactRepeating更改为alarmMgr.setRepeating

These alarms are more power-efficient than the strict recurrences traditionally supplied by setRepeating(int, long, long, PendingIntent), since the system can adjust alarms' delivery times to cause them to fire simultaneously, avoiding waking the device from sleep more than necessary.这些警报比传统上由 setRepeating(int, long, long, PendingIntent) 提供的严格重复更省电,因为系统可以调整警报的传递时间以使它们同时触发,避免不必要地从睡眠中唤醒设备.

Your alarm's first trigger will not be before the requested time, but it might not occur for almost a full interval after that time.您的警报的第一次触发不会在请求的时间之前,但它可能不会在该时间之后的几乎整个间隔内发生。

In your class code.在您的 class 代码中。

public class Alarm extends BroadcastReceiver 
{    
@Override
public void onReceive(Context context, Intent intent) 
{   
    PowerManager pm = (PowerManager) context.getSystemService(Context.POWER_SERVICE);
    PowerManager.WakeLock wl = pm.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, "");
    wl.acquire();

    // Put here YOUR code.

   // wl.release();
}

public void setAlarm(Context context)
{
    AlarmManager am =( AlarmManager)context.getSystemService(Context.ALARM_SERVICE);
    Intent i = new Intent(context, Alarm.class);
    PendingIntent pi = PendingIntent.getBroadcast(context, 0, i, 0);
    am.setRepeating(AlarmManager.RTC_WAKEUP, System.currentTimeMillis(), 1000 * 60 * 
 10, pi); // Millisec * Second * Minute
}

public void cancelAlarm(Context context)
{
    Intent intent = new Intent(context, Alarm.class);
    PendingIntent sender = PendingIntent.getBroadcast(context, 0, intent, 0);
    AlarmManager alarmManager = (AlarmManager) 
 context.getSystemService(Context.ALARM_SERVICE);
    alarmManager.cancel(sender);
 }
}

then set alarm service

public class YourService extends Service
{
Alarm alarm = new Alarm();
public void onCreate()
{
    super.onCreate();       
}

@Override
public int onStartCommand(Intent intent, int flags, int startId) 
{
    alarm.setAlarm(this);
    return START_STICKY;
}

@Override        
public void onStart(Intent intent, int startId)
{
    alarm.setAlarm(this);
}

@Override
public IBinder onBind(Intent intent) 
{
    return null;
 }
}

documentation [ https://developer.android.com/training/scheduling/alarms]文档 [ https://developer.android.com/training/scheduling/alarms]

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM