Обновления GPS не запрашиваются с уровнем API ниже 26 - PullRequest
0 голосов
/ 21 сентября 2018

в моем проекте у меня есть Backroundservice, который работает на переднем плане.Он вызывает службу, которая запрашивает обновления GPS, когда экран включен.Но почему-то это работает только тогда, когда уровень API Android => 26. Я понятия не имею, что там не так.

Вот мой Backround Service:

public class BackroundService extends Service {

boolean isDestroy;
boolean updatesRunning;


//initializing the BR for checking if the screen is turned on or off
BroadcastReceiver broadcastReceiverScreen = new BroadcastReceiver() {
    @Override
    public void onReceive(Context context, Intent intent) {
        //if screen is turned on
        if(Intent.ACTION_SCREEN_ON.equals(intent.getAction())){
            //asking for a new update
            if (!isMyServiceRunning(LocationUpdateService.class)) {
                try {
                    startService(new Intent(BackroundService.this, LocationUpdateService.class));
                    Log.e("Updates Requested", "" + isMyServiceRunning(LocationUpdateService.class));
                } catch (Exception e) {
                    Log.e("ScreenTurnedOn", "" + e);
                }
            }
        }
        //if screen is turned off
        if(Intent.ACTION_SCREEN_OFF.equals(intent.getAction())){
            //if screen is turned off updates will be removed
            if (isMyServiceRunning(LocationUpdateService.class)){
                try {
                    stopService(new Intent(BackroundService.this, LocationUpdateService.class));
                    Log.e("Updates Requested", ""+isMyServiceRunning(LocationUpdateService.class));
                }catch (Exception e){
                    Log.e("ScreenTurnedOff", ""+e);
                }
            }
        }
    }
};

//Method to make the service work
@Nullable
@Override
public IBinder onBind(Intent intent) {
return null;
}

//method that get's started on the start of the service
@SuppressLint("MissingPermission")
@Override
public int onStartCommand(final Intent intent, int flags, int startId) {

    Log.e("New Service","################STARTED#################");

    isDestroy = false;

    //Intent filter for BR checking if screen is turned on
    IntentFilter screenStateFilter = new IntentFilter();
    screenStateFilter.addAction(Intent.ACTION_SCREEN_ON);
    screenStateFilter.addAction(Intent.ACTION_SCREEN_OFF);


    //Broadcast receiver for checking if Screen is turned on
    registerReceiver(broadcastReceiverScreen, screenStateFilter);

    //code for letting the service run even if app is not used
    try{
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
            // For foreground service
            Intent notificationIntent = new Intent(this, MainActivity.class);
            PendingIntent pendingIntent = PendingIntent.getActivity(this, 0, notificationIntent, 0);

            // Creating channel for notification
            String id = BackroundService.class.getSimpleName();
            String name = BackroundService.class.getSimpleName();
            NotificationChannel notificationChannel = new NotificationChannel(id,
                    name, NotificationManager.IMPORTANCE_LOW);
            NotificationManager service = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
            service.createNotificationChannel(notificationChannel);
            notificationChannel.setSound(null, null);

            // Foreground notification
            Notification notification = new Notification.Builder(this, id)
                    .setContentTitle(getText(R.string.app_name))
                    .setContentText("KSL is protecting you!")
                    .setSmallIcon(R.mipmap.ic_launcher)
                    .setContentIntent(pendingIntent)
                    .setTicker("Ticker text")
                    .setChannelId(id)
                    .build();

            startForeground(9, notification);
        }else{
            String id = BackroundService.class.getSimpleName();
            Intent notificationIntent = new Intent(this, MainActivity.class);
            PendingIntent pendingIntent = PendingIntent.getActivity(this, 0, notificationIntent, 0);
            NotificationCompat.Builder builder = new NotificationCompat.Builder(this)
                    .setContentTitle(getText(R.string.app_name))
                    .setContentText("KSL is protecting you!")
                    .setSmallIcon(R.mipmap.ic_launcher)
                    .setContentIntent(pendingIntent)
                    .setTicker("Ticker text");

            Notification notification = builder.build();

            startForeground(1, notification);
        }

    }catch (Exception e){
        Log.e("Notification", ""+e);
    }

    return START_STICKY;
}

и вот мой LocationUpdateService:

public class LocationUpdateService extends Service {


//initializing the Location Manager and Listener
LocationManager locationManager;
LocationListener locationListener;

@Nullable
@Override
public IBinder onBind(Intent intent) {
    return null;
}

@SuppressLint("MissingPermission")
@Override
public int onStartCommand(Intent intent, int flags, int startId) {

    Log.d("Location Updates", "*************Started**************");




    //Instantiating the device manager an  listener
    locationManager = (LocationManager) getSystemService(LOCATION_SERVICE);
    locationListener = new LocationListener() {
        @Override
        public void onLocationChanged(Location location) {

            //Some code happening here...


        }



        @Override
        public void onStatusChanged(String s, int i, Bundle bundle) {
        }

        @Override
        public void onProviderEnabled(String s) {
        }

        @Override
        public void onProviderDisabled(String s) {
            Toast.makeText(LocationUpdateService.this, "gps is turned off!", Toast.LENGTH_SHORT).show();
        }
    };

    final Criteria criteria = new Criteria();
    criteria.setAccuracy(Criteria.ACCURACY_FINE);
    criteria.setPowerRequirement(Criteria.POWER_LOW);
    criteria.setSpeedAccuracy(Criteria.ACCURACY_FINE);
    criteria.setAltitudeRequired(false);
    criteria.setSpeedRequired(true);
    criteria.setCostAllowed(false);
    criteria.setBearingRequired(false);
    //API level 9 and up
    criteria.setHorizontalAccuracy(Criteria.ACCURACY_HIGH);
    criteria.setVerticalAccuracy(Criteria.ACCURACY_HIGH);
    locationManager.requestLocationUpdates(1000, 0, criteria, locationListener, null);
    return START_STICKY;
}

@Override
public void onDestroy() {
    super.onDestroy();
    Log.d("Location Updates", "*************Stopped**************");
    locationManager.removeUpdates(locationListener);
    stopSelf();
}


}

Когда я проверяю свои файлы журналов, я вижу, что LocationUpdateClass запускается и останавливается, но я не получаю никаких обновлений ... Не могли бы вы помочь мне?

...