几分钟后服务自动停止

service automatically stops after several minutes

我正在创建一个服务,它应该在 activity 处于后台以及整个应用程序被销毁时工作。

我每隔 1 分钟调用服务中的位置坐标。

但是,当我尝试这样做时,服务会在 12-15 分钟后自动关闭。

我希望该服务无休止地工作,直到且除非它因用户交互的 activity 完成而被破坏。

我的服务class如下:

public class SensorService extends Service {
    public int counter=0; 
    public static final int NINTY_SECONDS = 90000; 
    public static Boolean isRunning = false;
    public LocationManager mLocationManager;
    public Get_Coordinates mLocationListener;
    public GetSharedPreference sharedPreference;
    @Override
    public void onCreate() {
        mLocationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
        mLocationListener = new Get_Coordinates(getApplicationContext());
        sharedPreference = new GetSharedPreference(getApplicationContext());
        startTimer();
        super.onCreate();
    }
    public SensorService(Context applicationContext) {
        super();
        Log.i("HERE", "here I am!");
    }

    public SensorService() {
    }
    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {
        super.onStartCommand(intent, flags, startId);
        return START_STICKY;
    }
    @Override
    public void onDestroy() {
        super.onDestroy();
        Log.i("EXIT", "ondestroy!");
        Intent broadcastIntent = new Intent("com.android.startBgService");
        broadcastIntent.putExtra("abc","abcd");
        sendBroadcast(broadcastIntent);
        stoptimertask();
    }

    private Timer timer;
    private TimerTask timerTask;
    long oldTime=0;
    public void startTimer() {
        //set a new Timer
        timer = new Timer();

        //initialize the TimerTask's job
        initializeTimerTask();

        //schedule the timer, to wake up every 1 second
        timer.schedule(timerTask, NINTY_SECONDS, NINTY_SECONDS); //
    }

    /**
     * it sets the timer to print the counter every x seconds
     */
    public void initializeTimerTask() {
        timerTask = new TimerTask() {
            public void run() {
               // Log.i("in Etro Sendor", "in timer ++++  "+ (counter++));
                if (Check_Internet_Con.isConnectingToInternet(getApplicationContext())) {

                    if (!isRunning) {
                        startListening();
                    }
                    try {
                        if (sharedPreference.getActiveUserId() > 0) {
                            mLocationListener.getLocation();
                            mLocationListener.insertCoordinatesInSqlite();
                        }
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                }
            }
        };
    }

    /**
     * not needed
     */
    public void stoptimertask() {
        //stop the timer, if it's not already null
        if (timer != null) {
            timer.cancel();
            timer = null;
        }
    }

    @Nullable
    @Override
    public IBinder onBind(Intent intent) {
        return null;
    }
    public void startListening() {
        if (ContextCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) == PackageManager.PERMISSION_GRANTED
                || ContextCompat.checkSelfPermission(this, Manifest.permission.ACCESS_COARSE_LOCATION) == PackageManager.PERMISSION_GRANTED) {
            if (mLocationManager.getAllProviders().contains(LocationManager.NETWORK_PROVIDER))
                mLocationManager.requestLocationUpdates(LocationManager.NETWORK_PROVIDER, 0, 0, mLocationListener, Looper.getMainLooper());

            if (mLocationManager.getAllProviders().contains(LocationManager.GPS_PROVIDER))
                mLocationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 0, 0, mLocationListener,Looper.getMainLooper());
        }
        isRunning = true;
    }
}

这是我的清单

<service
           android:name="com.lunetta.etro.e_tro.SensorService"
           android:enabled="true"></service>
       <service
           android:name="com.lunetta.etro.e_tro.SecondService"
           android:enabled="true" >
       </service>

       <receiver
           android:name=".SensorRestarterBroadcastReceiver"
           android:enabled="true"
           android:exported="true"
           android:label="RestartServiceWhenStopped">
           <intent-filter>
               <action android:name="com.android.startBgService" />
               <action android:name="android.intent.action.BOOT_COMPLETED" />
           </intent-filter>
       </receiver>

这是 SensorRestarterBroadcastReceiver class

public class SensorRestarterBroadcastReceiver extends BroadcastReceiver {
    @Override
    public void onReceive(Context context, Intent intent) {
        Log.i(SensorRestarterBroadcastReceiver.class.getSimpleName(), "Service Stops! Oooooooooooooppppssssss!!!!");
        context.startService(new Intent(context, SensorService.class));
        
    }
}

https://developer.android.com/guide/components/bound-services.html

"A bound service typically lives only while it serves another application component and does not run in the background indefinitely."

要使其 运行 无限期,您需要将服务绑定到无限期存在的 UI 组件。您可以使用 Android 通知。这是前台服务。

https://developer.android.com/guide/components/services.html#Foreground

是的,它会停止工作,查看 Google 提供的新文档,它完全改变了位置对电池性能的影响,是的,它对性能有很大影响,我已经改变了我的完全用于非常具体的任务。也停止使用其他声称它们工作错误的回购协议

通过google

检查新更新的文档

https://developer.android.com/training/building-location.html

我实现您相同要求的最佳方式是并且在超过 60k 台设备中运行并且完美地工作是根据 Android API 的版本使用 23 及更高和更低的 JobService后台服务。相应地使用了 LocationProvider API 和 Location provider Client API。

根据我的个人经验,我会这样说 旧式代码用于在几个小时内耗尽设备电池,现在我的代码几乎没有任何影响,它在一夜之间仅消耗了 15% 的整体使用量。这是消费的巨大变化。