Alarm manager don't work after some time

前端 未结 2 572
闹比i
闹比i 2020-12-20 05:09

This is my code. It works correctly, but after some time (about 1 hour) it doesn\'t work. Whats wrong? Thanks in advance.



        
2条回答
  •  生来不讨喜
    2020-12-20 06:06

    This is working code. It wakes CPU every 10 minutes and shows notification.

    Add to Manifest.xml:

    ...
    
    ...
    
    ...
    

    Code:

    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, "YOUR TAG");
             wl.acquire();
    
             // Put here YOUR code.
             Toast.makeText(context, "Alarm !!!!!!!!!!", Toast.LENGTH_LONG).show(); // For example
    
             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);
         }
    }
    

提交回复
热议问题