背景: 我们有一个应用程序可以为一群人进行时间登记。在此示例中,我们使用 Zebra TC26(型号:TC26BK-11A222-A6),并通过扫描对多人进行打卡。 接下来,应用程序会跟踪手机的 GPS 位置,以定位在哪个字段中执行活动。然后,农民可以更准确地计算每块田地的成本。
这个功能在 Android 10 之前都运行良好。 现在我的设备上发现 1 小时或 1 小时 30 分后我没有获得新位置。 在另一台设备上,我有时会得到更长的时间,但也会停止。 从Android 10开始我遇到了问题,我在网上找到了很多信息,但似乎并没有解决问题。 正常工作日:
所以在工作期间他们不使用手机。
额外:
清单:(我遗漏了一些权限和 antiDozeService,因为我认为它们与 GPS 部分无关)
<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" />
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.WAKE_LOCK" />
<uses-permission android:name="android.permission.FOREGROUND_SERVICE" />
<uses-permission android:name="android.permission.ACCESS_BACKGROUND_LOCATION"/>
<activity android:name=".SplashActivity"
android:theme="@style/SplashTheme">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<activity android:name=".MainActivity"
android:launchMode="singleTop"
android:windowSoftInputMode="stateAlwaysHidden">
<intent-filter>
<action android:name="android.nfc.action.NDEF_DISCOVERED" />
<category android:name="android.intent.category.DEFAULT" />
</intent-filter>
</activity>
<service
android:name=".Services.LocationTracker"
android:enabled="true"
android:foregroundServiceType="location">
</service>
主要活动(请注意,启动活动是入口点,但后来添加,因此仍然称为主要活动)
protected void onCreate(Bundle savedInstanceState)
{
...
Intent service = new Intent(this, xxx.LocationTracker.class);
service.setAction("STARTFOREGROUND_ACTION");
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
startForegroundService(service);
}else{
startService(service);
}
}
位置跟踪器:(onStartCommand)
public int onStartCommand(Intent intent, int flags, int startId) {
//Show notification
Intent notificationIntent = new Intent(mContext, MainActivity.class);
notificationIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TASK);
PendingIntent pendingIntent = PendingIntent.getActivity(mContext, 0, notificationIntent, 0);
//Create notification channel
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
CharSequence name = getString(R.string.service_channel_name);
String description = getString(R.string.service_channel_description);
int importance = NotificationManager.IMPORTANCE_DEFAULT;
NotificationChannel channel = new NotificationChannel("12345678", name, importance);
channel.setDescription(description);
// Register the channel with the system; you can't change the importance
// or other notification behaviors after this
NotificationManager notificationManager = getSystemService(NotificationManager.class);
notificationManager.createNotificationChannel(channel);
}
Notification notification = new NotificationCompat.Builder(this, "12345678")
.setContentTitle("My app title")
.setTicker("My app title")
.setContentText("Application is running")
.setSmallIcon(R.drawable.xxxx)
.setContentIntent(pendingIntent)
.build();
// starts this service as foreground
if(Build.VERSION.SDK_INT >= Build.VERSION_CODES.Q)
{
startForeground(NOTIFICATION_ID, notification, ServiceInfo.FOREGROUND_SERVICE_TYPE_LOCATION);
//=> My latest test I added here the "FOREGROUND_SERVICE_TYPE_LOCATION"
}
else{
startForeground("12345678", notification);
}
return START_STICKY;
}
位置跟踪器:(创建时)
@Override
public void onCreate() {
//LogUtils.debug("LocationTracker service started");
mContext = getApplicationContext();
//Location listener
final Handler handler = new Handler();
handler.postDelayed(new Runnable() {
public void run() {
try{
if(StaticVariables.LocationAllowed)
{
if(StaticVariables.LocationTrackingActive)
{
//Check if we found a point.
Location location = getLatestPoint();
writeLocationToServer(location);
startLocationTracking();
}
else
{
//LogUtils.debug("Location 1: Location tracking is not active");
stopLocationListener();
}
}
handler.postDelayed(this, HANDLER_DELAY);
}
catch (Exception ex)
{
LogUtils.debug("Location failed to run: " + ex.getMessage());
}
}
}, 1000);
位置追踪器:(获取最新点)
private Location getLatestPoint()
{
Location gpsPoint = null;
Location networkPoint = null;
LogUtils.debug("Getting latest point");
if(gpsListener != null)
{
gpsPoint = gpsListener.getLastLocation();
}
if(networkListener != null)
{
networkPoint = networkListener.getLastLocation();
}
if(gpsPoint != null && networkPoint != null)
{
if(gpsPoint.getAccuracy() < networkPoint.getAccuracy())
{
return gpsPoint;
}
else
{
return networkPoint;
}
}
else if(gpsPoint != null)
{
return gpsPoint;
}
else if(networkPoint != null)
{
return networkPoint;
}
else
{
return null;
}
}
位置监听器:
public CustomerLocationListener(LocationManager locationManager, String provider) {
this.locationManager = locationManager;
this.provider = provider;
}
@Override
public void onLocationChanged(Location location) {
this.location = location;
stopLocationListener();
}
@SuppressLint("MissingPermission") //=> Not an issue as this is checked before starting
public void startLocationListener()
{
if(StaticVariables.LocationAllowed)
{
if(locationManager.isProviderEnabled(provider))
{
locationManager.requestLocationUpdates(provider, GPS_TIME_INTERVAL, GPS_DISTANCE,this);
}
else
{
//LogUtils.debug("Provider: " + provider + " is not available");
}
}
}
public void stopLocationListener()
{
if(locationManager != null)
{
locationManager.removeUpdates(this); // remove this listener
}
}
build.gradle:
apply plugin: 'com.android.application'
android {
compileSdkVersion 30
buildToolsVersion '30.0.3'
defaultConfig {
applicationId "xxxx"
minSdkVersion 21
targetSdkVersion 30
versionCode 28
versionName "VERSIONNAME"
testInstrumentationRunner "android.support.test.runner.AndroidJUnitRunner"
multiDexEnabled true //For zxing
}
buildTypes {
release {
minifyEnabled false
proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
}
}
apply plugin: 'com.android.application'
compileOptions {
sourceCompatibility JavaVersion.VERSION_1_7
targetCompatibility JavaVersion.VERSION_1_7
}
}
...
间隔是:“1 个请求/20 秒”,但我已经将其更改为“1 个请求/分钟”
我希望有人可以帮助我找到解决方案,因为这是一个流行的产品。 谢谢您的宝贵时间。
如果你想让你的服务在Android 10及以上的设备上运行,那么你必须使用
startForeground(id, notification)
,否则,它会在一段时间后被系统杀死。
您必须让用户意识到您的应用程序不断在后台运行,如新 API 更改中所述。因此,请尝试仅发送一个简单的通知,并在某个时间间隔内仅发送当前位置,然后检查它是否仍在运行或被杀死。
您还必须关闭应用程序的电池优化,否则会出现同样的问题。
您可以在 Google 上找到有关
startForeground
以及如何以编程方式忽略电池优化的更多信息。
所以尝试一下吧。 :)
查看这篇有关 Android 后台位置限制的文章可能会有所帮助,但恐怕不是好消息。 https://developer.android.com/about/versions/oreo/background-location-limits