locationManager.requestLocationUpdates(LocationManager.NETWORK_PROVIDER, 0, 0, locationListener);
locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 0, 0, locationListener);
Как вы можете видеть в Або ve code, вы назначаете двух разных провайдеров одному locationManager и тому же locationListener.
Эта реализация приводит к данным, полученным от GPS_Provider
, а не от сети.
Попробуйте использовать двух разных менеджеров местоположения и разных локальных пользователей, чтобы получить результаты от обоих поставщиков.
public class MainActivity extends Activity implements
GooglePlayServicesClient.ConnectionCallbacks,
GooglePlayServicesClient.OnConnectionFailedListener {
protected static final int START_GPS_SETTINGS = 1;
GoogleMap googleMap;
Dialog alertDialog = null;
LocationManager locationManager = null;
LocationManager GPSlocationManager = null;
LocationManager NetworklocationManager = null;
private LocationClient locationclient;
Location location;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
if (GooglePlayServicesUtil.isGooglePlayServicesAvailable(this) == ConnectionResult.SUCCESS) {
locationclient = new LocationClient(this, this, this);
locationclient.connect();
} else {
Toast.makeText(
this,
"Google Play Service Error "
+ GooglePlayServicesUtil
.isGooglePlayServicesAvailable(this),
Toast.LENGTH_LONG).show();
}
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
@Override
protected void onStart() {
// TODO Auto-generated method stub
super.onStart();
googleMap = ((MapFragment) getFragmentManager().findFragmentById(
R.id.mapFragment)).getMap();
if (googleMap != null) {
googleMap.setMyLocationEnabled(true);
googleMap.getUiSettings().setZoomControlsEnabled(true);
googleMap.getUiSettings().setMyLocationButtonEnabled(true);
googleMap.getUiSettings().setAllGesturesEnabled(true);
}
}
public void locateMe(View view) {
checkforGPS();
}
private void checkforGPS() {
// checking whether the gps is enabled on the device or not
if (!((LocationManager) this.getSystemService(Context.LOCATION_SERVICE))
.isProviderEnabled(LocationManager.GPS_PROVIDER)) {
// GPS is not enabled
// 1. Instantiate an AlertDialog.Builder with its constructor
AlertDialog.Builder builder = new AlertDialog.Builder(this);
// 2. Chain together various setter methods to set the dialog
// characteristics
builder.setMessage(R.string.generic_gps_not_found)
.setTitle(R.string.generic_gps_not_found_message_title)
.setPositiveButton(R.string.generic_ok,
new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog,
int id) {
// User selected yes
Intent intent = new Intent(
Settings.ACTION_LOCATION_SOURCE_SETTINGS);
startActivityForResult(intent,
START_GPS_SETTINGS);
}
});
// 3. Get the AlertDialog from create()
AlertDialog dialog = builder.create();
dialog.setCancelable(false);
dialog.show();
} else {
// GPS is enabled
startGettingLocation();
}
}
public void captureImage(View view) {
}
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (resultCode == RESULT_CANCELED) {
switch (requestCode) {
case START_GPS_SETTINGS:
startGettingLocation();
break;
}
}
}
private void startGettingLocation() {
getLocationFromLocationClient();
getLocationFromNetworkPriver();
getLocationFromGPSPriver();
final Handler handler1 = new Handler();
handler1.postDelayed(new Runnable() {
@Override
public void run() {
// Do something after 3000ms
showDialogBox();
getLocation();
}
}, 20000);
}
public void animateGoogleMap() {
if (location != null && googleMap != null) {
LatLng latLng = new LatLng(location.getLatitude(),
location.getLongitude());
googleMap.moveCamera(CameraUpdateFactory.newLatLng(latLng));
googleMap.animateCamera(CameraUpdateFactory.zoomTo(17));
// googleMap.moveCamera(CameraUpdateFactory.newLatLng(latLng));
googleMap.addMarker(new MarkerOptions().position(latLng).icon(
BitmapDescriptorFactory
.fromResource(R.drawable.trip_start_icon)));
} else {
// Something went wrong.
// Restarting the activity
reload();
}
}
/**
* code for getting the current location
*/
private void showDialogBox() {
alertDialog = new Dialog(this);
alertDialog.setCanceledOnTouchOutside(false);
alertDialog.setCancelable(false);
alertDialog.setTitle("Location Updates....");
LayoutInflater layoutInflater = (LayoutInflater) getSystemService(Context.LAYOUT_INFLATER_SERVICE);
View v = layoutInflater.inflate(R.layout.dialog_layout, null);
// Setting Dialog Title
((TextView) v.findViewById(R.id.header))
.setText("Location Updates....");
// Setting Dialog Message
((TextView) v.findViewById(R.id.text_msg))
.setText("Please wait for updates");
// Showing Alert Message
alertDialog.setContentView(v);
alertDialog.show();
}
private void getLocation() {
locationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
Criteria criteria = new Criteria();
criteria.setAccuracy(Criteria.ACCURACY_COARSE);
String provider = locationManager.getBestProvider(criteria, false);
Log.e("provider", provider);
locationManager.requestLocationUpdates(provider, 1000, 1,
myLocationListener);
}
private LocationListener myLocationListener = new LocationListener() {
@Override
public void onStatusChanged(String provider, int status, Bundle extras) {
// TODO Auto-generated method stub
}
@Override
public void onProviderEnabled(String provider) {
// TODO Auto-generated method stub
}
@Override
public void onProviderDisabled(String provider) {
// TODO Auto-generated method stub
}
@Override
public void onLocationChanged(Location locationBest) {
if (locationBest == null)
return;
Log.e("Best Provider", "Best Provider");
Log.e("latitude", locationBest.getLatitude() + "");
Log.e("longitude", locationBest.getLongitude() + "");
Log.e("accuracy", locationBest.getAccuracy() + "");
removeLocationUpdatesAndAddMarker(locationBest);
}
};
private LocationListener myGPSLocationListener = new LocationListener() {
@Override
public void onStatusChanged(String provider, int status, Bundle extras) {
// TODO Auto-generated method stub
}
@Override
public void onProviderEnabled(String provider) {
// TODO Auto-generated method stub
}
@Override
public void onProviderDisabled(String provider) {
// TODO Auto-generated method stub
}
@Override
public void onLocationChanged(Location locationGPS) {
if (locationGPS == null)
return;
Log.e("GPS Provider", "GPS Provider");
Log.e("latitude", locationGPS.getLatitude() + "");
Log.e("longitude", locationGPS.getLongitude() + "");
Log.e("accuracy", locationGPS.getAccuracy() + "");
removeLocationUpdatesAndAddGPSMarker(locationGPS);
}
};
private LocationListener myNetworkLocationListener = new LocationListener() {
@Override
public void onStatusChanged(String provider, int status, Bundle extras) {
// TODO Auto-generated method stub
}
@Override
public void onProviderEnabled(String provider) {
// TODO Auto-generated method stub
}
@Override
public void onProviderDisabled(String provider) {
// TODO Auto-generated method stub
}
@Override
public void onLocationChanged(Location locationNetwork) {
if (locationNetwork == null)
return;
Log.e("Network Provider", "Network Provider");
Log.e("latitude", locationNetwork.getLatitude() + "");
Log.e("longitude", locationNetwork.getLongitude() + "");
Log.e("accuracy", locationNetwork.getAccuracy() + "");
removeLocationUpdatesAndAddNetworkMarker(locationNetwork);
}
};
private void removeLocationUpdatesAndAddMarker(
Location locationFromBestLocationProvider) {
// Removing the listener from giving the location
if (locationManager != null) {
locationManager.removeUpdates(myLocationListener);
locationManager = null;
}
WriteLogToFile.appendLog(
this.getString(R.string.app_name),
"BestProvider",
"BestProvider",
"Location :\n" + "Latitude:"
+ locationFromBestLocationProvider.getLatitude()
+ "\nLongitude:"
+ locationFromBestLocationProvider.getLongitude()
+ "\nAccuracy:"
+ locationFromBestLocationProvider.getAccuracy());
location = locationFromBestLocationProvider;
if (alertDialog != null)
alertDialog.dismiss();
animateGoogleMap();
}
private void removeLocationUpdatesAndAddGPSMarker(Location locationFromGPS) {
if (GPSlocationManager != null) {
GPSlocationManager.removeUpdates(myGPSLocationListener);
GPSlocationManager = null;
}
WriteLogToFile.appendLog(this.getString(R.string.app_name), "GPS",
"GPS",
"Location :\n" + "Latitude:" + locationFromGPS.getLatitude()
+ "\nLongitude:" + locationFromGPS.getLongitude()
+ "\nAccuracy:" + locationFromGPS.getAccuracy());
LatLng latLng = new LatLng(locationFromGPS.getLatitude(),
locationFromGPS.getLongitude());
googleMap.moveCamera(CameraUpdateFactory.newLatLng(latLng));
googleMap.animateCamera(CameraUpdateFactory.zoomTo(17));
// googleMap.moveCamera(CameraUpdateFactory.newLatLng(latLng));
googleMap.addMarker(new MarkerOptions().position(latLng).icon(
BitmapDescriptorFactory.fromResource(R.drawable.gps_provider)));
}
private void removeLocationUpdatesAndAddNetworkMarker(
Location locationFromNetwork) {
if (NetworklocationManager != null) {
NetworklocationManager.removeUpdates(myNetworkLocationListener);
NetworklocationManager = null;
}
WriteLogToFile.appendLog(
this.getString(R.string.app_name),
"Network",
"Network",
"Location :\n" + "Latitude:"
+ locationFromNetwork.getLatitude() + "\nLongitude:"
+ locationFromNetwork.getLongitude() + "\nAccuracy:"
+ locationFromNetwork.getAccuracy());
LatLng latLng = new LatLng(locationFromNetwork.getLatitude(),
locationFromNetwork.getLongitude());
googleMap.moveCamera(CameraUpdateFactory.newLatLng(latLng));
googleMap.animateCamera(CameraUpdateFactory.zoomTo(17));
// googleMap.moveCamera(CameraUpdateFactory.newLatLng(latLng));
googleMap.addMarker(new MarkerOptions().position(latLng).icon(
BitmapDescriptorFactory
.fromResource(R.drawable.network_provider)));
}
public void reload() {
Intent intent = getIntent();
overridePendingTransition(0, 0);
intent.addFlags(Intent.FLAG_ACTIVITY_NO_ANIMATION);
finish();
overridePendingTransition(0, 0);
startActivity(intent);
}
private void getLocationFromLocationClient() {
if (locationclient != null && locationclient.isConnected()) {
Location loc = locationclient.getLastLocation();
WriteLogToFile.appendLog(this.getString(R.string.app_name),
"LocationClient", "LocationClient",
"Last Known Location :\n" + "Latitude:" + loc.getLatitude()
+ "\nLongitude:" + loc.getLongitude()
+ "\nAccuracy:" + loc.getAccuracy());
LatLng latLng = new LatLng(loc.getLatitude(), loc.getLongitude());
googleMap.moveCamera(CameraUpdateFactory.newLatLng(latLng));
googleMap.animateCamera(CameraUpdateFactory.zoomTo(17));
// googleMap.moveCamera(CameraUpdateFactory.newLatLng(latLng));
googleMap.addMarker(new MarkerOptions().position(latLng).icon(
BitmapDescriptorFactory
.fromResource(R.drawable.trip_end_icon)));
}
}
private void getLocationFromGPSPriver() {
GPSlocationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
GPSlocationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER,
1000, 1, myGPSLocationListener);
}
private void getLocationFromNetworkPriver() {
NetworklocationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
NetworklocationManager.requestLocationUpdates(
LocationManager.NETWORK_PROVIDER, 1000, 1,
myNetworkLocationListener);
}
@Override
public void onConnectionFailed(ConnectionResult arg0) {
// TODO Auto-generated method stub
}
@Override
public void onConnected(Bundle arg0) {
// TODO Auto-generated method stub
}
@Override
public void onDisconnected() {
// TODO Auto-generated method stub
}
}
Этот код поможет вам лучше понять, как реализовать различные типы поставщиков
Просьба показать ваш манифест. –
@ ZohraKhan Я добавил код манифеста – Alex248