【问题标题】:Background service are not working in Android in sleep mode后台服务在睡眠模式下无法在 Android 中运行
【发布时间】:2020-12-09 05:17:47
【问题描述】:

在我的 Android 应用程序中,我每天下午 5 点跟踪用户位置并将该位置发送到服务器。为此,我正在运行一项服务。 但我的问题是,如果应用程序处于前台模式,服务就会启动。但如果应用程序处于后台模式超过 10 分钟或下一个日期。 然后服务没有启动。下面是我的服务启动代码。

Log.d("Service log","service will start");
if( (ContextCompat.checkSelfPermission(context, 
           Manifest.permission.ACCESS_FINE_LOCATION)) == 
                    PackageManager.PERMISSION_GRANTED){
Intent backgnd = new Intent(context, BackgrndService.class);
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
try{ 
  Log.d("Service log","service starting in oreo");
                             context.stopService(backgnd);
                           context.startForegroundService(backgnd);}
                           catch(Exception e){
                              context.startForegroundService(backgnd);
                           }
                        }else {
                            
                           try{ 
                           Log.d("Service log","service start");
                             context.stopService(backgnd);
                           context.startService(backgnd);}
                           catch(Exception e){
                              context.startService(backgnd);
                           }
                        }
                    }else{
                        Log.d("Service log","NO Access Location permission");
                    }
                    

在 LogCat 中,我可以看到第一个日志。但其他日志没有显示。 请提供如何在后台模式(睡眠模式)下运行该服务的建议。

【问题讨论】:

    标签: java android service androidx


    【解决方案1】:

    Android 操作系统会不时终止后台服务以节省资源(能源)。因此,避免您需要将其保留为前台服务。 我会为服务创建一个通知并指出它是前台。 (这有两个好处,操作系统不会终止您的服务,用户也不会尝试终止正在运行的应用程序)。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2014-03-01
      • 2013-12-03
      • 2015-08-10
      • 2019-05-16
      • 1970-01-01
      • 2016-04-27
      • 1970-01-01
      相关资源
      最近更新 更多