【问题标题】:Will startService() still work if my app targeting nougat devices如果我的应用程序针对牛轧糖设备,startService() 仍然有效
【发布时间】:2018-05-28 09:05:36
【问题描述】:

这就是我启动定位服务的方式。

private void initLocationService() {

    locationManager = (LocationManager) getSystemService(LOCATION_SERVICE);

    if(getPermissions(android.Manifest.permission.ACCESS_FINE_LOCATION,GET_LOCATION_PERMISSION)){
        startService(new Intent(HomeActivity.this, LocationUpdateService.class));
    }
}

LocationUpdateService 中,我将其作为STICKY 服务启动。所以它一直在后台工作。

public class LocationUpdateService extends Service implements
        LocationListener,
        GoogleApiClient.ConnectionCallbacks,
        GoogleApiClient.OnConnectionFailedListener,
        IServiceResponse {


    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {
        Log.i(TAG, "onStartCommand: ");
        mLocationRequest = new LocationRequest();
        mLocationRequest.setInterval(BACKGROUND_INTERVAL);
        mLocationRequest.setFastestInterval(BACKGROUND_INTERVAL);
        mLocationRequest.setPriority(LocationRequest.PRIORITY_BALANCED_POWER_ACCURACY);

        super.onStartCommand(intent, flags, startId);
        return START_STICKY;
    }

由于我的应用目前针对 Api 25(Nougat),我需要在此特定服务中进行哪些更改才能使其在 Oreo 中工作

在使用compileSdkVersion 25 时,我仍然无法访问startForegroundService() 方法。

这些是我的gradle 设置。

compileSdkVersion 25
buildToolsVersion "25.0.3"

defaultConfig {

    minSdkVersion 21
    targetSdkVersion 25
}

【问题讨论】:

标签: android performance android-location android-8.0-oreo


【解决方案1】:

startForegroundService() 可从API level 25 的 API 级别 26 NOT 获得。

compileSdkVersion 25buildToolsVersion "25.0.3" 更改为最新版本并尝试。

例如,就我而言,我在下面使用:

compileSdkVersion 26
buildToolsVersion '27.0.3'

【讨论】:

  • 是的,在将compileSdkVersion 更改为27 之后,它给了我方法,但是如果我不使用startForegroundService() 会出什么问题,它会导致我的应用程序崩溃,或者START_STICKY 会停止工作。
  • 这种变化会让一切工作更顺利吗? if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) { startForegroundService(start_intent); }
  • 是的,正确,您的应用在运行时会崩溃。所以是的,这个检查将起作用if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) { startForegroundService(start_intent); }
  • 谢谢,您知道 Google 何时推出这些指南吗?
  • 我认为不需要指南。检查和支持以前的版本是常见的 Android 编码实践。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2016-12-30
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多