1

我的Android应用程序出现问题。我使用这个类:如何获得当前位置

package com.example.seadog.gps; 

import android.app.AlertDialog; 
import android.app.Service; 
import android.content.Context; 
import android.content.DialogInterface; 
import android.content.Intent; 
import android.location.Location; 
import android.location.LocationListener; 
import android.location.LocationManager; 
import android.os.Bundle; 
import android.os.IBinder; 
import android.provider.Settings; 

import org.json.JSONObject; 

public class GPSTracker extends Service implements LocationListener { 

    private Context mContext; 

    public GPSTracker() { 

    } 

    boolean isGPSEnabled = false; 

    boolean isNetworkEnabled = false; 

    boolean canGetLocation = false; 

    Location location; 
    double latitude; 
    double longitude; 

    private static final long MIN_DISTANCE_CHANGE_FOR_UPDATES = 10; 

    private static final long MIN_TIME_BW_UPDATES = 5000; 

    protected LocationManager locationManager; 

    public GPSTracker(Context context) { 
     this.mContext = context; 
     getLocation(); 
    } 

    public Location getLocation() { 
     try { 
      locationManager = (LocationManager) mContext.getSystemService(LOCATION_SERVICE); 

      isGPSEnabled = locationManager.isProviderEnabled(LocationManager.GPS_PROVIDER); 

      isNetworkEnabled = locationManager.isProviderEnabled(LocationManager.NETWORK_PROVIDER); 

      if (!isGPSEnabled && !isNetworkEnabled) { 

      } else { 

       this.canGetLocation = true; 

       if (isNetworkEnabled) { 
        locationManager.requestLocationUpdates(LocationManager.NETWORK_PROVIDER, 
          MIN_TIME_BW_UPDATES, 
          MIN_DISTANCE_CHANGE_FOR_UPDATES, this); 

        if (locationManager != null) { 
         location = locationManager.getLastKnownLocation(LocationManager.NETWORK_PROVIDER); 
         if (location != null) { 
          latitude = location.getLatitude(); 
          longitude = location.getLongitude(); 
         } 
        } 
       } 

       if (isGPSEnabled) { 

        if (location == null) { 
         locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 
           MIN_TIME_BW_UPDATES, 
           MIN_DISTANCE_CHANGE_FOR_UPDATES, this); 

         if (locationManager != null) { 
          location = locationManager.getLastKnownLocation(LocationManager.GPS_PROVIDER); 
          if (location != null) { 
           latitude = location.getLatitude(); 
           longitude = location.getLongitude(); 
          } 
         } 
        } 
       } 
      } 

     } catch (Exception e) { 
      e.printStackTrace(); 
     } 

     return location; 
    } 

    public void stopUsingGPS(){ 
     if(locationManager != null){ 
      locationManager.removeUpdates(GPSTracker.this); 
     } 
    } 

    public double getLatitude(){ 
     if(location != null){ 
      latitude = location.getLatitude(); 
     } 

     return latitude; 
    } 

    public double getLongitude(){ 
     if(location != null){ 
      longitude = location.getLongitude(); 
     } 

     return longitude; 
    } 

    public boolean canGetLocation() { 
     return this.canGetLocation; 
    } 


    public void showSettingsAlert() { 
     AlertDialog.Builder alertDialog = new AlertDialog.Builder(mContext); 

     alertDialog.setTitle("GPS jest wyłączony"); 

     alertDialog.setMessage("Do używania tej aplikacji wymagany jest GPS. W tym celu przejdź do ustawień, włącz GPS a następnie uruchom ponownie."); 

     alertDialog.setPositiveButton("Ustawienia", new DialogInterface.OnClickListener() { 
      public void onClick(DialogInterface dialog,int which) { 
       Intent intent = new Intent(Settings.ACTION_LOCATION_SOURCE_SETTINGS); 
       mContext.startActivity(intent); 
       System.exit(0); 
      } 
     }); 

     alertDialog.setNegativeButton("Anuluj", new DialogInterface.OnClickListener() { 
      public void onClick(DialogInterface dialog, int which) { 
       dialog.cancel(); 
       System.exit(0); 
      } 
     }); 


     alertDialog.show(); 
    } 

    @Override 
    public void onLocationChanged(Location location) { 

     int ID = GlobalConfig.ID; 
     int Random = GlobalConfig.Random; 

     double latitude = location.getLatitude(); 
     double longitude = location.getLongitude(); 

     try { 

      JSONObject json = new JSONObject(); 
      json.put("ID", ID); 
      json.put("Random", Random); 
      json.put("latitude", latitude); 
      json.put("longitude", longitude); 

      GlobalConfig config = new GlobalConfig(); 
      config.set(json); 
      //config.i(0); 

     } catch(Exception e){ 
      e.printStackTrace(); 
     } 

    } 

    @Override 
    public void onProviderDisabled(String provider) { 
     System.exit(0); 
    } 

    @Override 
    public void onProviderEnabled(String provider) { 
    } 

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

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

} 

