android 獲取地理位置時為null
阿新 • • 發佈:2019-02-11
發現有很多android 手機獲取地理位置,很多時候都不一定能夠獲取到,並且不一定準確,因為那個位置都是上次獲取的時候拿到的,得更新。具體實現程式碼如下
import android.app.Activity;
import android.content.pm.PackageManager;
import android.location.Criteria;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.location.LocationProvider;
import android.os.Bundle;
import android.widget.TextView;
import java.util.Iterator;
import java.util.List;
public class LocationBase extends Activity {
private TextView myText;
private String textStr = "";
private LocationManager mgr = null;
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
addText("Location Based-Services Demo...");
//步驟 1: 獲取系統的定位管理器
mgr = (LocationManager) getSystemService(LOCATION_SERVICE);
addText("get system Location Manager " + mgr);
}
//步驟2.2 持續跟蹤中的停止update:在本例中,我們要求不斷獲得位置更新,我們必須在人工進行removeUpdates(),否則即使應用中所有的Activity都關閉,App仍繼續在不斷更新位置資訊,導致應用資源無法被回收
protected void onPause() {
super.onPause();
PackageManager pm = getPackageManager();
boolean permissionFine = (PackageManager.PERMISSION_GRANTED == pm.checkPermission("android.permission.ACCESS_FINE_LOCATION", getPackageName()));
boolean permissionCoarse = (PackageManager.PERMISSION_GRANTED == pm.checkPermission("android.permission.ACCESS_COARSE_LOCATION", getPackageName()));
if (permissionFine == true && permissionCoarse == true) {
mgr.removeUpdates(onLocationChange);
}
addText("Remove Updates...");
}
//步驟2:設定持續跟蹤
//步驟 2.1(1) :我們在onResume()中持續跟蹤,相應的在onPause()中關閉出現跟蹤。我們只在Activity執行時進行跟蹤。具體見Activity的生命週期
protected void onResume() {
super.onResume();
mgr.addTestProvider(LocationManager.NETWORK_PROVIDER,
"requiresNetwork" == "", "requiresSatellite" == "", "requiresCell" == "", "hasMonetaryCost" == "",
"supportsAltitude" == "", "supportsSpeed" == "",
"supportsBearing" == "", android.location.Criteria.POWER_LOW,
android.location.Criteria.ACCURACY_FINE);
mgr.setTestProviderEnabled(LocationManager.NETWORK_PROVIDER, true);
PackageManager pm = getPackageManager();
boolean permissionFine = (PackageManager.PERMISSION_GRANTED == pm.checkPermission("android.permission.ACCESS_FINE_LOCATION", getPackageName()));
boolean permissionCoarse = (PackageManager.PERMISSION_GRANTED == pm.checkPermission("android.permission.ACCESS_COARSE_LOCATION", getPackageName()));
addText("Request Updates automatically ...");
List<String> list = mgr.getAllProviders(); //mgr即LocationManager
for (Iterator<String> i = list.iterator(); i.hasNext(); ) {
System.out.println("\t" + i.next());
}
Criteria criteria = new Criteria();
String providerName = mgr.getBestProvider(criteria, true /*enabledOnly*/); //criteria不能填null,否則出現異常
LocationProvider provider = mgr.getProvider(providerName);
location = mgr.getLastKnownLocation(providerName);
if (permissionFine == true && permissionCoarse == true) {
//步驟2.1 (2):由於人的位置是不斷變化,我要設定一個位置變化的範圍,包括同時滿足最小的時間間隔和最小的位移變化,如果兩個條件要同時滿足,將位置監聽器將被觸發。實際上該方法有多個引數格式,特別是requestLocationUpdates (long minTime, float minDistance, Criteria criteria,PendingIntent intent),當位置變化時可呼叫其他的Activity。 在本例中,我們制定用GPS,則在許可權中必須要求精確定位許可。
while(location == null) {
mgr.requestLocationUpdates(LocationManager.NETWORK_PROVIDER, 100/*10秒,為測試方便*/, 0.1f/*1公里*/, onLocationChange/*位置監聽器*/);
}
}
if (location != null)
System.out.println("Get Location from " + providerName + " : " + location.getLatitude() + "," + location.getLongitude());
}
Location location;
//步驟3:位置監聽器LocationListener 的設定,當位置發生變化是觸發onLocationChanged( )
LocationListener onLocationChange = new LocationListener() {
public void onLocationChanged(Location location2) {
location = location2;
addText("Location Changed : (" + location.getLongitude() + "," + location.getLatitude() + ")");
}
public void onProviderDisabled(String arg0) {
addText("onProviderDisabled");
}
public void onProviderEnabled(String arg0) {
addText("onProviderEnabled");
}
public void onStatusChanged(String arg0, int arg1, Bundle arg2) {
addText("onStatusChanged");
}
};
private void addText(String s) {
textStr = textStr.concat(s + "\n\n");
myText.setText(textStr);
}
}