java - Android GPS 未显示正确的 LAN 和 lon

标签 java android geolocation android-gps

下面是我的代码,当我接近这个时

(distance is less than 100 meter from my current location) 9.443469,76.540650

GPS 位置我需要振动我的手机,但当我到达那里时它没有振动,并且显示错误的局域网和经度。
我的代码有什么问题?

import android.Manifest;
import android.app.ActivityManager;
import android.app.AlarmManager;
import android.app.PendingIntent;
import android.app.Service;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.pm.PackageManager;
import android.location.Address;
import android.location.Geocoder;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import android.os.IBinder;
import android.os.SystemClock;
import android.os.VibrationEffect;
import android.os.Vibrator;
import android.util.Log;
import android.widget.Toast;

import java.io.IOException;
import java.util.List;
import java.util.Locale;

import androidx.annotation.Nullable;
import io.nlopez.smartlocation.OnLocationUpdatedListener;
import io.nlopez.smartlocation.SmartLocation;
import io.nlopez.smartlocation.location.config.LocationAccuracy;
import io.nlopez.smartlocation.location.config.LocationParams;

public class OfferLocator extends Service {
    SmartLocation mSmartLocation;
    LocationParams locationParam = null;
    double l2 = 9.443469, lo2 = 76.540650, lan = 0, lon = 0;
    boolean running = false;
    double prelan = 0, prelon = 0;
    MyLocationListener locationListener;
    int ct = 0;
    LocationManager locationManager;

    private void info() {
        if (locationManager == null) {
            locationManager = (LocationManager)
                    getSystemService(Context.LOCATION_SERVICE);
        }
        if (locationListener == null) {
            locationListener = new MyLocationListener();
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
                if (checkSelfPermission(Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && checkSelfPermission(Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
                    return;
                }
            }
        }

        locationManager.requestLocationUpdates(
                LocationManager.GPS_PROVIDER, 5000, 5, locationListener);

        Log.i("OfferLocator_info","info called "+ct+" times  lan lon "+lan+","+lon);
        ct++;
        new Handler().postDelayed(new Runnable() {
            @Override
            public void run() {
                info();
            }
        },10000);
        try {
           if(locationParam==null) locationParam = new LocationParams.Builder().setAccuracy(LocationAccuracy.HIGH).build();
        } catch (Exception e){
            Log.i("OfferLocatorv2","error2 :"+e.getMessage()+"");
        }
    }

    @Override
    public void onCreate() {
        super.onCreate();
        Log.d("myLog", "Service: onCreate");
        try {
            locationParam = new LocationParams.Builder().setAccuracy(LocationAccuracy.HIGH).build();
        } catch (Exception e){
            Log.i("OfferLocatorv2","error2 :"+e.getMessage()+"");
        }
        info();
    }

    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {
        Log.d("myLog", "Service: onStartCommand");
        return START_STICKY;
    }

    @Override
    public void onTaskRemoved(Intent rootIntent) {
        Log.d("myLog", "Service: onTaskRemoved");

        Intent restartService = new Intent(getApplicationContext(), this.getClass());
        restartService.setPackage(getPackageName());
        PendingIntent restartServicePI = PendingIntent.getService(
                getApplicationContext(), 1, restartService,
                PendingIntent.FLAG_ONE_SHOT);
        AlarmManager alarmService = (AlarmManager) getApplicationContext().getSystemService(Context.ALARM_SERVICE);
        alarmService.set(AlarmManager.ELAPSED_REALTIME, SystemClock.elapsedRealtime() + 1000, restartServicePI);

        if (Build.VERSION.SDK_INT <= 19) {
            Intent restart = new Intent(getApplicationContext(), this.getClass());
            restart.setPackage(getPackageName());
            startService(restart);
        }

        super.onTaskRemoved(rootIntent);
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
            startForegroundService(new Intent(getApplicationContext(),OfferLocator.class));
        } else {
            startService(new Intent(getApplicationContext(),OfferLocator.class));
        }
        Log.d("myLog", "Service: onDestroy");
        // unregisterReceiver(batteryReceiver);
    }

