微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

GPS 跟踪的前台服务在一段时间后停止工作

如何解决GPS 跟踪的前台服务在一段时间后停止工作

背景: 我们有一个应用程序可以为一群人进行时间注册。在本例中,我们使用 Zebra TC26(型号:TC26BK-11A222-A6)并通过扫描为多人计时。 接下来,应用程序会跟踪手机的 GPS 位置以定位执行活动的字段。然后,农民可以更准确地计算每块田的成本。

这一直工作到 android 10。 现在我在我的设备上没有在 1 小时或 1 小时 30 分后获得新位置。 在另一台设备上,我有时会得到更长的时间,但它也停止了。 从 Android 10 开始,我遇到了问题,我在网上找到了很多信息,但似乎并没有解决问题。 一个正常的工作日:

  • 早上 8 点左右开始。然后设备在口袋里直到午餐
  • 在下午 1:00 至下午 1:30 之间享用午餐,然后设备再次放入口袋。
  • 下午 5 点左右结束。

所以他们在工作期间不使用手机。

额外

  • 过去,我尝试在屏幕上设置唤醒锁。这适用于 android 8/9 再次激活 GPS。但这在 android 10/11 上不起作用
  • 我还在不需要的情况下添加后台位置访问权限,但看看是否可以启用“始终定位”(如果这有影响)。
  • antiDoze 服务也是几年前用来保持 cpu 清醒的东西。请注意,通知的 channelID 是相同的。我不知道这是否有影响。
  • 我还在我的应用中看到,大多数情况下(例如 99%),服务器仍会从设备接收数据,但该位置为空。在 1% 的情况下,设备没有发送数据。
  • 我不使用保险丝位置提供程序,因为并非所有设备都具有 GMS 服务。
  • 答案可能是我需要重写一些东西。对我来说这不是问题,因为我的最终目标是拥有一个可以工作的产品。如果是这种情况,请向我提供详细的计划以及放置内容的位置或提供教程链接

清单:(我省略了一些权限和 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>

Main acitivity(注意,splash Activity 是入口点,但后来添加,所以它仍然被称为 main Activity)

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,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;
}

位置跟踪器:(onCreate)

@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);

位置跟踪器:(getLatestPoint)

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 更改中所述。因此,尝试使用简单的通知并在某个时间间隔内仅发送当前位置,然后检查它是否仍在运行或被杀死。

您还必须关闭应用的电池优化,否则会出现同样的问题。

您可以在谷歌的任何地方找到有关 startForeground 以及如何以编程方式忽略电池优化的信息。

所以试试吧。 :)

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。