在 Android 上无需互联网即可在后台获取更新的纬度经度

问题描述 投票:0回答:1

我想构建位置跟踪Android应用程序,可以在后台每分钟保存用户的坐标,我们的应用程序在具有离线谷歌地图的设备上运行良好,但在我们没有离线地图或互联网连接的设备上,它会停止接收位置更新.

尝试使用两种方法访问纬度/经度 Google Fused API 和 LocationManager 都有相同的问题,下面是我的代码;

public class BackgroundLocationService extends Service {

    @Override
    public void onCreate() {
        super.onCreate();
        initData();

    }


    //Location Callback
    private LocationCallback locationCallback = new LocationCallback() {
        @Override
        public void onLocationResult(LocationResult locationResult) {
            super.onLocationResult(locationResult);

            Location currentLocation = locationResult.getLastLocation();
            lat= Double.toString(currentLocation.getLatitude());
            longit=Double.toString(currentLocation.getLongitude());

        }
    };


    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {


        prepareForegroundNotification("");
        startLocationUpdates();

        return START_STICKY;
    }

    @SuppressLint("MissingPermission")
    private void startLocationUpdates() {
        mFusedLocationClient.requestLocationUpdates(this.locationRequest,
                this.locationCallback, Looper.myLooper());
    }

    private void prepareForegroundNotification(String msg) {

        if(msg.length()==0)
        {
            msg="HCM Location Tracking";
        }
        else {
            msg="HCM, "+msg;
        }
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
            NotificationChannel serviceChannel = new NotificationChannel(
                    "1",
                    msg,
                    NotificationManager.IMPORTANCE_HIGH
            );
            NotificationManager manager = getSystemService(NotificationManager.class);
            manager.createNotificationChannel(serviceChannel);
        }
        Intent notificationIntent = new Intent(this, SplashActivity.class);
        PendingIntent pendingIntent = PendingIntent.getActivity(this,
                121,
                notificationIntent, PendingIntent.FLAG_IMMUTABLE);

        Notification notification = new NotificationCompat.Builder(this, "1")
                .setContentTitle(getString(R.string.app_name))
                .setContentTitle(msg)
                .setSmallIcon(R.mipmap.ic_launcher)
                .setContentIntent(pendingIntent)
                .build();
        startForeground(1, notification);
    }

    @Nullable
    @Override
    public IBinder onBind(Intent intent) {
        return null;
    }

    private void initData() {

         locationRequest = new LocationRequest.Builder(Priority.PRIORITY_HIGH_ACCURACY, UPDATE_INTERVAL_IN_MILLISECONDS)
                .setWaitForAccurateLocation(false)
                .setMinUpdateIntervalMillis(UPDATE_INTERVAL_IN_MILLISECONDS) 
                .setMaxUpdateDelayMillis(UPDATE_INTERVAL_IN_MILLISECONDS)
                .build();

         mFusedLocationClient =
                LocationServices.getFusedLocationProviderClient(Global.getInstance());

          gpsTracker = new GPSTracker( this);
          getCoordinatesFromMangerHandler();

 

        locationSettings();

    }

    private void getCoordinatesFromMangerHandler() {
        mHandler.postDelayed(new Runnable() {
            @Override
            public void run() {
                getCoordinatesFromManger();
                mHandler.postDelayed(this, CHECK_INTERVAL);
            }
        }, CHECK_INTERVAL);
    }

 
     private void getCoordinatesFromManger() {
 
        if(gpsTracker==null){
            gpsTracker = new GPSTracker( this);
        }
        gpsTracker.getLocation();

        lat= Double.toString(gpsTracker.getLatitude());
        longit=Double.toString(gpsTracker.getLongitude());

 
    }

    private void locationSettings() {

        LocationSettingsRequest.Builder builder = new LocationSettingsRequest.Builder()
                .addLocationRequest(locationRequest);

        SettingsClient client = LocationServices.getSettingsClient(this);
        Task<LocationSettingsResponse> task = client.checkLocationSettings(builder.build());
        task.addOnSuccessListener(new OnSuccessListener<LocationSettingsResponse>() {
            @Override
            public void onSuccess(LocationSettingsResponse locationSettingsResponse) {

            }
        });

        task.addOnFailureListener(new OnFailureListener() {
            @Override
            public void onFailure(@NonNull Exception e) {
                if (e instanceof ResolvableApiException) {
                      try {
                        ResolvableApiException resolvable = (ResolvableApiException) e;
                     prepareForegroundNotification("Kindly enable Wi-Fi scanning and location.");

                    } catch (Exception sendEx) {
                    }
                }
            }
        });

    }



    @Override
    public void onDestroy() {
        super.onDestroy()

        Intent broadcastIntent = new Intent();
        broadcastIntent.setAction("restartservice");
        broadcastIntent.setClass(this, RestartUserActivity.class);
        this.sendBroadcast(broadcastIntent);
    }
}
android geolocation locationmanager android-gps fusedlocationproviderapi
1个回答
0
投票

在 Android 中,有 3 种获取位置的方法。 它们是 GPS、网络和 Google。 实际上网络使用谷歌的API,但如果你想在没有任何地图和互联网连接的情况下获取当前位置,你需要实现GPS_PROVIDER

如果存在,该提供商使用 GNSS 卫星确定位置。定位的响应能力和准确性可能取决于 GNSS 信号条件。然而,GPS 获取位置信息的速度可能较慢,并且可能无法在室内或高楼大厦遮挡卫星信号的城市环境中正常工作。

检查这个 教程

© www.soinside.com 2019 - 2024. All rights reserved.