Android开发之Location定位的基本使用

1、基本UI,上图

2、使用步骤
2.1、基本视图创建一个文本框,两个按钮;
2.2、按钮事件分别加载最佳定位方案与当前位置显示到文本框中;
2.3、使用Location的基本条件:
2.3.1、在AndoirdManifest.xml中申请权限

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

2.3.2、使用Activity的getSystemService()方法获取LocationManager对象,参数为Context.LOCATION_SERVICE;
2.3.3、使用LocationManager的getAllProviders()方法可以获取当前支持的所有定位方式,主要有GPS与Network;
2.3.4、创建Criteria对象及设置各种条件,使用LocationManager的getBestProvider()方法可以自动筛选出当前最佳定位方式;
2.3.5、LocationManager的requestLocationUpdates()方法可以请求定位,定位结果在LocationListener监听器中回调;

3、参考代码
activity_main.xml

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="vertical"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context="com.yusian.location.MainActivity">
 
    <TextView
        android:id="@+id/tv_message"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Hello World!"
        android:textSize="18sp"
        android:padding="10dp"/>
 
    <Button
        android:id="@+id/btn_best_provider"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="定位最佳方案"/>
 
    <Button
        android:id="@+id/btn_get_location"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="获取位置"/>
 
</LinearLayout>

MainActivity

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
package com.yusian.location;
 
import android.Manifest;
import android.content.Context;
import android.content.pm.PackageManager;
import android.location.Criteria;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.support.v4.app.ActivityCompat;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.TextView;
 
import java.util.Iterator;
import java.util.List;
 
public class MainActivity extends AppCompatActivity implements View.OnClickListener{
    private final static String TAG = "SALog";
    private LocationManager locationManager = null;
    private TextView textView = null;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
 
        textView = (TextView) findViewById(R.id.tv_message);
        findViewById(R.id.btn_best_provider).setOnClickListener(this);
        findViewById(R.id.btn_get_location).setOnClickListener(this);
        locationManager = (LocationManager) this.getSystemService(Context.LOCATION_SERVICE);
 
    }
    /*按钮事件处理*/
    @Override
    public void onClick(View v) {
        switch (v.getId()){
            case R.id.btn_best_provider:{
                List<String> list = locationManager.getAllProviders();
                Iterator iterator = list.iterator();
                StringBuilder builder = new StringBuilder();
                while (iterator.hasNext()){
                    String str = (String) iterator.next();
                    builder.append(str+"\n");
                }
                textView.setText(builder.toString());
            }break;
            case R.id.btn_get_location:{
                this.getLocation();
            }break;
            default:break;
        }
    }
    /*获取当前定位信息*/
    public void getLocation(){
        // 权限判断
        Boolean b1 = ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED;
        Boolean b2 = ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED;
        if (b1 && b2) {
            // 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.
            Log.d(TAG, "onCreate: 无定位权限!");
        }
        locationManager.requestLocationUpdates(this.getBestProvider(), 0, 0, new LocationListener() {
            @Override
            public void onLocationChanged(Location location) {
                Log.d(TAG, "onLocationChanged: " + location);
                textView.setText(location.toString());
            }
            @Override
            public void onStatusChanged(String provider, int status, Bundle extras) {
                Log.d(TAG, "onStatusChanged: ");
            }
            @Override
            public void onProviderEnabled(String provider) {
                Log.d(TAG, "onProviderEnabled: ");
            }
            @Override
            public void onProviderDisabled(String provider) {
                Log.d(TAG, "onProviderDisabled: ");
            }
        });
    }
    /*获取最佳定位方案*/
    public String getBestProvider(){
        Criteria criteria = new Criteria();
        criteria.setAccuracy(Criteria.ACCURACY_FINE);
        criteria.setBearingRequired(false);
        criteria.setCostAllowed(false);
        criteria.setPowerRequirement(Criteria.POWER_LOW);
        String provider = locationManager.getBestProvider(criteria, true);
        Log.d(TAG, "getBestProvider: "+provider);
        return provider;
    }
}

One thought on “Android开发之Location定位的基本使用

  1. Sian Post author

    地理编码和反地理编码的基本使用:

    1
    2
    3
    4
    5
    6
    7
    
    try {
        Geocoder geocoder = new Geocoder(MainActivity.this, Locale.CHINA);
        List<Address> addressList = geocoder.getFromLocation(28.1149, 112.5842, 1);
        Log.d(TAG, "onClick: "+addressList);
    } catch (IOException e) {
        e.printStackTrace();
    }
    1
    2
    3
    4
    5
    6
    7
    
    try{
        Geocoder geocoder = new Geocoder(MainActivity.this);
        List<Address> addressList = geocoder.getFromLocationName("北京市海淀区双清路30号", 1);
        Log.d(TAG, "onClick: address "+addressList);
    }catch (IOException e){
        e.printStackTrace();
    }

Leave a Reply