保持服务即使在运行时手机是睡着了吗? [英] Keep a Service running even when phone is asleep?

查看:134
本文介绍了保持服务即使在运行时手机是睡着了吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个服务在我的应用程序,它被设计成每10分钟一趟。它主要检查了我们的服务器上,看看是否一切都正常运行,并通知任何问题的用户。我创造了这个应用程序在我们公司内部使用。

I have a Service in my application which is designed to run every 10 minutes. It basically checks up on our servers to see if everything is running properly and notifies the user of any problems. I created this application for internal use at our company.

我的同事用在长周末的应用程序,发现没有检查进行时,该设备睡觉去了。我下的是IM pression的服务应该保持在后台运行,直到我明确地调用 stopService()在我的code

My co-worker used the application over the long weekend and noticed that no checks were performed when the device went to sleep. I was under the impression that the Service was supposed to keep running in the background until I explicitly call stopService() in my code.

所以,最后,我的目标是让服务运行,直到用户点击应用程序的关闭按钮或终止进程。

So ultimately, my goal is to have the service running until the user hits the off button in the application or kills the process.

我听说过一种叫 WakeLock 这是为了保持屏幕不关闭,这是不是我想要的。然后我听到了另一件事称为的部分WakeLock 的,这使即使在运行的CPU时,该设备是睡着了。后者听起来更接近我所需要的。

I heard about something called WakeLock which is meant to keep the screen from turning off, which is not what I want. I then heard of another thing called a partial WakeLock, which keeps the CPU running even when the device is asleep. The latter sounds closer to what I need.

我如何获得这种WakeLock,当我应该释放以及是否有其他办法解决这个?

How do I acquire this WakeLock and when should I release it and are there other ways around this?

推荐答案

注:该帖子已被更新,包括了Android棒棒堂发布的的jobscheduler API。下面仍然是一个可行的办法,但也算是德pcated $ P $如果您定位的Andr​​oid棒棒糖和超越。见下半年的的jobscheduler 的选择。

Note: This post has been updated to include the JobScheduler API of the Android Lollipop release. The following is still a viable way, but can be considered deprecated if you're targeting Android Lollipop and beyond. See the second half for the JobScheduler alternative.

要做到经常性工作的一种方法是这样的:

One way to do recurrent tasks is this:

  • 创建一个类 AlarmReceiver

public class AlarmReceiver extends BroadcastReceiver 
{
    @Override
    public void onReceive(Context context, Intent intent) 
    {
        Intent myService = new Intent(context, YourService.class);
        context.startService(myService);
    }
}

YourService 为您服务; - )

with YourService being your service ;-)

如果您需要唤醒锁你的任务,最好是从<一个延伸href="https://developer.android.com/reference/android/support/v4/content/WakefulBroadcastReceiver.html"><$c$c>WakefulBroadcastReceiver.不要忘记添加 WAKE_LOCK 允许在你的清单中这种情况下!

If you require a wake lock for your Task, it is advisable to extend from WakefulBroadcastReceiver. Don't forget to add the WAKE_LOCK permission in your Manifest in this case!

  • 创建一个待定意向

要开始新的反复投票,在活动执行此code:

To start your recurrent polling, execute this code in your activity:

Intent myAlarm = new Intent(getApplicationContext(), AlarmReceiver.class);
//myAlarm.putExtra("project_id", project_id); //Put Extra if needed
PendingIntent recurringAlarm = PendingIntent.getBroadcast(getApplicationContext(), 0, myAlarm, PendingIntent.FLAG_CANCEL_CURRENT);
AlarmManager alarms = (AlarmManager) this.getSystemService(Context.ALARM_SERVICE);
Calendar updateTime = Calendar.getInstance();
//updateTime.setWhatever(0);    //set time to start first occurence of alarm 
alarms.setInexactRepeating(AlarmManager.RTC_WAKEUP, updateTime.getTimeInMillis(), AlarmManager.INTERVAL_DAY, recurringAlarm); //you can modify the interval of course

这code设置了一个报警和canceable pendingIntent 。该 alarmManager 得到这份工作重复 recurringAlarm 每天(第三个参数),而不精确这样CPU就约了时间间隔后,但没有醒来完全(它可以让操作系统选择最佳时间,从而降低电池消耗)。第一次报警(并因此服务)已启动将是您选择的是时间录入

This code sets up an alarm and a canceable pendingIntent. The alarmManager gets the job to repeat the recurringAlarm every day (third argument), but inexact so the CPU does wake up approximately after the interval but not exactly (It lets the OS choose the optimal time, which reduces battery drain). The first time the alarm (and thus the service) is started will be the time you choose to be updateTime.

  • 最后但并非最不重要的:这里是如何杀死循环闹铃

  • last but not least: here is how to kill the recurring alarm

Intent myAlarm = new Intent(getApplicationContext(), AlarmReceiver.class);
//myAlarm.putExtra("project_id",project_id); //put the SAME extras
PendingIntent recurringAlarm = PendingIntent.getBroadcast(getApplicationContext(), 0, myAlarm, PendingIntent.FLAG_CANCEL_CURRENT);
AlarmManager alarms = (AlarmManager) getApplicationContext().getSystemService(Context.ALARM_SERVICE);
alarms.cancel(recurringAlarm);

这code创建您的(可能)现有的报警副本,并告诉 alarmManager 取消所有该类型的警报。

This code creates a copy of your (probably) existing alarm and tells the alarmManager to cancel all alarms of that kind.

  • 当然,也有一些做的,清单

包括以下两行

  < receiver android:name=".AlarmReceiver"></receiver>
  < service android:name=".YourService"></service>

&LT;用途&gt; - 标记。没有它,系统不接受的服务的周期性闹铃开始。

inside the < application>-tag. Without it, the system does not accept the start of recurrent alarm of a service.

Android的棒棒堂发行版开始,有优雅的解决这一任务的新方法。 这也使得它,如果某些标准,例如网络状态满​​足容易只执行一个动作。

Starting with the Android Lollipop release, there's a new way of solving this task elegantly. This also makes it easier to only perform an action if certain criteria such as network state are met.

// wrap your stuff in a componentName
ComponentName mServiceComponent = new ComponentName(context, MyJobService.class);
// set up conditions for the job
JobInfo task = JobInfo.Builder(mJobId, mServiceComponent)
   .setPeriodic(mIntervalMillis)
   .setRequiresCharging(true) // default is "false"
   .setRequiredNetworkCapabilities(JobInfo.NetworkType.UNMETERED) // Parameter may be "ANY", "NONE" (=default) or "UNMETERED"
   .build();
// inform the system of the job
JobScheduler jobScheduler = (JobScheduler) context.getSystemService(Context.JOB_SCHEDULER_SERVICE);
jobScheduler.schedule(task);

您也可以提供与 setOverrideDeadline(maxExecutionDelayMillis)的最后期限

要摆脱这样的任务,只需拨打 jobScheduler.cancel(mJobId); jobScheduler.cancelAll();

To get rid of such a task, just call jobScheduler.cancel(mJobId); or jobScheduler.cancelAll();.

这篇关于保持服务即使在运行时手机是睡着了吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