android gps 没有显示正确的 lan 和 lon

Posted

技术标签:

【中文标题】android gps 没有显示正确的 lan 和 lon【英文标题】:android gps is not showing right lan and lon 【发布时间】:2019-08-26 21:58:59 【问题描述】:

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

(距离我当前位置不到 100 米) 9.443469,76.540650

gps 位置我需要振动我的手机,但是当我到达那里时它没有振动并且它显示错误的 lan 和 lon。 我的代码有什么问题?

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) 
    

【问题讨论】:

【参考方案1】:

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

【讨论】:

以上是关于android gps 没有显示正确的 lan 和 lon的主要内容,如果未能解决你的问题,请参考以下文章

由于不包括大地水准面高度,Android 的 GPS 高度是不是不正确?

在 Android 中使用 GPS 检测位置需要很长时间

使用 React Native 的 Android 上的 GPS 定位精度差/差

Android HTML5 地理位置不显示 GPS 图标

如何将 GPS 坐标转换为位置

Android GPS 和定位服务帮助