我想通过 GPS 在谷歌地图上找到我当前的位置,但问题是它应该搜索当前位置直到特定的时间量,例如 30 秒,30 秒后 GPS 应该停止搜索或 GPS 应该自动停止。
然后我想将当前位置点保存为经度和经度。我的代码是这样的:-
//on create
ConnectivityManager cm = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo netInfo = cm.getActiveNetworkInfo();
if (netInfo != null && netInfo.isConnected()) {
lmngr = (LocationManager)getSystemService(Context.LOCATION_SERVICE);
llstnr = new MyLocationListener();
Criteria criteria = new Criteria();
provider = lmngr.getBestProvider(criteria, false);
Location location = lmngr.getLastKnownLocation(provider);
if (location != null) {
lmngr.requestLocationUpdates(LocationManager.GPS_PROVIDER,0,0,llstnr);
} else {
Toast.makeText(getApplicationContext(), "No location found", Toast.LENGTH_LONG).show();
}
//Toast.makeText(getApplicationContext(), "Connection", Toast.LENGTH_LONG).show();
}
else{
AlertDialog.Builder alertDialogBuilder = new AlertDialog.Builder(this);
alertDialogBuilder.setTitle("Check Connection");
alertDialogBuilder
.setMessage("No internet Connection Do U Want To Exit ?")
.setCancelable(false)
.setPositiveButton("Yes",new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog,int id) {
Nissan_Map_Final.this.finish();
}
})
.setNegativeButton("No",new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog,int id) {
// if this button is clicked, just close
// the dialog box and do nothing
dialog.cancel();
}
});
AlertDialog alertDialog = alertDialogBuilder.create();
alertDialog.show();
// Toast.makeText(getApplicationContext(), "No Connection", Toast.LENGTH_LONG).show();
}
我的位置监听器类:-
公共类 MyLocationListener 实现 LocationListener {
@Override
public void onLocationChanged(Location location) {
// TODO Auto-generated method stub
GeoPoint p = new GeoPoint((int) (location.getLatitude() * 1E6),(int) (location.getLongitude() * 1E6));
int cur_lati = (int)location.getLatitude();
int cur_longi = (int)location.getLongitude();
float accuracy = location.getAccuracy();
String add = " ";
p = new GeoPoint((int) (cur_lati * 1E6),(int) (cur_longi * 1E6));
mc = mapView.getController();
mc.animateTo(p);
mc.setZoom(18);
Geocoder geoCoder = new Geocoder(getBaseContext(), Locale.getDefault());
try {
List<Address> addresses = geoCoder.getFromLocation(
p.getLatitudeE6() / 1E6,
p.getLongitudeE6() / 1E6, 1);
if (addresses.size() > 0)
{
for (int i=0; i<addresses.get(0).getMaxAddressLineIndex();i++)
add += addresses.get(0).getAddressLine(i) ;
}
}
catch (IOException e) {
e.printStackTrace();
}
cur_loc.setText("Your Accuracy: " + accuracy + "\n" + "Address is:" + location.getLatitude() + "" + location.getLongitude());
}
@Override
public void onProviderDisabled(String provider) {
// TODO Auto-generated method stub
}
@Override
public void onProviderEnabled(String provider) {
// TODO Auto-generated method stub
}
@Override
public void onStatusChanged(String provider, int status, Bundle extras) {
// TODO Auto-generated method stub
lmngr.removeUpdates(llstnr);
}
}