2014-11-28 2 views
1

내 앱에서 GPS가 활성화되어 있는지 확인합니다. 사용하도록 설정되지 않은 경우 페이지를 GPS 설정으로 리디렉션합니다.안드로이드에서 위치 관리자로부터 위치 정보를 가져올 수 없습니다.

GPS를 사용 설정하면 LocationManager에서 위치 정보를 가져옵니다. 그러나 나는 그 위치를 알 수 없다.

여기에 제 코드가 첨부되었습니다.

if (isGPSEnabled()) 
{ 
getLocation(); 
} 



private boolean isGPSEnabled() { 
     boolean gpsEnabled = false; 
     LocationManager locationManager = (LocationManager) getSystemService(LOCATION_SERVICE); 
     if (locationManager.isProviderEnabled(LocationManager.GPS_PROVIDER)) { 
      gpsEnabled = true; 
      return gpsEnabled; 
     } else { 
      showGPSDisabledAlertToUser(); 
     } 
     return gpsEnabled; 
    } 



private void showGPSDisabledAlertToUser() { 
     AlertDialog.Builder alertDialogBuilder = new AlertDialog.Builder(this); 
     alertDialogBuilder 
       .setMessage(
         "GPS is disabled in your device. Would you like to enable it?") 
       .setCancelable(false) 
       .setPositiveButton("Goto Settings Page To Enable GPS", 
         new DialogInterface.OnClickListener() { 
          public void onClick(DialogInterface dialog, int id) { 
           Intent callGPSSettingIntent = new Intent(
             android.provider.Settings.ACTION_LOCATION_SOURCE_SETTINGS); 
           startActivity(callGPSSettingIntent); 
          } 
         }); 

     alertDialogBuilder.setNegativeButton("Cancel", 
       new DialogInterface.OnClickListener() { 
        public void onClick(DialogInterface dialog, int id) { 
         dialog.cancel(); 
        } 
       }); 
     AlertDialog alert = alertDialogBuilder.create(); 
     alert.show(); 
    } 



private void getLocation() { 
     LocationManager locationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE); 
     Criteria criteria = new Criteria(); 
     provider = locationManager.getBestProvider(criteria, false); 
     Location location = locationManager.getLastKnownLocation(provider); 
     if (location != null) { 
      onLocationChanged(location); 
     } else { 

     } 
    } 



    public void onLocationChanged(Location location) { 
     Double lat = (Double) (location.getLatitude()); 
     Double lng = (Double) (location.getLongitude()); 
    } 

내가 실수 한 것을 알려주십시오. 사전에

감사합니다 ..

+0

는 당신이 테스트 실제 장치 또는 안드로이드 에뮬레이터? 당신이 어떤 장치를 사용하고 있다면? GPS가 실내에서 잘 작동하지 않는다는 사실을 명심하십시오. 실외 또는 창문 가까이에서 (예전에 비슷한 모습을 보였을 때) 시도하면 좋을지도 모릅니다. 그러나 LastKnownLocation 전략은 말한대로 작동해야합니다. – facundofarias

+0

Maythis 링크 도움이됩니다. http://stackoverflow.com/questions/4772686/location-managers-requestlocationupdates-called-only-once –

+0

내가 한 실수? 나는 모든 것이 정확하다고 생각한다. GPS를 사용하지 않고 내 앱을 실행하려고하면 메소드가 숨겨지고 수동으로 GPS가 작동합니다. GPS 사용 방법을 추가하려고하면 위치가 표시되지 않습니다. –

답변

0

이 내 Ready made class for finding Location입니다.

Now Use following code in your activity in which you want to get the latitude and longtide.

FindGPSLocation gps; 
gps = new FindGPSLocation(CurrentLocation.this); 
if(gps.canGetLocation()){ 

       latitude = gps.getLatitude(); 
       longitude = gps.getLongitude(); 
       //Toast.makeText(getApplicationContext(), "Your Location is - \nLat: " + latitude + "\nLong: " + longitude, Toast.LENGTH_LONG).show();  
      }else{ 

       gps.showSettingsAlert(); 
      } 

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 android.util.Log; 
public class FindGPSLocation extends Service implements LocationListener { 

    private final Context mContext; 

    // flag for GPS status 
    boolean isGPSEnabled = false; 

    // flag for network status 
    boolean isNetworkEnabled = false; 

    // flag for GPS status 
    boolean canGetLocation = false; 

    Location location; // location 
    double latitude; // latitude 
    double longitude; // longitude 

    // The minimum distance to change Updates in meters 
    private static final long MIN_DISTANCE_CHANGE_FOR_UPDATES = 10; // 10 meters 

    // The minimum time between updates in milliseconds 
    private static final long MIN_TIME_BW_UPDATES = 1000 * 60 * 1; // 1 minute 

    // Declaring a Location Manager 
    protected LocationManager locationManager; 

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

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

       // getting GPS status 
       isGPSEnabled = locationManager 
         .isProviderEnabled(LocationManager.GPS_PROVIDER); 

       // getting network status 
       isNetworkEnabled = locationManager 
         .isProviderEnabled(LocationManager.NETWORK_PROVIDER); 

       if (!isGPSEnabled && !isNetworkEnabled) { 
        // no network provider is enabled 
       } else { 
        this.canGetLocation = true; 
        // First get location from Network Provider 
        if (isNetworkEnabled) { 
         locationManager.requestLocationUpdates(
           LocationManager.NETWORK_PROVIDER, 
           MIN_TIME_BW_UPDATES, 
           MIN_DISTANCE_CHANGE_FOR_UPDATES, this); 
         Log.d("Network", "Network"); 
         if (locationManager != null) { 
          location = locationManager 
            .getLastKnownLocation(LocationManager.NETWORK_PROVIDER); 
          if (location != null) { 
           latitude = location.getLatitude(); 
           longitude = location.getLongitude(); 
          } 
         } 
        } 
        // if GPS Enabled get lat/long using GPS Services 
        if (isGPSEnabled) { 
         if (location == null) { 
          locationManager.requestLocationUpdates(
            LocationManager.GPS_PROVIDER, 
            MIN_TIME_BW_UPDATES, 
            MIN_DISTANCE_CHANGE_FOR_UPDATES, this); 
          Log.d("GPS Enabled", "GPS Enabled"); 
          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; 
     } 

     /** 
     * Stop using GPS listener 
     * Calling this function will stop using GPS in your app 
     * */ 
     public void stopUsingGPS(){ 
      if(locationManager != null){ 
       locationManager.removeUpdates(FindGPSLocation.this); 
      }  
     } 

     /** 
     * Function to get latitude 
     * */ 
     public double getLatitude(){ 
      if(location != null){ 
       latitude = location.getLatitude(); 
      } 

      // return latitude 
      return latitude; 
     } 

     /** 
     * Function to get longitude 
     * */ 
     public double getLongitude(){ 
      if(location != null){ 
       longitude = location.getLongitude(); 
      } 

      // return longitude 
      return longitude; 
     } 

     /** 
     * Function to check GPS/wifi enabled 
     * @return boolean 
     * */ 
     public boolean canGetLocation() { 
      return this.canGetLocation; 
     } 

     /** 
     * Function to show settings alert dialog 
     * On pressing Settings button will lauch Settings Options 
     * */ 
     public void showSettingsAlert(){ 
      AlertDialog.Builder alertDialog = new AlertDialog.Builder(mContext); 

      // Setting Dialog Title 
      alertDialog.setTitle("GPS is settings"); 

      // Setting Dialog Message 
      alertDialog.setMessage("GPS is not enabled. Do you want to go to settings menu?"); 

      // On pressing Settings button 
      alertDialog.setPositiveButton("Settings", new DialogInterface.OnClickListener() { 
       public void onClick(DialogInterface dialog,int which) { 
        Intent intent = new Intent(Settings.ACTION_LOCATION_SOURCE_SETTINGS); 
        mContext.startActivity(intent); 
       } 
      }); 

      // on pressing cancel button 
      alertDialog.setNegativeButton("Cancel", new DialogInterface.OnClickListener() { 
       public void onClick(DialogInterface dialog, int which) { 
       dialog.cancel(); 
       } 
      }); 

      // Showing Alert Message 
      alertDialog.show(); 
     } 

     @Override 
     public void onLocationChanged(Location location) { 
     } 

     @Override 
     public void onProviderDisabled(String provider) { 
     } 

     @Override 
     public void onProviderEnabled(String provider) { 
     } 

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

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

} 
이 코드는 나를 위해 일했다.

+0

가져 오기도 추가 할 수 있습니까 ?? 왜냐하면 나는 수입품을 해결할 수 없기 때문이다. –

+0

추가됨, 그냥 확인해주세요. 알아두면 좋음 –

+0

모바일에서는 실행되지 않습니다. 또한 GPS 사용 설정을 표시하지 않습니다. –

2

저는 LocationManager에서 절대 새로운 위치를 묻지 않는 것이 문제라고 생각합니다.

private void getLocation() { 
    LocationManager locationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE); 
    Criteria criteria = new Criteria(); 
    provider = locationManager.getBestProvider(criteria, false); 
    Location location = locationManager.getLastKnownLocation(provider); 
    if (location != null) { 
     onLocationChanged(location); 
    } else { 
     locationManager.requestSingleUpdate(provider, myLocationListener, null); 
    } 
} 
-1

오래된 위치 제공 업체는 사용하지 마십시오. 구형입니다. Google Play 서비스에 포함 된 통합 위치 제공 업체를 사용해야합니다. 안드로이드 Studio에 내장되어

https://github.com/nickfox/GpsTracker/tree/master/phoneClients/android

: 여기 전체 작업 예제가 있습니다. 그것은 여기에 어떻게 작동하는지 그리고 나는 또한 설명하는 튜토리얼을 가지고 새로운 안드로이드 위치 서비스에 대한 자세한 내용은 마지막으로

https://www.websmithing.com/2014/04/23/how-the-gpstracker-android-client-works/

을 그리고,이 글을 읽을 :

https://developer.android.com/google/play-services/location.html

+0

사실이지만 질문에 답변하지 않습니다. –

관련 문제