上下文发生了变化,无法进行操作

时间:2015-10-17 18:52:52

标签: android location android-gps

我的应用正在使用两个单独的Process。我在一个Services中拥有所有Process,在另一个Process中拥有所有其他组件。当我LocationMangerIntent收到来自public int onStartCommand(Intent intent, int flags, int startId)的{​​{1}}时,我试图从Activity获取lastKnownLocation时,我得到Location null ,当我看到调试器中的LocationManager对象显示Context has changed, operation is not possible时。感谢您的帮助enter image description here。 这是代码片段 -

@Override
    public int onStartCommand(Intent intent, int flags, int startId) {
        String action = intent.getAction();
        if (action != null) {
            if (action.equalsIgnoreCase(Synchronize.ACTION_UPDATE_LOCATION)) {
                Location location = getLastKnownLocation();
                if (location != null) {
                    new Synchronize(getApplicationContext()).
                            updateLocation(prefs.getInt(Utils.PROPERTY_USER_ID, 0),
                                    location.getLatitude(), location.getLongitude(),
                                    Utils.formatDateMilliSecondToUTC(location.getTime()));
                }
            } else if (action.equalsIgnoreCase(Synchronize.ACTION_SYNC_CONTACTS)) {
                new Synchronize(getApplicationContext()).syncContacts();
            } else if (action.equalsIgnoreCase(Synchronize.ACTION_SYNC_EVENTS)) {
                new Synchronize(getApplicationContext()).syncEvents();
            } else if (action.equalsIgnoreCase(Synchronize.ACTION_SYNC_OFFERS)) {
                new Synchronize(getApplicationContext()).syncOffers();
            } else if (action.equalsIgnoreCase(Synchronize.ACTION_SYNC_DISCOVERS)) {
                new Synchronize(getApplicationContext()).syncDiscoverEvents();
            }
        }
        return START_STICKY;
    }

    private Location getLastKnownLocation() {
        LocationManager locationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
        if (Build.VERSION.SDK_INT > Build.VERSION_CODES.LOLLIPOP_MR1) {
            if (checkSelfPermission(Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED &&
                    checkSelfPermission(Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
                return locationManager.getLastKnownLocation(LocationManager.GPS_PROVIDER);
            }
        } else {
            return locationManager.getLastKnownLocation(LocationManager.GPS_PROVIDER);
        }
        return null;
    }

0 个答案:

没有答案