In Android, I have an activity which schedules a task(showing a notification) to repeat for every 10 or 15 mins even if the app is closed or killed.
I have tried to schedule it using AlarmManager
with alarmManager.setExact
, alarmManager.set
and alarmManager.setRepeating
and none of them fired the event at exact time. There is a lot of delay in firing the event. Sometimes it fire at exact time and sometimes there will be delay. The delay ranges from 15 mins to several hours.
I saw the android docs saying that AlarmManager will delay the events starting from Lollipop 5.1. I have tried it with Handlers
as well as TimerTask
and Timer
, but they get killed immediately when app is killed.
Is there any alternate solution which runs for short interval times and runs in the background too.
答案 0 :(得分:0)
您需要的是Service和CountDownTimer。
启动服务并将倒数计时器初始化10到15分钟,如计时器完成时重新初始化同一计时器并在计时器的onFinish方法中显示通知。
这样,即使应用关闭,您也会显示通知。
答案 1 :(得分:0)
更新并运作示例:
这个为特定的日期和时间设置和警报。然后每3分钟重复一次。
MainActivity:
public class MainActivity extends AppCompatActivity {
private AlarmManager alarmManager;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Calendar calendar = Calendar.getInstance();
calendar.setTimeInMillis(System.currentTimeMillis());
calendar.set(Calendar.HOUR_OF_DAY, 17);
calendar.set(Calendar.MINUTE, 03);
calendar.set(Calendar.SECOND, 0);
calendar.set(Calendar.MILLISECOND, 0);
calendar.set(Calendar.DAY_OF_WEEK, Calendar.TUESDAY);
Intent dailyIntent = new Intent(this, AlarmActivity.class);
PendingIntent mondayIntent = PendingIntent.getActivity(this, 1000, dailyIntent, 0);
alarmManager = (AlarmManager) getSystemService(Context.ALARM_SERVICE);
if (Build.VERSION.SDK_INT >= 19) {
alarmManager.setExact(AlarmManager.RTC_WAKEUP, calendar.getTimeInMillis(), mondayIntent);
} else {
System.out.println("------------------------");
}
}
}
AlarmActivity:
public class AlarmActivity extends Activity {
private AlarmManager alarmManager;
Intent intent;
PendingIntent pendingIntent;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.alarm_activity);
alarmManager = (AlarmManager) getSystemService(Context.ALARM_SERVICE);
intent = new Intent(this, AlarmActivity.class);
pendingIntent = PendingIntent.getActivity(this, 1000, intent, 0);
alarmManager.set(AlarmManager.ELAPSED_REALTIME_WAKEUP,
SystemClock.elapsedRealtime() +
60 * 1000 * 3, pendingIntent);
}
}
希望这有帮助。
修改强> 另外,请不要忘记在系统重启和打包(您的应用)更新时设置闹钟。