android位置服务GPS经纬度获取

Activity_main.xml




    

MainActivity.java

public class MainActivity extends AppCompatActivity {
	TextView gps_text;//GPS显示控件
    LocationManager locationManager;//位置服务管理器
     protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        gps_text = (TextView) findViewById(R.id.gps_text);
        locationManager = (LocationManager) getSystemService(LOCATION_SERVICE);
       
		 if (ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
            // TODO: Consider calling
            //    ActivityCompat#requestPermissions
            // here to request the missing permissions, and then overriding
            //   public void onRequestPermissionsResult(int requestCode, String[] permissions,
            //                                          int[] grantResults)
            // to handle the case where the user grants the permission. See the documentation
            // for ActivityCompat#requestPermissions for more details.
            return;
        }
        locationManager.requestLocationUpdates(
                LocationManager.GPS_PROVIDER,//指定GPS为内容提供者
                1000,//间隔时间为1秒
                1,//距离为1米
                new LocationListener() {
                    @Override
                    public void onLocationChanged(Location location) {

                    }

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

                    }

                    @Override
                    public void onProviderEnabled(String provider) {

                    }

                    @Override
                    public void onProviderDisabled(String provider) {

                    }
                }
        );
        Location location=locationManager.getLastKnownLocation(LocationManager.GPS_PROVIDER);
        locationUpdate(location);
    }
    //Location更新方法
    private void locationUpdate(Location location){
        //获取最新位置信息
        StringBuffer stringBuffer=new StringBuffer();//存储GPS信息
        stringBuffer.append("您的当前位置:"+"\n"+"经度:");
        stringBuffer.append(location.getLongitude());//精度信息
        stringBuffer.append("\n"+"纬度:");
        stringBuffer.append(location.getLatitude());//纬度信息
        gps_text.setText(stringBuffer.toString());

    }
}

你可能感兴趣的:(android)