Java 从前景到背景的位置始终为空?

Java 从前景到背景的位置始终为空?,java,android,location,location-services,Java,Android,Location,Location Services,我有一个问题,我的Android的位置总是空的,但它似乎只有当我的应用程序从后台转到前台时才会发生。这是我的密码: Public.java: @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { String userId = AccessToken.getCurrentAccessToken().getUserId();

我有一个问题,我的Android的位置总是空的,但它似乎只有当我的应用程序从后台转到前台时才会发生。这是我的密码:

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;
    }
}
问题是,即使我在
Public.java
中输入
checkLocation()
函数(我实现该函数是为了尝试初始化我的位置服务以防止我的位置为空),并且无论何时调用
Location.getLastLocation(),我都能看到我的
LocationService
已正确初始化,并且所有内容都正确
,我总是返回一个空值。我真的不知道为什么会发生这种情况,而这种情况似乎只有在我的应用程序从后台转到前台时才会发生。任何帮助都将不胜感激,谢谢

试试这个

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) {

}

我会用它代替LocationService.java吗?或者在Public.java中?您可以将其添加到Public.java中,并调用checkLocation()方法这似乎对我有用。你会不会碰巧知道为什么我的代码在早些时候不起作用?谢谢!:)