当我的位置服务被停用且我想要使用我的应用时,只有GPS provider
有效,而network provider
没有。
它只在重启后才会起作用。
我在nexus4
遇到了这个问题,但在其他设备上也是如此。
我创建了一个具有相同问题的测试应用程序。
如果有人帮我解决这个问题,我将不胜感激。
public class MainActivity extends Activity {
protected static final String TAG = "Gpstest";
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
initLocationManager();
}
private void initLocationManager() {
locationManager = (LocationManager) this.getSystemService(Context.LOCATION_SERVICE);
locationManager.requestLocationUpdates(LocationManager.NETWORK_PROVIDER, 0, 0, locationListener);
locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 0, 0, locationListener);
}
LocationManager locationManager;
// Define a listener that responds to location updates
LocationListener locationListener = new LocationListener() {
public void onStatusChanged(String provider, int status, Bundle extras) {}
public void onProviderEnabled(String provider) {}
public void onProviderDisabled(String provider) {}
@Override
public void onLocationChanged(Location location) {
Log.d(TAG,"onLocationChanged "+location.getProvider());
}
};
@Override
protected void onStop() {
super.onStop();
locationManager.removeUpdates(locationListener);
}
}
清单
<?xml version="1.0" encoding="utf-8"?>
<uses-sdk
android:minSdkVersion="8"
android:targetSdkVersion="18" />
<!-- Location -->
<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" />
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
<application
android:allowBackup="true"
android:icon="@drawable/ic_launcher"
android:label="@string/app_name"
android:theme="@style/AppTheme" >
<activity
android:name="com.example.gpstext.MainActivity"
android:label="@string/app_name" >
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
</application>
答案 0 :(得分:0)
locationManager.requestLocationUpdates(LocationManager.NETWORK_PROVIDER, 0, 0, locationListener);
locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 0, 0, locationListener);
正如您在上面的代码中所看到的,您将两个不同的提供商分配给一个 locationManager 和相同的 locationListener 。
此实现会导致从GPS_Provider
而不是从网络获取数据。
尝试使用两个不同的locationManagers和不同的locationListeners来获取两个提供程序的结果。
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
}
}
此代码将帮助您更好地了解如何实现不同类型的提供程序
答案 1 :(得分:0)
您的代码运行正常。试穿我的设备 经许可
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
和代码
public class MainActivity extends Activity {
protected static final String TAG = "Gpstest";
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
initLocationManager();
}
private void initLocationManager() {
locationManager = (LocationManager) this.getSystemService(Context.LOCATION_SERVICE);
locationManager.requestLocationUpdates(LocationManager.NETWORK_PROVIDER, 0, 0, locationListener);
}
LocationManager locationManager;
// Define a listener that responds to location updates
LocationListener locationListener = new LocationListener() {
public void onStatusChanged(String provider, int status, Bundle extras) {}
public void onProviderEnabled(String provider) {}
public void onProviderDisabled(String provider) {}
@Override
public void onLocationChanged(Location location) {
Log.d(TAG, "onLocationChanged " + location.getProvider());
Toast.makeText(MainActivity.this, "Lat:" + location.getLatitude()
+"Long" + location.getLongitude(),Toast.LENGTH_LONG).show();
}
};
@Override
protected void onStop() {
super.onStop();
locationManager.removeUpdates(locationListener);
}
}
确保wi-fi已开启。