Android:后台服务总是关闭

问题描述 投票:3回答:1

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

我试图使用“START_STICKY”标志和一个startForeground()通知来保持服务活着,但这根本没有帮助。我正在使用一个每隔5秒调用dowork()的Handler,然后检查是否有事要做。

我想在某个时间事件上执行一个简单的任务:每半个/每季度或整个小时醒来,在没有CPU限制的情况下快速完成工作,然后关闭直到下一次。手机应该按时唤醒可靠和准确,并且“白名单”使用一些CPU功率大约半分钟。我不做任何可能影响用户性能的紧张工作。


public class MyService extends Service {


public MyService() {
    super();

}


@Override
public IBinder onBind(Intent intent) {

    return null;
}

@Override 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; }

java android service handler background-process
1个回答
0
投票

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

© www.soinside.com 2019 - 2024. All rights reserved.