手機位置獲取(GPS)支援5.0以及上
阿新 • • 發佈:2019-01-09
public class MainActivity extends AppCompatActivity {
private double latitude = 0.0;
private double longitude = 0.0;
private Button info;
private LocationManager myLocationManager;
private Button btRequest;
private TextView tv_Info;
private static final int REQUEST_PERMISSION = 0;
private int GPS_REQUEST_CODE = 10;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
init();
myClick();
}
private void init() {
btRequest = findViewById (R.id.bt_Request);
info = findViewById(R.id.bt_Info);
tv_Info = findViewById(R.id.tv_Info);
myLocationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
}
private void myClick() {
info.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
PackageManager pkgManager = getPackageManager();
// 讀寫 sd card 許可權非常重要, android6.0預設禁止的, 建議初始化之前就彈窗讓使用者賦予該許可權
boolean gpsPermission = pkgManager.checkPermission(android.Manifest.permission.WRITE_EXTERNAL_STORAGE, getPackageName()) == PackageManager.PERMISSION_GRANTED;
if (Build.VERSION.SDK_INT >= 23 && !gpsPermission) {
requestPermission();
} else {
checkGPSIsStart();
}
}
});
}
/**
* 申請許可權
*/
private void requestPermission() {
ActivityCompat.requestPermissions(this,
new String[]{android.Manifest.permission.WRITE_EXTERNAL_STORAGE,
Manifest.permission.READ_PHONE_STATE,
Manifest.permission.ACCESS_FINE_LOCATION},
REQUEST_PERMISSION);
}
@Override
public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions,
@NonNull int[] grantResults) {
super.onRequestPermissionsResult(requestCode, permissions, grantResults);
//回撥,判斷使用者到底點選是還是否。
//如果同時申請多個許可權,可以for迴圈遍歷
if (requestCode == 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
//寫入你需要許可權才能使用的方法
checkGPSIsStart();
} else {
// 沒有獲取 到許可權,從新請求,或者關閉app
Toast.makeText(this, "需要獲得XXX許可權", Toast.LENGTH_SHORT).show();
requestPermission();
}
}
/**
* 判斷當前位置服務是否開啟
* 如果未開啟進行跳轉到設定服務介面,然後延遲進行獲取經緯度
* @return
*/
private void checkGPSIsStart() {
boolean isOpen = false;
isOpen = myLocationManager.isProviderEnabled(LocationManager.GPS_PROVIDER);
if (isOpen) {
getLocation();
} else {
//跳轉GPS設定介面
Intent intent = new Intent(Settings.ACTION_LOCATION_SOURCE_SETTINGS);
startActivityForResult(intent, GPS_REQUEST_CODE);
new Handler() {
}.postDelayed(new Runnable() {
@Override
public void run() {
getLocation();
}
}, 2000);
}
}
/**
* 獲取經緯度進行顯示
*/
private String getLocation() {
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 "";
}
//查詢到位置服務
Criteria criteria=new Criteria();
criteria.setAccuracy(Criteria.ACCURACY_FINE);//高精度
criteria.setAltitudeRequired(false);
criteria.setBearingRequired(false);
criteria.setCostAllowed(true);
criteria.setPowerRequirement(Criteria.POWER_LOW); // 低功耗
String provider = myLocationManager.getBestProvider(criteria,true); // 獲取GPS資訊
Location location = myLocationManager.getLastKnownLocation(provider);
if (location != null) {
latitude = location.getLatitude();
longitude = location.getLongitude();
} else {
myLocationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 1000, 0, myLocationListener);
}
return "緯度:" + latitude + "\n" + "經度:" + longitude;
}
/**
*獲取GPS位置監聽器,包含四個不同觸發方式
*/
LocationListener myLocationListener = new LocationListener() {
// Provider的狀態在可用、暫時不可用和無服務三個狀態直接切換時觸發此函式
@Override
public void onStatusChanged(String provider, int status, Bundle extras) {
}
// 當位置獲取(GPS)開啟時呼叫此方法
@Override
public void onProviderEnabled(String provider) {
Log.d("執行,GPS的開啟", provider);
}
// 當位置獲取(GPS)關閉時呼叫此方法
@Override
public void onProviderDisabled(String provider) {
Log.d("執行,GPS關閉", provider);
}
// 當座標改變時觸發此方法,如果獲取到相同座標,它就不會被觸發
@Override
public void onLocationChanged(Location location) {
if (location != null) {
latitude = location.getLatitude(); // 經度
longitude = location.getLongitude(); // 緯度
Log.d("執行,座標發生改變", "Lat: " + location.getLatitude() + " Lng: " + location.getLongitude());
}
}
};
}
遠端門,已上傳git:https://github.com/kyzgxiaoguo/AzGetGPS_master/tree/master