我有一个使用谷歌地图并具有显示当前位置的功能的 android 应用程序。我收到的评论很少,说“即使 GPS 开启,当前位置也不会出现”。我用几个设备尝试过,但我看不到这个问题,但昨天我在手机上也遇到了这个问题,之前它工作正常。
我想出的解决方案是,如果当前位置没有出现,则关闭 wi-fi 并使用移动互联网获取当前位置并开始显示。我知道这似乎有点奇怪,但它对我有用。如果我遗漏了什么,请建议我对我的代码进行所需的更改。我无法为我的应用用户建议上述解决方法。
locMgr = (LocationManager)getSystemService(Context.LOCATION_SERVICE);
boolean enabled = locMgr.isProviderEnabled(LocationManager.GPS_PROVIDER);
cEnabled = getIntent().getExtras().getBoolean("cEnabled");
if (!enabled && !cEnabled) {
AlertDialog.Builder alt_bld = new AlertDialog.Builder(this);
alt_bld.setMessage("Would you like to activate GPS?\n(recommended- Yes)")
.setCancelable(false)
.setPositiveButton("Yes", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
Intent intent = new Intent(android.provider.Settings.ACTION_LOCATION_SOURCE_SETTINGS);
startActivity(intent);
}
})
.setNegativeButton("No", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
dialog.cancel();
}
});
AlertDialog alert = alt_bld.create();
// Title for AlertDialog
alert.setTitle("Activate GPS?");
// Icon for AlertDialog
alert.setIcon(R.drawable.location1);
alert.show();
}
ImageButton clocButton = (ImageButton) findViewById(R.id.cLoc);
clocButton.setOnTouchListener(new OnTouchListener() {
public boolean onTouch(View v, MotionEvent event) {
getToMyLocation();
return false;
}
});
private void getToMyLocation() {
mapView.invalidate();
Criteria criteria = new Criteria();
String provider = locMgr.getBestProvider(criteria, false);
Location lastLoc = locMgr.getLastKnownLocation(provider);
if(lastLoc != null) {
GeoPoint lastPoint = new GeoPoint((int)(lastLoc.getLatitude()*1E6), (int)(lastLoc.getLongitude()*1E6));
center = lastPoint;
showLocation(lastPoint);
}
else
{
Toast.makeText(mContext, "Waiting for current location", Toast.LENGTH_SHORT).show();
}
myLocOverlay.enableMyLocation();
myLocOverlay.runOnFirstFix(new Runnable() {
public void run() {
GeoPoint loc = myLocOverlay.getMyLocation();
mapView.getController().setCenter(loc);
center = loc;
}
});
}
private void showLocation(GeoPoint location) {
if (location != null) {
myLocOverlay.enableMyLocation();
mapView.getController().animateTo(location);
}
}
我在清单文件中添加了以下权限:
<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_NETWORK_STATE"/>