我有一项服务,我想在后台每分钟执行一项任务.只要用户正在使用手机,它就不需要在手机处于睡眠状态时执行任务.我试图用IntentService这样做,设置如下:
public class CounterService extends IntentService{
public CounterService() {
super("CounterService");
}
@Override
public int onStartCommand(Intent intent, int flags, int startId) {
return super.onStartCommand(intent,flags,startId);
}
@Override
protected void onHandleIntent(Intent intent) {
Toast.makeText(this, "onhandleintent", Toast.LENGTH_SHORT).show();
while(true)
{
//one minute is 60*1000
try {
Thread.sleep(5 * 1000);
Toast.makeText(getApplicationContext(), "getting app count", Toast.LENGTH_LONG).show();
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
}
Run Code Online (Sandbox Code Playgroud)
现在为了使功能正常工作,我只想让它每隔5秒显示一次吐司,我会在一分钟之后将其更改.如果我已while(true)
注释掉,则会显示"onhandleintent"消息.但是,如果我运行以下代码,则不会显示Toasts.我怎样才能解决这个问题?
我有这个代码
Calendar c = new GregorianCalendar();
c.add(Calendar.DAY_OF_YEAR, 1);
c.set(Calendar.HOUR_OF_DAY, 23);
c.set(Calendar.MINUTE, 22);
c.set(Calendar.SECOND, 0);
c.set(Calendar.MILLISECOND, 0);
// We want the alarm to go off 30 seconds from now.
long firstTime = SystemClock.elapsedRealtime();
firstTime += 30*1000;
long a=c.getTimeInMillis();
// Schedule the alarm!
AlarmManager am = (AlarmManager)ctx.getSystemService(Context.ALARM_SERVICE);
am.setRepeating(AlarmManager.ELAPSED_REALTIME_WAKEUP,
c.getTimeInMillis(), 1*60*60*1000, sender);
Run Code Online (Sandbox Code Playgroud)
它不会在23:22h执行
我做错了什么?我注意到firstTime和c.getTimeInMillis()在大小和长度上有很大差异.当我使用firstTime时,所以当设置为30秒时,警报执行得很好.
我进入了我希望在特定时间触发服务的场景.
我所知道的是......我需要使用AlarmManager
,我发现这个问题听到,使用Alarmmanager在特定时间启动服务.现在,我可以在特定时间开始服务.
现在的问题是......我需要24小时间隔才能开始服务.现在如果手机重启会怎样 它会再次开始服务吗?
我怎么能让这件事发生?请在这件事上给予我帮助
谢谢
我编写了一个前台服务,以确保我的应用程序在进入后台时可以继续运行。该应用程序需要在后台运行,因为在其计时器结束后,它会发出提示音并振动以提醒用户。但是,当按下电源或主页按钮时,除非手机接通电源,否则应用程序的计时器会在大约 15 分钟后停止运行。当我测试时,手机已充满电。
顺便说一句,在阅读了确保应用程序继续运行的各种网站后,我还将应用程序设置为不针对电池寿命进行优化。从我阅读的所有内容来看,我所做的一切都是正确的,但我仍然无法让它发挥作用。我在 Pixel 2 上运行 Android 11。我知道 Google 限制了更高版本 Android 的前台处理,但是将应用程序设置为不优化电池寿命应该可以解决这个问题,不是吗?为安全起见,当应用程序启动时,它会要求用户批准后台操作:
PowerManager pm = (PowerManager)getSystemService(POWER_SERVICE);
if (!pm.isIgnoringBatteryOptimizations(APPLICATION_ID)) {
// Ask user to allow app to not optimize battery life. This will keep
// the app running when the user puts it in the background by pressing
// the Power or Home button.
Intent intent = new Intent();
intent.setAction(Settings.ACTION_REQUEST_IGNORE_BATTERY_OPTIMIZATIONS);
intent.setData(Uri.parse("package:" + APPLICATION_ID));
startActivity(intent);
}
Run Code Online (Sandbox Code Playgroud)
因此,当应用程序运行并针对电池进行优化时,用户会看到以下内容:
我启动前台服务如下:
private void startForegroundMonitoring() {
broadcastIntent = new Intent(context, BroadcastService.class);
broadcastIntent.putExtra(ALLOWEDTIME, allowed_time);
broadcastIntent.putExtra(BEEP, beep.isChecked()); …
Run Code Online (Sandbox Code Playgroud)