【问题标题】:Fucntion inside service stops after app is closed应用程序关闭后服务内的功能停止
【发布时间】:2020-05-05 04:18:12
【问题描述】:

该服务一直在后台运行,但由于某种原因我的功能saveUserLocation();,一段时间后停止。当应用程序打开时,它会一直运行。这是一些图片,显示关闭应用程序后服务仍在后台运行,另一张图片我关闭应用程序然后logD 仍然打印几秒钟,然后停止。

后台服务

LogD -> logcat 突然停止

服务代码

@Override
public int onStartCommand(Intent intent, int flags, int startId) {
    Log.d(TAG, "onStartCommand: called");

    notificationGenerator();
    getLocation();
    return START_NOT_STICKY;
}

private void getLocation() {
    // ---------------------------------- LocationRequest ------------------------------------
    // Create the location request to start receiving updates
    LocationRequest mLocationRequestHighAccuracy = new LocationRequest();
    mLocationRequestHighAccuracy.setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY);
    mLocationRequestHighAccuracy.setInterval(UPDATE_INTERVAL);
    mLocationRequestHighAccuracy.setFastestInterval(FASTEST_INTERVAL);
    mFusedLocationClient.requestLocationUpdates(mLocationRequestHighAccuracy, new LocationCallback() {
                @Override
                public void onLocationResult(LocationResult locationResult) {
                    Log.d(TAG, "(*) Service Running");
                }
            },
            Looper.myLooper()); // Looper.myLooper tells this to repeat forever until thread is destroyed
}

清单

<service android:name=".service.Service"
android:enabled="true"
android:exported="true"/>

它在 Logcat 中没有说任何错误,它只是停止,当我再次启动应用程序时它继续。任何想法为什么它会停止?

【问题讨论】:

    标签: java android


    【解决方案1】:

    当应用关闭时,服务也会关闭。因为它们在一个线程中,所以服务应该在另一个线程上运行,所以它不能被关闭,所以有两种方法可以激活服务。

    1:使用报警器(关注此[https://stackoverflow.com/a/34790376/8918150][1]

    2:您也可以使用 startForeground()。这是一个很好的方法

    【讨论】:

    • 我确实使用 StartForeground();'
    • 是的,正如我所说,这是最好的方法。是消耗更少的batery。但是,如果您认为有必要使服务始终处于活动状态,请使用第一个选项。这也是方法。通过广播接收器接收您的服务。看看它。 stackoverflow.com/a/52258125/8918150
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-05-15
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多