安卓开发入门gps获取定位经纬度海拔速度

layout xml 文件

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:paddingBottom="68dp"
    android:paddingLeft="68dp"
    android:paddingRight="68dp"
    android:paddingTop="68dp"
    tools:context="com.example.location2.MainActivity">


    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:textAppearance="?android:attr/textAppearanceMedium"
        android:text="经纬度"
        android:id="@+id/tvLag"
        android:layout_alignParentTop="true"
        android:layout_alignParentStart="true"
        android:layout_alignParentLeft="true" />

    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:textAppearance="?android:attr/textAppearanceMedium"
        android:text="海拔"
        android:id="@+id/tvAlt"
        android:layout_below="@+id/tvLag"
        android:layout_alignParentStart="true"
        android:layout_marginTop="10dp"
        android:layout_alignParentLeft="true" />

    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:textAppearance="?android:attr/textAppearanceMedium"
        android:text="速度"
        android:id="@+id/tvSpeed"
        android:layout_below="@+id/tvAlt"
        android:layout_alignParentStart="true"
        android:layout_marginTop="10dp"
        android:layout_alignParentLeft="true" />

</RelativeLayout>

MainActivity类代码

import android.Manifest;
import android.content.Context;
import android.content.Intent;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.provider.Settings;
import androidx.appcompat.app.AppCompatActivity;
import android.os.Bundle;
import android.widget.TextView;
import android.widget.Toast;
import android.os.Build;
import android.content.pm.PackageManager;

public class MainActivity extends AppCompatActivity {
    private String[] perms = {Manifest.permission.ACCESS_FINE_LOCATION};
    private final int PERMS_REQUEST_CODE = 200;
    private TextView tvLag,tvAlt,tvSpeed;
    private LocationManager lm = null;
    private Location mLocation;
    private MyLocationListner mLocationListner;




    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        tvLag = (TextView) findViewById(R.id.tvLag);
        tvAlt = (TextView) findViewById(R.id.tvAlt);
        tvSpeed = (TextView) findViewById(R.id.tvSpeed);

        lm = (LocationManager)getSystemService(Context.LOCATION_SERVICE);
        //Android 6.0以上版本需要临时获取权限
        if(Build.VERSION.SDK_INT>Build.VERSION_CODES.LOLLIPOP_MR1&&
                PackageManager.PERMISSION_GRANTED!=checkSelfPermission(perms[0])) {
            requestPermissions(perms,PERMS_REQUEST_CODE);
        }else{
            initLocation();
        }
    }
    private void initLocation(){
        //判断GPS是否正常启动
        if(!lm.isProviderEnabled(LocationManager.GPS_PROVIDER)){
            Toast.makeText(MainActivity.this, "请开启GPS...",Toast.LENGTH_SHORT);
            //返回开启GPS导航设置界面
            Intent intent = new Intent(Settings.ACTION_LOCATION_SOURCE_SETTINGS);
            startActivityForResult(intent,0);
            return;
        }

        if (mLocationListner == null)
        {
            mLocationListner = new MyLocationListner();
        }

        try{
            mLocation = lm.getLastKnownLocation(lm.GPS_PROVIDER);
            updateView(mLocation);
        }catch (SecurityException se){
        }

        try{
             /**
         * 开启定位监听变化
         * 参数1,定位方式:主要有GPS_PROVIDER和NETWORK_PROVIDER,前者是GPS,后者是GPRS以及WIFI定位
         * 参数2,位置信息更新周期.单位是毫秒
         * 参数3,位置变化最小距离:当位置距离变化超过此值时,将更新位置信息
         * 参数4,监听
         * 备注:参数2和3,如果参数3不为0,则以参数3为准;参数3为0,则通过时间来定时更新;两者为0,则随时刷新
         */
            lm.requestLocationUpdates(LocationManager.GPS_PROVIDER, 3000, 1, mLocationListner);
        }catch (SecurityException se){
        }

    }

    private class MyLocationListner implements LocationListener
    {
        @Override
        public void onLocationChanged(Location location)
        {
            updateView(location);
        }
        @Override
        public void onProviderDisabled(String provider)
        {
            updateView(null);
        }
        @Override
        public void onProviderEnabled(String provider)
        {
            try{
                updateView(lm.getLastKnownLocation(provider));
            }catch (SecurityException e){}
        }
        @Override
        public void onStatusChanged(String provider, int status, Bundle extras)
        {

        }
    }

    private void updateView(Location location)
    {
        if (location!=null) {
            tvLag.setText("经度:"+location.getLongitude()+"\n"+"纬度:"+location.getLatitude());
            tvAlt.setText("当前海拔:" + location.getAltitude() + "m");
            tvSpeed.setText("当前速度:" + location.getSpeed() + "m/s");
        }else{
            tvLag.setText("经度:"+"纬度:");
            tvAlt.setText("当前海拔:" );
            tvSpeed.setText("当前速度:");
        }
    }

    @Override
    public void onRequestPermissionsResult(int permsRequestCode, String[] permissions, int[] grantResults){
        switch(permsRequestCode){
            case PERMS_REQUEST_CODE:
                boolean storageAccepted = grantResults[0] == PackageManager.PERMISSION_GRANTED;
                if(storageAccepted){
                    initLocation();
                }
                break;

        }
    }


}

getFromLocation类
address.getAddressLine(0)详细地址
address.getFeatureName()所在小区街道
address.getCountryName()所在国家
address.getLocality()所在城市

 Address[addressLines=[0:"贵州省xx市xx区xx小区"],feature=xx小区,admin=贵州省,sub-admin=xx街道,locality=xx市,thoroughfare=xx路,postalCode=null,countryCode=CN,countryName=中国,hasLatitude=true,latitude=xx,hasLongitude=true,longitude=xx,phone=null,url=null,extras=Bundle[mParcelledData.dataSize=92]]

参考文献:开发实战Android Studio从零基础到App上线 欧阳燊 清华大学出版社

  • 0
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

pinkrecall2012

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值