获取当前设备的经纬度

时间:2022-02-04 19:51:54

1、获取定位管理者,这是一个系统级的服务
 2、请求定位更新,这里设置网络/GPS定位,定位监听器
 3、定位监听器中可以获取到定位对象,其中包括经纬度等信息

布局:

 1 <?xml version="1.0" encoding="utf-8"?>
2 <LinearLayout
3 xmlns:android="http://schemas.android.com/apk/res/android"
4 xmlns:app="http://schemas.android.com/apk/res-auto"
5 xmlns:tools="http://schemas.android.com/tools"
6 android:layout_width="match_parent"
7 android:layout_height="match_parent"
8 android:orientation="vertical"
9 tools:context="net.bwie.locationandsessior.MainActivity">
10
11 <Button
12 android:id="@+id/location_btn"
13 android:layout_width="wrap_content"
14 android:layout_height="wrap_content"
15 android:text="定位"/>
16
17 <TextView
18 android:id="@+id/result_tv"
19 android:text="结果"
20 android:layout_width="wrap_content"
21 android:layout_height="wrap_content"/>
22
23
24 </LinearLayout>

Activity:

 1 public class MainActivity extends AppCompatActivity implements
2 View.OnClickListener, LocationListener {
3
4 protected Button mLocationBtn;
5 protected TextView mResultTv;
6 private LocationManager mLocationManager;
7
8 @Override
9 protected void onCreate(Bundle savedInstanceState) {
10 super.onCreate(savedInstanceState);
11 super.setContentView(R.layout.activity_main);
12 initView();
13 }
14
15 private void initView() {
16 mLocationBtn = (Button) findViewById(R.id.location_btn);
17 mLocationBtn.setOnClickListener(MainActivity.this);
18 mResultTv = (TextView) findViewById(R.id.result_tv);
19 }
20
21 @Override
22 public void onClick(View view) {
23 if (view.getId() == R.id.location_btn) {
24 locate();
25 }
26 }
27
28 // 定位
29 private void locate() {
30 // 定位管理者
31 mLocationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
32 // NETWORK_PROVIDER:使用网络定位(粗略定位)
33 // GPS_PROVIDER:使用GPS定位(精准定位)
34 mLocationManager.requestLocationUpdates(LocationManager.NETWORK_PROVIDER, 200, 200, this);
35 }
36
37 // 获取当前设备的经纬度
38 @Override
39 public void onLocationChanged(Location location) {
40 double latitude = location.getLatitude();// 纬度
41 double longitude = location.getLongitude();// 经度
42
43 mResultTv.setText("纬度:" + latitude + ",经度:" + longitude);
44 }
45
46 @Override
47 public void onStatusChanged(String provider, int status, Bundle extras) {
48
49 }
50
51 @Override
52 public void onProviderEnabled(String provider) {
53
54 }
55
56 @Override
57 public void onProviderDisabled(String provider) {
58
59 }
60 }

权限:

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

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

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