【发布时间】: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