    private boolean isMyServiceRunning(Class<?> serviceClass) {
        ActivityManager manager = (ActivityManager) getSystemService(Context.ACTIVITY_SERVICE);
        for (ActivityManager.RunningServiceInfo service : manager.getRunningServices(Integer.MAX_VALUE)) {
            if (serviceClass.getName().equals(service.service.getClassName())) {
                return true;
            }
        }
        return false;
    }

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

    class MyLocationListener implements LocationListener {
        String TAG="newloc";
        @Override
        public void onLocationChanged(Location loc) {
            //  editLocation.setText("");
            // pb.setVisibility(View.INVISIBLE);
            double l2 = 9.443469, lo2 = 76.540650;
            float[] results = new float[1];
            Location.distanceBetween( loc.getLatitude(), loc.getLongitude(),l2,lo2, results);
            if (results[0]<100) {
                Toast.makeText(getApplicationContext(),"vibrate please "+results[0],Toast.LENGTH_SHORT).show();
                try {
                    Vibrator v = (Vibrator) getSystemService(getApplicationContext().VIBRATOR_SERVICE);
                    // Vibrate for 500 milliseconds
                    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
                        v.vibrate(VibrationEffect.createOneShot(1500, VibrationEffect.DEFAULT_AMPLITUDE));
                    } else {
                        //deprecated in API 26
                        v.vibrate(1500);
                    }
                } catch (Exception e){
                    Log.i("OfferLocatorv2","error4 :"+e.getMessage()+"");
                }
            } else {
                if (results[0]>500) {
                    try {
                        Vibrator v = (Vibrator) getSystemService(getApplicationContext().VIBRATOR_SERVICE);
                        // Vibrate for 500 milliseconds
                        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
                            v.vibrate(VibrationEffect.createOneShot(1500, VibrationEffect.DEFAULT_AMPLITUDE));
                        } else {
                        //deprecated in API 26
                            v.vibrate(1500);
                        }
                    }catch (Exception e){
                        Log.i("OfferLocatorv2","error4 :"+e.getMessage()+"");
                    }
                }
                Toast.makeText(getApplicationContext(),"my current location is "+results[0],Toast.LENGTH_SHORT).show();
            }

            String longitude = "Longitude: " + loc.getLongitude();
            Log.v(TAG, longitude);
            String latitude = "Latitude: " + loc.getLatitude();
            Log.v(TAG, latitude);

            /*------- To get city name from coordinates -------- */
            String cityName = null;
            Geocoder gcd = new Geocoder(getBaseContext(), Locale.getDefault());
            List<Address> addresses;
            try {
                addresses = gcd.getFromLocation(loc.getLatitude(),
                        loc.getLongitude(), 1);
                if (addresses.size() > 0) {
                    System.out.println(addresses.get(0).getLocality());
                    cityName = addresses.get(0).getLocality();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
            String s = longitude + "\n" + latitude + "\n\nMy Current City is: " + cityName;
            // editLocation.setText(s);
        }

        @Override
        public void onProviderDisabled(String provider) {}

        @Override
        public void onProviderEnabled(String provider) {}

        @Override
        public void onStatusChanged(String provider, int status, Bundle extras) {}
    }
}

最佳答案

如果您从谷歌地图获取坐标,它们可能与通过 MapsActivity 从同一位置获取的坐标略有不同。尝试通过另一个带有 MapsActivity 的应用程序获取您希望手机振动的点的坐标,该应用程序只会为您提供您的位置坐标。

关于java - Android GPS 未显示正确的 LAN 和 lon,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55527908/

相关文章:

java 列表类型变量

java - 尝试使用 java/javafx 在 intellij 上启动并运行 Maven

java - 为服务器端设置 gcm

android - 如何使用 Jenkins、github 和 android studio

java - 如何使用一把 key 加密多个密码?

android - 如何获得未过时的位置?

java - java实现查找HCF/GCD的递归函数

java - 为什么G1 Remark阶段的Unloading Action 耗时太长

android - 为什么 HTML5 地理定位比 Android 上的本地定位慢?

xcode - 使用 Xcode UI 测试更改模拟器位置