簡體   English   中英

Android 無法在后台訪問位置

[英]Android cant access location in the background

我的應用程序出現問題,它應該每 20-30 秒將當前位置發送到服務器,並且它曾經可以工作。 但是我們剛剛使用 android 8.0 將它安裝在一部新手機上,在這里我可以讀到有一些背景位置限制,但我不知道如何讓他們更快地獲得一些更新。 atm 如果顯示屏關閉,我每小時會收到 3-4 次更新

到目前為止,我正在像這樣開始我的后台服務

intentService = new Intent(getBaseContext(), BackgroundService.class);
    mLayout = findViewById(R.id.layout);
    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
        Log.e(TAG, "onCreate: Startet as foregroundservioce" );
        startForegroundService(intentService);
    } else {
        Log.e(TAG, "onCreate: started as background service" );
        startService(intentService);
    }

后台服務 onStartCommand()

@Override
    public int onStartCommand(Intent intent, int flags, int startId) {
        // Let it continue running until it is stopped.
        PowerManager pm = (PowerManager) getSystemService(Context.POWER_SERVICE);
        appPreferences = new AppPreferences(this.getBaseContext());
        child = appPreferences.getChild();
        lockStatic = pm.newWakeLock(PowerManager.FULL_WAKE_LOCK, "taxaapp:WorkInBackground123");
        lockStatic.acquire();
        sslClientService = new SSLClientService(this);
        return START_STICKY;
    }

我的地理位置管理器

public class GeoLocationService {
    private Timer mTimer;
    private Alarm alarm;
    private boolean tracking;
    private LocationManager locationManager;
    private BackgroundService _context;
    private Child child;
    private SSLClientService sslClientService;
    private long alarmTimeToStop = 0;
    private LocalDatabaseHandler ldbh;
    private Handler mHandler = new Handler();

    /**
     * constructor initializes
     *
     * @param context
     * @param child
     */
    public GeoLocationService(BackgroundService context, Child child) {
        _context = context;
        locationManager = (LocationManager) context.getSystemService(Context.LOCATION_SERVICE);
        sslClientService = _context.getSSLClient();
        ldbh = new LocalDatabaseHandler(context);
        mTimer = new Timer();
        this.child = child;
    }

    /**
     * Updates the working alarm
     *
     * @param alarm
     */
    public void setAlarm(Alarm alarm) {
        if (this.alarm.getId() == 0) {
            this.alarm = alarm;
        }
        _context.sendMessageToUI(R.integer.MSG_GPS_START);
    }

    /**
     * Returns the alarm being used at the moment
     */
    public Alarm getAlarm() {
        return alarm;
    }

    /**
     * Starts location listener
     *
     * @return true if it was able to start
     */
    public boolean start() {
        boolean bool = false;
        mTimer.schedule(new TimedTask(), 20, 30000);
        if (!isTracking()) {
            alarm = new Alarm(child.getId());
            alarmTimeToStop = System.currentTimeMillis() / 1000L + _context.getResources().getInteger(R.integer.GpsMaxTime);
        } else {
            if (!alarm.getAlarmCoordinates().isEmpty()) {
                alarm = new Alarm(child.getId());
                alarmTimeToStop = System.currentTimeMillis() / 1000L + _context.getResources().getInteger(R.integer.GpsMaxTime);
//                sslClientService.SendAlarm(new Alarm(child.getId(), alarm.getLastAlarmCoordinates().getAddress()));
            }
        }
        // Register the listener with the Location Manager to receive location updates
        if (ActivityCompat.checkSelfPermission(_context, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(_context, Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(_context, Manifest.permission.ACCESS_BACKGROUND_LOCATION) != PackageManager.PERMISSION_GRANTED) {
            Log.e("Missing permissions", "we are missing some permissions for GPS location");
            bool = false;
        }
        if (locationManager.isProviderEnabled(LocationManager.GPS_PROVIDER) && locationManager.isProviderEnabled(LocationManager.NETWORK_PROVIDER)) {
            locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 0, _context.getResources().getInteger(R.integer.GeoSettingsDistance), locationListener);
            locationManager.requestLocationUpdates(LocationManager.NETWORK_PROVIDER, 0, _context.getResources().getInteger(R.integer.GeoSettingsDistance), locationListener);
            locationManager.requestLocationUpdates(LocationManager.PASSIVE_PROVIDER, 0, 0, locationListener);
            tracking = true;
            bool = true;
            ldbh.addLog("Starting new alarm", 200, "GeoLocationService-Start");
        }
        return bool;
    }

    /**
     * is the tracking active
     */

    /**
     * Listens for location updates
     */
    private LocationListener locationListener = new LocationListener() {
        private long time = 0;


        /**
         * Called when the location has changed.
         * <p> only accepts new location if 10seconds has passed and location accuracy is less than 30
         * <p> There are no restrictions on the use of the supplied Location object.
         *
         * @param location The new location, as a Location object.
         */
        @Override
        public void onLocationChanged(Location location) {
            Log.i(TAG, "onLocationChanged: Location Accuracy and provider: " + location.getAccuracy() + " / " + location.getProvider());
            Log.i(TAG, "onLocationChanged: TIME! " + (location.getTime() - time));
            if (location.getTime() - time > _context.getResources().getInteger(R.integer.GeoSettingsTime) && location.getAccuracy() <= _context.getResources().getInteger(R.integer.GpsAccuracy)) {
                time = location.getTime();
                // Called when a new location is found by the network location provider.
                List<Address> address;
                double lat = location.getLatitude();
                double lng = location.getLongitude();
//                lat = 10.27657397;  //Kan bruges til test af dårlige kordinator
//                lng = 56.21009964;  //Kan bruges til test af dårlige kordinator
                AlarmCoordinates alarmCoordinates = new AlarmCoordinates(lat, lng, alarm.getId());
                
                Log.i(TAG, "onLocationChanged: new coordinates!");
                NewAlarmCoordinates(alarmCoordinates);
            }
        }

您處於打盹模式。 https://developer.android.com/training/monitoring-device-state/doze-standby關閉屏幕后,設備將很快 Z34D1F91FB2E514B8576FAB1A75A89A6B 提供事件到應用程序用於高優先級推送消息和警報)。 這是預期的行為。

關閉它的唯一方法是讓您的用戶將您的應用列入電池優化白名單。 它不能以編程方式完成。 並且不要期望許多用戶實際上會這樣做。 實際上,您需要圍繞它編寫代碼,並在屏幕關閉時進行少量位置更新。

您也可以使用 ACTION_REQUEST_IGNORE_BATTERY_OPTIMIZATIONS 但在 Play 商店中限制使用,您需要申請豁免。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM