如何在特定时间触发 android 的后台服务?
How to trigger a background service in android on specific time?
我知道如何在 android 甚至在特定时间触发后台服务。我已经使用 AlarmManager
来实现这一点,但我想在那个时间每天启动该服务。
假设我想在中午 12 点启动它,但服务应该会在这之后继续进行。我也用过stopitself()
的方法,但是不行。
这是我的代码:
void alram(Context ctx){
Calendar cal = Calendar.getInstance();
cal.setTimeInMillis(System.currentTimeMillis());
cal.set(Calendar.HOUR_OF_DAY, 12);
cal.set(Calendar.MINUTE, 0);
cal.set(Calendar.SECOND, 0);
cal.set(Calendar.AM_PM,Calendar.AM);
Intent serviceIntent = new Intent(ctx, ServiceClass.class);
PendingIntent servicePendingIntent =
PendingIntent.getService(ctx,Service_Apps.SERVICE_ID,serviceIntent,0);
AlarmManager alarm = (AlarmManager) ctx
.getSystemService(Context.ALARM_SERVICE);
alarm.set(AlarmManager.RTC_WAKEUP,cal.getTimeInMillis(),servicePendingIntent);
alarm.setRepeating(
AlarmManager.RTC_WAKEUP,
cal.getTimeInMillis(),
AlarmManager.INTERVAL_DAY,
servicePendingIntent
);
}
您好,请使用此代码,这将有助于满足您的需求。
Calendar calendar = Calendar.getInstance();
calendar.set(Calendar.HOUR_OF_DAY, 12);
calendar.set(Calendar.MINUTE, 0);
calendar.set(Calendar.SECOND, 0);
PendingIntent pi = PendingIntent.getService(this, 0,
new Intent(this, Service_Apps.class),PendingIntent.FLAG_UPDATE_CURRENT);
AlarmManager am = (AlarmManager)getSystemService(Context.ALARM_SERVICE);
am.setRepeating(AlarmManager.RTC_WAKEUP, calendar.getTimeInMillis(),
AlarmManager.INTERVAL_DAY, pi);
我知道如何在 android 甚至在特定时间触发后台服务。我已经使用 AlarmManager
来实现这一点,但我想在那个时间每天启动该服务。
假设我想在中午 12 点启动它,但服务应该会在这之后继续进行。我也用过stopitself()
的方法,但是不行。
这是我的代码:
void alram(Context ctx){
Calendar cal = Calendar.getInstance();
cal.setTimeInMillis(System.currentTimeMillis());
cal.set(Calendar.HOUR_OF_DAY, 12);
cal.set(Calendar.MINUTE, 0);
cal.set(Calendar.SECOND, 0);
cal.set(Calendar.AM_PM,Calendar.AM);
Intent serviceIntent = new Intent(ctx, ServiceClass.class);
PendingIntent servicePendingIntent =
PendingIntent.getService(ctx,Service_Apps.SERVICE_ID,serviceIntent,0);
AlarmManager alarm = (AlarmManager) ctx
.getSystemService(Context.ALARM_SERVICE);
alarm.set(AlarmManager.RTC_WAKEUP,cal.getTimeInMillis(),servicePendingIntent);
alarm.setRepeating(
AlarmManager.RTC_WAKEUP,
cal.getTimeInMillis(),
AlarmManager.INTERVAL_DAY,
servicePendingIntent
);
}
您好,请使用此代码,这将有助于满足您的需求。
Calendar calendar = Calendar.getInstance();
calendar.set(Calendar.HOUR_OF_DAY, 12);
calendar.set(Calendar.MINUTE, 0);
calendar.set(Calendar.SECOND, 0);
PendingIntent pi = PendingIntent.getService(this, 0,
new Intent(this, Service_Apps.class),PendingIntent.FLAG_UPDATE_CURRENT);
AlarmManager am = (AlarmManager)getSystemService(Context.ALARM_SERVICE);
am.setRepeating(AlarmManager.RTC_WAKEUP, calendar.getTimeInMillis(),
AlarmManager.INTERVAL_DAY, pi);