【问题标题】:Using GPS in the background在后台使用 GPS
【发布时间】:2021-03-05 09:18:18
【问题描述】:

在我正在开发的 GPS 应用程序中,我希望我的 GPS 继续向我提供信息,即使该应用程序不再处于前台。

但是当我的应用程序在后台时,我觉得我不再收到它的信息。

我的智能手机是搭载 android 10 的三星 A41。

不过,我认为我做对了。这是我所做的:

在“build.gradle (Module GPSNav.app) 文件中):

apply plugin: 'com.android.application'
 
android {
    compileSdkVersion 29
    buildToolsVersion "29.0.3"
 
    defaultConfig {
        applicationId "com.example.gpsnav"
        minSdkVersion 23
        targetSdkVersion 29
    }
    buildTypes {
        release {
            minifyEnabled false
            proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
        }
    }
}
 
dependencies {
    //noinspection GradleCompatible
    implementation 'com.android.support:support-v4:24.2.1'
}

在“androidManifest.xml”文件中我有:

    <uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" />
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
<uses-permission android:name="android.permission.ACCESS_BACKGROUND_LOCATION" />"

在我的应用程序中,我有:

private static final int PERMISSION_REQUEST_GPS = 100;
 
...
 
if (ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_BACKGROUND_LOCATION) != PackageManager.PERMISSION_GRANTED
&& ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED
&& ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
    ActivityCompat.requestPermissions(Main.this, new String[]{
        Manifest.permission.ACCESS_BACKGROUND_LOCATION,
        Manifest.permission.ACCESS_COARSE_LOCATION,
        Manifest.permission.ACCESS_FINE_LOCATION}, PERMISSION_REQUEST_GPS);
        return;
    }
 
... 
 
@Override
public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
    if (requestCode == PERMISSION_REQUEST_GPS) {
        if (grantResults[0] == PackageManager.PERMISSION_DENIED) { // Ferme l'application
            Toast.makeText(Main.this, "Désolé !!! vous ne pouvez pas utiliser cette application sans permission", Toast.LENGTH_LONG).show();
            finish();
        }
    }
}

显然这还不够。

应该怎么做?

【问题讨论】:

  • 您是否考虑过为此使用前台服务?
  • 在现代 Android 版本中,您需要使用上述建议的 ForegroundService,并且用户需要在设备的省电设置中将您的应用列入白名单。

标签: android android-gps


【解决方案1】:

确实是涉及服务的方法使得即使应用程序不再处于前台也可以保持 GPS 处于活动状态。

我终于知道为什么它不起作用了。这与我在“NotificationCompat.Builder”中只有一个参数可以给出的事实有关。

在寻找关于通知的文档时,我看到有必要在“build.gradle”文件中拥有这种依赖关系:

dependencies {
    implementation "com.android.support:support-compat:28.0.0"
}

我没有。我用指定的那个替换了我拥有的那个,这一次我能够设置我想要的两个参数并且......我没有更多错误。

今天下午,我带着我的应用程序去远足了,我用“PlantNet”、“birdNET”中断了几次,最后一个应用程序也使用了 GPS:我的应用程序的操作和记录轨迹没有问题。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多