Android GPS positioning and examples

To use GPS positioning, first, you need to register the permission to obtain positioning in the manifest file (AndroidManifest.xml):

1. Get the location manager object LocationManager

import android.location.LocationManager;  
    LocationManager lm;  //
     lm =(LocationManager) this.getSystemService(Context`.LOCATION_SERVICE);  //


2. Generally use the getLastKnownLocation(LocationManager.GPS_PROVIDER); method of LocationManager to obtain the Location object

String provider = LocationManager.GPS_PROVIDER;// 指定LocationManager的定位方法
Location location = locationManager.getLastKnownLocation(provider);// 调用getLastKnownLocation()方法获取当前的位置信息

However, this method is not recommended for several reasons:
First, in many applications that provide location services, it is not only necessary to obtain the current location information, but also to monitor the change of the location, and to call a specific processing method when the location changes, Among them, LocationManager provides a convenient and efficient location monitoring method requestLocationUpdates(), which can generate the conditions for location change events according to the distance change and time interval setting of the location, which can avoid a large number of location changes due to small distance changes. event.
Second, when you turn on GPS, the value of provider is GPS. At this time, the positioning method is GPS. Because GPS positioning is slow, it is impossible to return you a Location object immediately, so it returns null.
Regarding this issue, refer to the link:
1.The realization of android positioning

2. An introduction to Android location services, and how to obtain location information through the LocationManager object

3. Android development to obtain GPS location, including several methods of apn\wifi\gps

3.推荐locationManager.requestLocationUpdates();

The code for setting the monitoring location change in the method LocationManager is as follows:

lm.requestLocationUpdates(LocationManager.GPS_PROVIDER, 2000, 10,new MyLocationListener());

Next, we will introduce the parameters of the above line of code. The first parameter is the positioning method we specified for LocationManager before, GPS positioning or network positioning. The second parameter refers to the time interval for generating a location change event, in microseconds. The third parameter refers to the distance condition, in meters, and the fourth parameter is the callback function, which is used to process the location change event, that is, to set the LocationListener listener. Overall, that line of code conditions the generation of a position change event to a distance change of 10 meters with a time interval of 2 seconds.

4. Use the getLongitude() and getLatitude() of the location object to get the latitude and longitude data

tv_01.setText("经度:"+loc.getLongitude());
tv_02.setText("纬度:"+loc.getLatitude());

5. The simple demo code of the specific implementation is as follows

package introduction.android.gpsLocationin;
/*
 * 本工程GPSLocation的功能是使用GPS实时定位,实时显示手机的经纬度
 */
import introduction.android.gpsLocation.R;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.location.LocationListener;
import android.location.LocationManager;  //
import android.location.Location;   //
import android.os.Bundle;
import android.provider.Settings;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.TextView;
import android.widget.Toast;

public class MainActivity extends Activity {
    private Button btn_listen;
    private TextView tv_01,tv_02;
    LocationManager lm;  //
    Location loc;  //

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

        lm =(LocationManager) this.getSystemService(Context.LOCATION_SERVICE);  //
        //检测GPS状态(是否开启)
        if(!lm.isProviderEnabled(LocationManager.GPS_PROVIDER)){  //若未打开GPS
            Toast.makeText(MainActivity.this,"请开启GPS服务",Toast.LENGTH_LONG).show();
            Intent myintent = new Intent(Settings.ACTION_LOCATION_SOURCE_SETTINGS);
            startActivity(myintent);  //运行手机的设置程序
        }   

        btn_listen=(Button) findViewById(R.id.btn_listen);
        tv_01=(TextView) findViewById(R.id.tv_01);
        tv_02=(TextView) findViewById(R.id.tv_02);

        btn_listen.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View v) {
                lm.requestLocationUpdates(LocationManager.GPS_PROVIDER, 0, 0,new MyLocationListener());
            }
        }); 
    }
    //位置监听器方法
    class MyLocationListener implements LocationListener{  //位置监听器,作为方法参数
        @Override
        public void onLocationChanged(Location loc) {
            // TODO Auto-generated method stub
            tv_01.setText("经度:"+loc.getLongitude());
            tv_02.setText("纬度:"+loc.getLatitude());
        }
        @Override
        public void onProviderDisabled(String provider) {
            //当provider被用户关闭时调用
            Log.i("GpsLocation","provider被关闭!");
        }
        @Override
        public void onProviderEnabled(String provider) {
            //当provider被用户开启后调用
            Log.i("GpsLocation","provider被开启!");
        }
        @Override
        public void onStatusChanged(String provider, int status, Bundle extras) {
            //当provider的状态在OUT_OF_SERVICE、TEMPORARILY_UNAVAILABLE和AVAILABLE之间发生变化时调用
            Log.i("GpsLocation","provider状态发生改变!");
        }       
    }
}

6. Get the city location by latitude and longitude

   getPosition(double longitude, double latitude){
        // 通过经纬度获取地址,由于地址会有多个,这个和经纬度精确度有关            
        // 本实例中定义了最大的返回数2,即在集合对象中有两个值
        List<Address> list = null;
        Geocoder ge = new Geocoder(getActivity());
        try {
            list = ge.getFromLocation(latitude, longitude, 2);
        } catch (IOException e) {
            e.printStackTrace();
        }
        if (list !=null && list.size()>0){
            for (int i = 0; i < list.size(); i++){
                Address ad = list.get(i);
                cityName = ad.getLocality();//获取城市
            }
        }
    }


———————————————

Reprinted in: https://blog.csdn.net/Bruce_shan/article/details/50536203

Guess you like

Origin blog.csdn.net/weixin_42602900/article/details/122988213