关闭应用程序时,AlarmManager不起作用

时间:2019-09-29 12:34:35

标签: java android

public class background_alarm extends BroadcastReceiver {

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

         //CODE EVERY X MINUTES
} }

主要活动

public class MainActivity extends AppCompatActivity {



AlarmManager alarmManager;
PendingIntent pendingIntent;

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

   AlarmManager alarmManager = (AlarmManager) getSystemService(ALARM_SERVICE);

    Intent intent = new Intent(this, background_alarm.class);
    intent.putExtra("UserNumber", UserLogged.getNumeroTelefono());

    PendingIntent pendingIntent = PendingIntent.getBroadcast(this, REQUEST_CODE, intent, PendingIntent.FLAG_UPDATE_CURRENT);


    Long intervalMillis = 1L * 60L * 1000L; //IT'S ONLY FOR TEST 1 MINUTES
    Long triggerAtMillis = System.currentTimeMillis() + intervalMillis;

    alarmManager.setRepeating(AlarmManager.RTC_WAKEUP, triggerAtMillis, intervalMillis, pendingIntent);

}

关闭应用程序后,此功能将不再起作用...有没有可以运行的解决方案?注意:当应用程序正在运行这项工作

2 个答案:

答案 0 :(得分:0)

您的设备可能进入了DOZE模式。 在背景警报类https://developer.android.com/training/monitoring-device-state/doze-standby

中使用setAndAllowWhileIdle()或setExactAndAllowWhileIdle()方法

答案 1 :(得分:0)

对于这种特定情况,建议您使用前台服务。

从文档中:

  

已经运行前台服务(带有相关通知)的应用不受打ze的限制。

https://developer.android.com/guide/components/services