第一步:添加权限
<!-- 权限 -->
<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"/>
<uses-permission android:name="android.permission.ACCESS_WIFI_STATE" />
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
<uses-permission android:name="android.permission.CHANGE_WIFI_STATE" />
第二步:布局
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical" >
<TextView
android:id="@+id/tv"
android:layout_width="match_parent"
android:layout_height="wrap_content"/>
</LinearLayout>
第三步:
package com.example.locationandroidtest;
import java.util.Iterator;
import java.util.List;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.location.Criteria;
import android.location.GpsSatellite;
import android.location.GpsStatus;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.location.LocationProvider;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.provider.Settings;
import android.util.Log;
import android.view.Window;
import android.widget.TextView;
import android.widget.Toast;
public class GpsActivity extends Activity{
private TextView tv = null;
private LocationManager locationManager = null;
private Location location;
private static final String TAG="Gps11111";
private boolean threadDisable = false;
private Handler mHandler;
private final int REFRESH_UI = 1;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
requestWindowFeature(Window.FEATURE_NO_TITLE);
setContentView(R.layout.gps_activity);
tv = (TextView)findViewById(R.id.tv);
locationManager = (LocationManager)getSystemService(Context.LOCATION_SERVICE);
//判断GPS是否正常启动
if(!locationManager.isProviderEnabled(LocationManager.GPS_PROVIDER)){
Toast.makeText(this, "请开启GPS导航...",Toast.LENGTH_SHORT).show();
//返回开启GPS导航的设置界面
Intent intent = new Intent(Settings.ACTION_LOCATION_SOURCE_SETTINGS);
startActivityForResult(intent, 0);
return;
}
location = getLastKnownLocation(locationManager);
//监听状态
locationManager.addGpsStatusListener(listener);
locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 1000,1, locationListener);
mHandler = new Handler(){
public void handleMessage(Message msg) {
switch(msg.what){
case REFRESH_UI:
Bundle data = msg.getData();
Double lat = (Double) data.get("lat");
Double lon = (Double) data.get("lon");
reFreshUI(lat,lon);
break;
default:
break;
}
};
};
}
private LocationListener locationListener = new LocationListener() {
//GPS状态变化时触发
@Override
public void onStatusChanged(String provider, int status, Bundle extras) {
switch (status) {
case LocationProvider.AVAILABLE:
Log.i(TAG,"当前GPS状态为可见状态");
break;
case LocationProvider.OUT_OF_SERVICE:
Log.i(TAG,"当前GPS状态为服务区外状态");
break;
case LocationProvider.TEMPORARILY_UNAVAILABLE:
Log.i(TAG,"当前GPS状态为暂停服务状态");
break;
}
}
//GPS开启时触发
@Override
public void onProviderEnabled(String provider) {
Location location = locationManager.getLastKnownLocation(provider);
reFreshUI(location.getLatitude(),location.getLongitude());
}
//GPS禁用时触发
@Override
public void onProviderDisabled(String provider) {
}
//位置信息变化时触发
@Override
public void onLocationChanged(Location location) {
Log.i(TAG,"时间:"+location.getTime());
Log.i(TAG, "经度:"+location.getLongitude());
Log.i(TAG, "纬度:"+location.getLatitude());
Log.i(TAG, "海拔:"+location.getAltitude());
//更新UI界面
double lat = location.getLatitude();
double lon = location.getLongitude();
Bundle data = new Bundle();
data.putDouble("lat", lat);
data.putDouble("lon", lon);
Message msg = new Message();
msg.setData(data);
msg.what = REFRESH_UI; //发送消息,通知刷新界面
mHandler.sendMessage(msg);
}
};
//状态监听
GpsStatus.Listener listener = new GpsStatus.Listener() {
@Override
public void onGpsStatusChanged(int event) {
switch (event) {
//第一次定位
case GpsStatus.GPS_EVENT_FIRST_FIX:
Log.i(TAG,"第一次定位");
break;
//卫星状态改变
case GpsStatus.GPS_EVENT_SATELLITE_STATUS:
Log.i(TAG,"卫星状态改变");
GpsStatus gpsStatus = locationManager.getGpsStatus(null);
int maxSatellites = gpsStatus.getMaxSatellites();
int count = 0;
Iterator<GpsSatellite> iterator = gpsStatus.getSatellites().iterator();
while(iterator.hasNext() && count <= maxSatellites){
GpsSatellite satellite = iterator.next();
count++;
}
System.out.println("搜索到:" + count + "颗卫星");
break;
case GpsStatus.GPS_EVENT_STARTED:
Log.i(TAG,"定位启动");
break;
case GpsStatus.GPS_EVENT_STOPPED:
Log.i(TAG,"定位结束");
break;
default:
break;
}
}
};
private void reFreshUI(Double lat,Double lon){
if(location != null){
tv.setText("目前经纬度:\n经度:" + lat + "\n纬度:" + lon);
}else{
tv.setText("找不到");
}
}
private Location getLastKnownLocation(LocationManager locationManager) {
Criteria criteria = new Criteria();
//设置定位精确度 Criteria.ACCURACY_COARSE比较粗略,Criteria.ACCURACY_FINE则较细
criteria.setAccuracy(Criteria.ACCURACY_FINE);
//设置是否要求速度
criteria.setSpeedRequired(false);
//设置是否允许运营商收费
criteria.setCostAllowed(false);
//设置是否需要方位信息
criteria.setBearingRequired(false);
//设置是否需要海拔信息
criteria.setAltitudeRequired(false);
//设置对电源的需求
criteria.setPowerRequirement(Criteria.POWER_LOW);
//为获取地理位置信息时设置查询条件
List<String> providers = locationManager.getProviders(criteria, true);
Location bestLocation = null;
for (String provider : providers) {
//如果不设置查询要求,getLastKnownLocation方法传入的参数为LocationManager.GPS_PROVIDER
Location l = locationManager.getLastKnownLocation(provider);
if (l == null) {
continue;
}
if (bestLocation == null || l.getAccuracy() < bestLocation.getAccuracy()) {
// Found best last known location: %s", l);
bestLocation = l;
}
}
return bestLocation;
}
}
参考1:
https://blog.csdn.net/w690333243/article/details/77658303
参考2:
https://www.jb51.net/article/79361.htm
这个完全可放心使用,就是当你获取的经纬度为空的时候,广播接收器接收数据为空,导致ui无法显示
参考3:
https://www.cnblogs.com/powerwu/articles/9228307.html
这个没试过,收藏用