我正在製作一個應用程序,其中我必須顯示1/2秒的啓動畫面。當飛濺加載時,我必須得到用戶的位置。位置的準確性並不值得關注。所以對於這個我已經寫了一個代碼,但我總是從位置得到null。沒有得到的位置
代碼
private Context context;
private LocationManager locationManager;
Location location;
double latitude;
double longitude;
public GetLocation(Context context) {
this.context = context;
getLocation();
}
private Location getLocation() {
locationManager = (LocationManager) context.getSystemService(Context.LOCATION_SERVICE);
location = locationManager.getLastKnownLocation(getProviderName());
if (location == null) {
locationManager.requestLocationUpdates(getProviderName(), 0, 0, this);
}
return location;
}
String getProviderName() {
locationManager = (LocationManager) context
.getSystemService(Context.LOCATION_SERVICE);
Criteria criteria = new Criteria();
criteria.setPowerRequirement(Criteria.POWER_LOW); // Chose your desired power consumption level.
criteria.setAccuracy(Criteria.ACCURACY_FINE); // Choose your accuracy requirement.
criteria.setSpeedRequired(true); // Chose if speed for first location fix is required.
criteria.setAltitudeRequired(false); // Choose if you use altitude.
criteria.setBearingRequired(false); // Choose if you use bearing.
criteria.setCostAllowed(false); // Choose if this provider can waste money :-)
// Provide your criteria and flag enabledOnly that tells
// LocationManager only to return active providers.
return locationManager.getBestProvider(criteria, true);
}
@Override
public void onLocationChanged(Location location) {
Toast.makeText(context,""+location,Toast.LENGTH_LONG).show();
}
@Override
public void onStatusChanged(String provider, int status, Bundle extras) {
Toast.makeText(context,provider,Toast.LENGTH_LONG).show();
}
@Override
public void onProviderEnabled(String provider) {
Toast.makeText(context,provider,Toast.LENGTH_LONG).show();
}
@Override
public void onProviderDisabled(String provider) {
Toast.makeText(context,provider,Toast.LENGTH_LONG).show();
}
public void stopUsingGPS() {
if (locationManager != null) {
locationManager.removeUpdates(this);
}
}
/**
* Function to get latitude
*/
public double getLatitude() {
if (location != null) {
latitude = location.getLatitude();
}
// return latitude
return latitude;
}
/**
* Function to get longitude
*/
public double getLongitude() {
if (location != null) {
longitude = location.getLongitude();
}
// return longitude
return longitude;
}
權限
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" />
使用
private void getLocation() {
getLocation = new GetLocation(contextActivity);
latitude = getLocation.getLatitude();
longitude = getLocation.getLongitude();
if (latitude != 0 && longitude != 0) {
getLocation.stopUsingGPS();
}
}
請你幫助我。 謝謝。
發佈完整的代碼,也檢查對象是否初始化 –
我已更新我的文章 –