【问题标题】:Android: Background Service always shuts downAndroid:后台服务总是关闭
【发布时间】:2018-06-01 01:22:47
【问题描述】:

Android 后台任务运行行为的最新变化使得在手机锁定时保持服务活动并继续在应用程序中工作变得非常困难。我的服务只有在屏幕打开或手机充电时才能正常工作。当手机被锁定时,服务几乎立即关闭或运行速度太慢而无法以任何方式使用。

我尝试使用“START_STICKY”标志和 startForeground() 通知来保持服务活动,但这根本没有帮助。我正在使用每 5 秒调用一次 dowork() 的处理程序,然后检查是否有事可做。

我想在某个时间事件上执行一个简单的任务:每半小时/四分之一小时或整小时醒来一次,做一些没有 CPU 限制的快速工作,然后关闭直到下一次。手机应该按时可靠准确地唤醒,并被“列入白名单”以使用一些 CPU 电源大约半分钟。我不做任何可能影响用户性能的高强度工作。

public class MyService extends Service {


public MyService() {
    super();

}


@Override
public IBinder onBind(Intent intent) {

    return null;
}

@覆盖 public int onStartCommand(Intent intent, int flags, int startId) {

Intent notificationIntent = new Intent(this, MainActivity.class); PendingIntent pendingIntent = PendingIntent.getActivity(this, 0, notificationIntent, 0); Notification notification = new NotificationCompat.Builder(this) .setSmallIcon(R.mipmap.ic_launcher) .setContentTitle("MyService") .setContentText("Service is running") .setPriority(IMPORTANCE_HIGH) .setContentIntent(pendingIntent).build(); startForeground(1, notification); final Handler handler = new Handler(); handler.postDelayed(new Runnable() { @Override public void run() { dowork(); handler.postDelayed(this, 5000); } }, 1500); return START_STICKY; }

【问题讨论】:

  • 你在什么设备上测试?
  • 小米max 2。我禁用了所有的省电限制。
  • 我的 OnePlus 3T 也遇到了同样的问题,结果证明它可以在其他设备上运行。尝试在其他人身上跑步
  • 我会尝试,即使我认为这是一个普遍的问题。还会有解决办法吗?

标签: java android service handler background-process


【解决方案1】:

对于这个问题,我想参考Alarm Manager Example 。这个工作做得很好,我终于做到了。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2020-07-07
    • 1970-01-01
    • 2014-08-10
    • 2022-11-18
    • 1970-01-01
    • 1970-01-01
    • 2011-12-28
    相关资源
    最近更新 更多