У меня возникла проблема, когда местоположение моего Android всегда равно null, но похоже, что это происходит только тогда, когда мое приложение переходит из фона на передний план. Вот мой код:Место всегда равно null после перехода от переднего плана к фону?
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;
}
}
Проблема заключается в том, даже когда я вхожу в checkLocation()
функцию (которую я осуществил, чтобы попытаться инициализировать мои службы местоположения, чтобы мое местоположение не было равным нулю) в Public.java
, и я вижу, что мой LocationService
инициализирован правильно и все, всякий раз, когда я вызываю Location.getLastLocation()
, я всегда возвращаю нулевое значение. Я действительно не уверен, почему это происходит, и это, похоже, происходит только тогда, когда у меня есть приложение, идущее из фона на передний план. Любая помощь будет оценена, спасибо!
Я использую бы это вместо LocationService.java? Или в Public.java? – user1871869
вы можете добавить его в public.java и вызвать метод checkLocation() –
Это, похоже, сработало для меня. Вы случайно не знаете, почему мой код не работал раньше? Спасибо! :) – user1871869