从前景到背景后位置始终为空? [英] Location is always null after coming from foreground to background?

查看:85
本文介绍了从前景到背景后位置始终为空?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我遇到了这样的问题,即我的Android位置始终为空,但似乎仅当我的应用程序从后台移动到前台时才会发生.这是我的代码:

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:

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:

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()函数(实现该函数以尝试初始化我的位置服务以防止我的位置为空)时,我仍然看到我的LocationService已正确初始化一切,每当我调用Location.getLastLocation()时,我总是返回一个空值.我真的不确定为什么会这样,这似乎只有在我的应用程序从后台转到前台时才会发生.任何帮助将不胜感激,谢谢!

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!

推荐答案

尝试一下,

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

}

这篇关于从前景到背景后位置始终为空?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