本课程取自互联网。我在OnChangedLocation中添加了自己的代码。当坐标发生变化时,然后在GlobalConfig类中创建一个带有新经度和纬度的JSONObject。 在另一个类中有一个Service,它在后台每5秒向服务器发送一次数据。 我的问题是经度和纬度不正确。有时候获得的价值是正确的,而其他时候则不是。该位置保持相同约10或几分钟,并在一段时间后显示正确的值。 我的应用程序在后台运行。在浏览器中,我在Google地图上预览了一下,我的标记在地图上跳转。我在驾驶汽车时进行了测试。

有什么不对。我想获得正确的经纬度。帮帮我!

+0

这种类型的问题已被问到 –

+0

您应该使用搜索功能并查看谷歌手册[API指南](http://developer.android.com/guide/topics/location/strategies.html) –

+0

可能[通过使用GPS获取Android手机的位置]的副本(http://stackoverflow.com/questions/2651499/getting-the-position-of-an-android-phone-by-using-gps) –

回答

2

您应该使用最后一个Google API来定位。首先,你像这样此API的连接:现在

GoogleApiClient googleApiClient = new GoogleApiClient.Builder(this) 
        .addApi(LocationServices.API) 
        .addConnectionCallbacks(locationClientCallback) 
        .addOnConnectionFailedListener(locationClientCallback) 
        .build(); 

if (!(googleApiClient.isConnected() || googleApiClient.isConnecting())) { 
     googleApiClient.connect(); 
} 

,在你locationClientCallback您收到API是否已连接上。

private class LocationClientCallback implements GoogleApiClient.ConnectionCallbacks, GoogleApiClient.OnConnectionFailedListener, LocationListener { 

     @Override 
     public void onLocationChanged(Location location) { 
      if (location == null) { 
       return; 
      } 

      // YOU HAVE YOUR POSITION 

     } 

     @Override 
     public void onConnectionFailed(ConnectionResult arg0) { 
      // CONNECTION FAILED 
     } 

     @Override 
     public void onConnected(Bundle arg0) { 
      // GOOGLE API CONNECTED 


      // MAKE A REQUEST FOR LOCATIONS 
      LocationRequest request = LocationRequest.create(); 
      request.setSmallestDisplacement(0); 
      request.setInterval(5000); 
      request.setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY); 
      LocationServices.FusedLocationApi.requestLocationUpdates(googleApiClient, request, this); 

     } 

     @Override 
     public void onConnectionSuspended(int i) { 
      // CONNECTION SUSPENDED 

     } 


    } 

而在回调中你会收到职位和其他事件。在onConnected事件中,您应该向Google API客户端请求位置信息。

希望它可以帮助你!

+0

我的意思是这不是。我为司机创建应用程序。即使隐藏了应用程序或智能手机处于睡眠模式,我的应用程序也可以在后台运行。设备每隔5秒向一台服务器发送一个数据,但这是一个问题。这个位置是错误的。有时候是正确的。我只想在我的数据库中保存正确的经度和纬度,然后将这些项目放在网站上的谷歌地图上。 – SeaDog

+0

获取位置的正确方法是这样的。您应该在服务中执行此代码。在这个位置你有一个表示位置准确度的字段,如果准确度非常高,你可以排除这个位置。 –

+0

我会告诉你,我不知道它是如何使用的。我有一个标有红色的库。我需要从谷歌获得API密钥,如果我有一个GPSTracker,我必须删除它,并创建新的LocationClientCallback类与实现...? – SeaDog