从前台到后台后,位置始终为空?

时间:2016-02-26 04:40:01

标签: java android location location-services

我遇到这个问题,我的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;
    }
}

问题是,即使我在checkLocation()中输入Public.java函数(我实现了尝试初始化我的位置服务以防止我的位置为空),我看到了LocationService 1}}被正确初始化了所有内容,每当我调用Location.getLastLocation()时,我总是返回一个空值。我真的不确定为什么会发生这种情况,这似乎只有在我的应用程序从后台转到前台时才会发生。任何帮助将不胜感激,谢谢!

1 个答案:

答案 0 :(得分:0)

试试这个,

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

}