Android(后台服务总是关闭)

白日放歌须纵酒,青春作伴好还乡。这篇文章主要讲述Android:后台服务总是关闭相关的知识,希望能为你提供帮助。
最近androids后台任务运行行为的变化使得维护服务变得非常困难并且在手机被锁定时继续在应用程序中工作。我的服务仅在屏幕开启或手机充电时才能正常工作。当手机被锁定时,服务几乎立即关闭或运行速度太慢而无法以任何方式使用。
我试图使用“START_STICKY”标志和一个startForeground()通知来保持服务活着,但这根本没有帮助。我正在使用一个每隔5秒调用dowork()的Handler,然后检查是否有事要做。
【Android(后台服务总是关闭)】我想在某个时间事件上执行一个简单的任务:每半个/每季度或整个小时醒来,在没有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; }


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

    推荐阅读