问题
I am having this issue where my Android's location is always null, but it seems like it only happens when my app goes from the background to the foreground. Here is my code:
Public.java:
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
String userId = AccessToken.getCurrentAccessToken().getUserId();
//Open DB and get freinds from db & posts.
datasource = new FriendsDataSource(getContext());
datasource.open();
postsDataSource = new PostsDataSource(getContext());
postsDataSource.open();
fragmentView = inflater.inflate(R.layout.public_tab, container, false);
populateNewsFeedList(fragmentView);
return fragmentView;
}
public void populateNewsFeedList(View fragmentView) {
RecyclerView rv = (RecyclerView)
fragmentView.findViewById(R.id.rv_public_feed);
LinearLayoutManager llm = new LinearLayoutManager(getContext());
rv.setLayoutManager(llm);
Location location = checkLocation();
//Set a 24140.2 meter, or a 15 mile radius.
adapter = new PostRecyclerViewAdapter(postsDataSource.getAllPublicPosts(location.getLatitude(), location.getLongitude(), 24140.2), getContext(), true);
rv.setAdapter(adapter);
}
private Location checkLocation() {
Location location = LocationService.getLastLocation();
if(location == null){
System.out.println("Null location");
LocationService.getLocationManager(getContext());
//Connect to google play services to get last location
LocationService.getGoogleApiClient().connect();
location = LocationService.getLastLocation();
return location;
}
else {
return location;
}
}
LocationService.java:
public class LocationService implements GoogleApiClient.ConnectionCallbacks, GoogleApiClient.OnConnectionFailedListener {
//Google Location Services API
private static LocationService instance = null;
public static GoogleApiClient googleApiClient;
private static Location lastLocation;
LocationManager locationManager;
Context context;
private static final int PERMISSION_REQUEST_COARSE_LOCATION = 1;
/**
* Singleton implementation
* @return
*/
public static LocationService getLocationManager(Context context) {
if (instance == null) {
instance = new LocationService(context);
}
return instance;
}
/**
* Local constructor
*/
private LocationService( Context context ) {
this.context = context;
initLocationService(context);
}
/**
* Sets up location service after permissions is granted
*/
private void initLocationService(Context context) {
if (googleApiClient == null) {
googleApiClient = new GoogleApiClient.Builder(context)
.addConnectionCallbacks(this)
.addOnConnectionFailedListener(this)
.addApi(com.google.android.gms.location.LocationServices.API)
.build();
}
}
@Override
public void onConnected(Bundle bundle) {
try {
lastLocation = LocationServices.FusedLocationApi.getLastLocation(
googleApiClient);
} catch (SecurityException e){
System.out.println("Security Exception: " + e);
}
}
public static Location getLastLocation(){
return lastLocation;
}
@Override
public void onConnectionSuspended(int i) {
}
@Override
public void onConnectionFailed(ConnectionResult connectionResult) {
}
protected static void onStart() {
googleApiClient.connect();
}
protected void onStop() {
googleApiClient.disconnect();
}
public static GoogleApiClient getGoogleApiClient() {
return googleApiClient;
}
}
The problem is, even when I enter the checkLocation()
function (which I implemented to try to initialize my Location Services to prevent my location from being null) in Public.java
and I see that my LocationService
is initialized correctly and everything, whenever I call Location.getLastLocation()
, I am always returned an null value. I'm really not sure why this is happening, and this seems to only happen when I have my app go from the background to foreground. Any help would be appreciated, thanks!
回答1:
Try this,
private LocationManager locationManager;
private String provider;
private Location location;
private boolean isGPSEnabled;
private static boolean isNetworkEnabled;
public static double lat=0.0;
public static double lng=0.0;
public void checkLocation(Activity activity) {
locationManager = (LocationManager) activity.getSystemService(Context.LOCATION_SERVICE);
Criteria c = new Criteria();
provider = locationManager.getBestProvider(c, false);
location = getLocation(activity);
locationManager.requestLocationUpdates(provider, 400, 1, this);
locationManager.removeUpdates(this);
if (location != null) {
// get latitude and longitude of the location
onLocationChanged(location);
} else {
Log.d("TAG","Unable to find Location");
}
}
public Location getLocation(Activity activity) {
try {
locationManager = (LocationManager) activity.getSystemService(Context.LOCATION_SERVICE);
// getting GPS status
isGPSEnabled = locationManager.isProviderEnabled(LocationManager.GPS_PROVIDER);
// getting network status
isNetworkEnabled = locationManager.isProviderEnabled(LocationManager.NETWORK_PROVIDER);
if (!isGPSEnabled && !isNetworkEnabled) {
// no network provider is enabled
} else {
if (isNetworkEnabled) {
locationManager.requestLocationUpdates(LocationManager.NETWORK_PROVIDER, 400, 0, this);
Log.d("Network", "Network Enabled");
if (locationManager != null) {
location = locationManager.getLastKnownLocation(LocationManager.NETWORK_PROVIDER);
if (location != null) {
lat = location.getLatitude();
lng = location.getLongitude();
}
}
}
// if GPS Enabled get lat/long using GPS Services
if (isGPSEnabled) {
if (location == null) {
locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 400, 0, this);
Log.d("GPS", "GPS Enabled");
if (locationManager != null) {
location = locationManager.getLastKnownLocation(LocationManager.GPS_PROVIDER);
if (location != null) {
lat = location.getLatitude();
lng = location.getLongitude();
}
}
}
}
}
} catch (SecurityException e) {
Log.e("PERMISSION_EXCEPTION","PERMISSION_NOT_GRANTED");
}catch (Exception e) {
e.printStackTrace();
}
return location;
}
@Override
public void onLocationChanged(Location location) {
lat = location.getLatitude();
lng = location.getLongitude();
}
@Override
public void onStatusChanged(String provider, int status, Bundle extras) {
}
@Override
public void onProviderEnabled(String provider) {
}
@Override
public void onProviderDisabled(String provider) {
}
来源:https://stackoverflow.com/questions/35643621/location-is-always-null-after-coming-from-foreground-to-background