Android to get the latitude and longitude of the phone

Create my application

* Get the LocationManager instance, and pass in the Context.LOCATION_SERVICE parameter through the getSystemService method.
* Get available location providers, there are three types GPS_PROVIDER, NETWORK_PROVIDER, PASSIVE_PROVIDER, the first two are more commonly used.
* Pass the obtained location provider to the LocationManager method getLastKnownLocation to obtain Location information.
If the geographic location of the mobile device continues to change, the real-time update requires the following steps:
* Call the locationManager requestLocationUpdates method, the first parameter is the location provider, the second parameter is the time interval (ms) to monitor the location change, the third One parameter is the distance interval (meters) for monitoring the location change, and the fourth parameter is the LocationListener listener.
When the location changes, the onLocationChanged method of the listener will be called.
* In order to save power and save resources, when the program is closed, call the RemoveUpdates method of LocationManager to remove the listener.

The specific steps are as follows

Open android studio, select [close],
Insert picture description here
Insert picture description here

Write the following permissions in AndroidManfest.xml, pay attention to the application.

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

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

3. Write the following code in activity_main.xml in the layout under res

<TextView
    android:id="@+id/positionView"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    />

MainActivity:

package com.example.myapplication;

import android.Manifest;
import android.content.pm.PackageManager;
import android.support.v4.app.ActivityCompat;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;

import android.app.Activity;
import android.content.Context;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.os.Bundle;
import android.view.Menu;
import android.widget.TextView;
import android.widget.Toast;

import java.util.List;

public class MainActivity extends Activity {

private TextView postionView;

private LocationManager locationManager;
private String locationProvider;

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

    //获取显示地理位置信息的TextView
    postionView = (TextView) findViewById(R.id.positionView);
    //获取地理位置管理器
    locationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
    //获取所有可用的位置提供器
    List<String> providers = locationManager.getProviders(true);
    if (providers.contains(LocationManager.GPS_PROVIDER)) {
        //如果是GPS
        locationProvider = LocationManager.GPS_PROVIDER;
    } else if (providers.contains(LocationManager.NETWORK_PROVIDER)) {
        //如果是Network
        locationProvider = LocationManager.NETWORK_PROVIDER;
    } else {
        Toast.makeText(this, "没有可用的位置提供器", Toast.LENGTH_SHORT).show();
        return;
    }
    //获取Location
    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 location = locationManager.getLastKnownLocation(locationProvider);
    if (location != null) {
        //不为空,显示地理位置经纬度
        showLocation(location);
    }
    //监视地理位置变化
    locationManager.requestLocationUpdates(locationProvider, 3000, 1, locationListener);

}

/**
 * 显示地理位置经度和纬度信息
 * @param location
 */
private void showLocation(Location location) {
    String locationStr = "纬度:" + location.getLatitude() + "\n"
            + "经度:" + location.getLongitude();
    postionView.setText(locationStr);
}

/**
 * LocationListern监听器
 * 参数:地理位置提供器、监听位置变化的时间间隔、位置变化的距离间隔、LocationListener监听器
 */

LocationListener locationListener = new LocationListener() {

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

    }

    @Override
    public void onProviderEnabled(String provider) {

    }

    @Override
    public void onProviderDisabled(String provider) {

    }

    @Override
    public void onLocationChanged(Location location) {
        //如果位置发生变化,重新显示
        showLocation(location);

    }
};

@Override
protected void onDestroy() {
    super.onDestroy();
    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) {
            // 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.removeUpdates(locationListener);
    }
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
    // Inflate the menu; this adds items to the action bar if it is present.
    getMenuInflater().inflate(R.menu.main, menu);
    return true;
}

}
Project List
Insert picture description here

operation result:

Insert picture description here

Published 9 original articles · liked 0 · visits 922

Guess you like

Origin blog.csdn.net/weixin_46146588/article/details/105568879