2016-11-22 3 views
-1

위치 관리자와 getLastKnownLocation을 사용하여 기기의 위치를 ​​얻으려고합니다. 다른 질문에 따라 작동해야하지만 위도 광고에 대해 0.0을 반환해야합니다. Longitude .위치 관리자 가져 오기 마지막 위치 가져 오기 위도와 경도에 대해 0.00을 반환합니다.

TrackGPS.java

package com.example.psni.test; 

import android.Manifest; 
import android.app.AlertDialog; 
import android.app.Service; 
import android.content.Context; 
import android.content.DialogInterface; 
import android.content.Intent; 

import android.content.pm.PackageManager; 
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.support.v4.app.ActivityCompat; 
import android.util.Log; 
import android.widget.Toast; 


public class TrackGPS extends Service implements LocationListener { 

    private final Context mContext; 


    boolean checkGPS = false; 
    boolean checkNetwork = false; 
    boolean canGetLocation = false; 
    Location loc; 
    double latitude; 
    double longitude; 


    private static final long MIN_DISTANCE_CHANGE_FOR_UPDATES = 10; 


    private static final long MIN_TIME_BW_UPDATES = 1000 * 60 * 1; 
    protected LocationManager locationManager; 

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

    private Location getLocation() { 

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

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

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

      if (!checkGPS && !checkNetwork) { 
       Toast.makeText(mContext, "No Service Provider Available", Toast.LENGTH_SHORT).show(); 
      } else { 
       this.canGetLocation = true; 
       // First get location from Network Provider 
       if (checkNetwork) { 
        Toast.makeText(mContext, "Network", Toast.LENGTH_SHORT).show(); 

        try { 
         locationManager.requestLocationUpdates(
           LocationManager.NETWORK_PROVIDER, 
           MIN_TIME_BW_UPDATES, 
           MIN_DISTANCE_CHANGE_FOR_UPDATES, this); 
         Log.d("Network", "Network"); 
         if (locationManager != null) { 
          loc = locationManager.getLastKnownLocation(LocationManager.NETWORK_PROVIDER); 

         } 

         if (loc != null) { 
          latitude = loc.getLatitude(); 
          longitude = loc.getLongitude(); 
         } 
        } catch (SecurityException e) { 

        } 
       } 
      } 
      // if GPS Enabled get lat/long using GPS Services 
      if (checkGPS) { 
       Toast.makeText(mContext, "GPS", Toast.LENGTH_SHORT).show(); 
       if (loc == null) { 
        try { 
         locationManager.requestLocationUpdates(
           LocationManager.GPS_PROVIDER, 
           MIN_TIME_BW_UPDATES, 
           MIN_DISTANCE_CHANGE_FOR_UPDATES, this); 
         Log.d("GPS Enabled", "GPS Enabled"); 
         if (locationManager != null) { 
          loc = locationManager.getLastKnownLocation(LocationManager.GPS_PROVIDER); 
          if (loc != null) { 
           latitude = loc.getLatitude(); 
           longitude = loc.getLongitude(); 
          } 
         } 
        } catch (SecurityException e) { 

        } 
       } 
      } 

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

     return loc; 
    } 

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

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

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

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


     alertDialog.setTitle("GPS Not Enabled"); 

     alertDialog.setMessage("Do you wants to turn On GPS"); 


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


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


     alertDialog.show(); 
    } 


    public void stopUsingGPS() { 
     if (locationManager != null) { 

      if (ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) { 

      } 
      locationManager.removeUpdates(TrackGPS.this); 

     } 
    } 


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

    @Override 
    public void onLocationChanged(Location location) { 

    } 

    @Override 
    public void onStatusChanged(String s, int i, Bundle bundle) { 

    } 

    @Override 
    public void onProviderEnabled(String s) { 

    } 

    @Override 
    public void onProviderDisabled(String s) { 

    } 
} 

MainActivity.java는

package com.example.psni.test; 

import android.support.v7.app.AppCompatActivity; 
import android.os.Bundle; 
import android.view.View; 
import android.widget.Button; 
import android.widget.Toast; 

public class MainActivity extends AppCompatActivity { 

    private Button b_get; 
    private TrackGPS gps; 
    double longitude; 
    double latitude; 

    @Override 
    protected void onCreate(Bundle savedInstanceState) { 
     super.onCreate(savedInstanceState); 
     setContentView(R.layout.activity_main); 

     b_get = (Button)findViewById(R.id.get); 



     b_get.setOnClickListener(new View.OnClickListener() { 
      @Override 
      public void onClick(View view) { 

       gps = new TrackGPS(MainActivity.this); 


       if(gps.canGetLocation()){ 


        longitude = gps.getLongitude(); 
        latitude = gps .getLatitude(); 


        Toast.makeText(getApplicationContext(),"Longitude:"+Double.toString(longitude)+"\nLatitude:"+Double.toString(latitude), Toast.LENGTH_SHORT).show(); 
       } 
       else 
       { 

        gps.showSettingsAlert(); 
       } 

      } 
     }); 
    } 

    @Override 
    protected void onDestroy() { 
     super.onDestroy(); 
     gps.stopUsingGPS(); 
    } 


} 
+0

은 마지막 위치에게 그것의 정확하지를하지 마십시오. 위치를 얻으려면 융합 된 API를 사용하십시오. http://stackoverflow.com/questions/39314901/getting-latitude-and-longitude-in-30-seconds의 예입니다. – Saveen

답변

0

이 링크, https://developer.android.com/training/location/retrieve-current.html를 참조하십시오.

mLastLocation = LocationServices.FusedLocationApi.getLastLocation(
      mGoogleApiClient); 
    if (mLastLocation != null) { 
     mLatitudeText.setText(String.valueOf(mLastLocation.getLatitude())); 
     mLongitudeText.setText(String.valueOf(mLastLocation.getLongitude())); 

이것은 onconnected 함수 내에 포함되어야합니다. 아니면 사용할 수

Getting current location in Android Studio app