Android中獲取定位經緯度信息


場景

根據GPS獲取經緯度效果

 

 

注:

博客:
https://blog.csdn.net/badao_liumang_qizhi
關注公眾號
霸道的程序猿
獲取編程相關電子書、教程推送與免費下載。

實現

修改頁面布局代碼activity_main.xml,在頁面上添加一個TextView來顯示經緯度信息。

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context=".MainActivity">


    <TextView
        android:id="@+id/location"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_centerHorizontal="true"
        android:textStyle="bold" />
</RelativeLayout>

然后打開MainActivity.java,修改代碼如下

package com.badao.servicetest;

import androidx.appcompat.app.AppCompatActivity;
import androidx.core.app.ActivityCompat;

import android.Manifest;
import android.content.pm.PackageManager;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.os.Bundle;
import android.view.WindowManager;
import android.widget.TextView;

public class MainActivity extends AppCompatActivity {

    private TextView text;  //定義用於顯示LocationProvider的TextView組件

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,
                WindowManager.LayoutParams.FLAG_FULLSCREEN);   //設置全屏顯示

        text = (TextView) findViewById(R.id.location);  //獲取顯示Location信息的TextView組件
        //獲取系統的LocationManager對象
        LocationManager 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;
        }
        //設置每一秒獲取一次location信息
        locationManager.requestLocationUpdates(
                LocationManager.GPS_PROVIDER,      //GPS定位提供者
                1000,       //更新數據時間為1秒
                1,      //位置間隔為1米
                //位置監聽器
                new LocationListener() {  //GPS定位信息發生改變時觸發,用於更新位置信息

                    @Override
                    public void onLocationChanged(Location location) {
                        //GPS信息發生改變時,更新位置
                        locationUpdates(location);
                    }

                    @Override
                    //位置狀態發生改變時觸發
                    public void onStatusChanged(String provider, int status, Bundle extras) {
                    }

                    @Override
                    //定位提供者啟動時觸發
                    public void onProviderEnabled(String provider) {
                    }

                    @Override
                    //定位提供者關閉時觸發
                    public void onProviderDisabled(String provider) {
                    }
                });
        //從GPS獲取最新的定位信息
        Location location = locationManager.getLastKnownLocation(LocationManager.GPS_PROVIDER);
        locationUpdates(location);    //將最新的定位信息傳遞給創建的locationUpdates()方法中
    }

    public void locationUpdates(Location location) {  //獲取指定的查詢信息
        //如果location不為空時
        if (location != null) {
            StringBuilder stringBuilder = new StringBuilder();        //使用StringBuilder保存數據
            //獲取經度、緯度、等屬性值
            stringBuilder.append("您的位置信息:\n");
            stringBuilder.append("經度:");
            stringBuilder.append(location.getLongitude());
            stringBuilder.append("\n緯度:");
            stringBuilder.append(location.getLatitude());
//            stringBuilder.append("\n精確度:");
//            stringBuilder.append(location.getAccuracy());
//            stringBuilder.append("\n高度:");
//            stringBuilder.append(location.getAltitude());
//            stringBuilder.append("\n方向:");
//            stringBuilder.append(location.getBearing());
//            stringBuilder.append("\n速度:");
//            stringBuilder.append(location.getSpeed());
//            stringBuilder.append("\n時間:");
//            SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH mm ss");    //設置日期時間格式
//            stringBuilder.append(dateFormat.format(new Date(location.getTime())));
            text.setText(stringBuilder);            //顯示獲取的信息
        } else {
            //否則輸出空信息
            text.setText("沒有獲取到GPS信息");
        }
    }
}

 

最后打開AndroidMainfest.xml添加權限

    <uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION"/>
    <uses-permission android:name="android.permission.ACCESS_FINE_LOCATION"/>

 

添加位置如下

 

 

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM