Location Updates funktionieren nur bei einem API Level von >25

  • Antworten:12
SlartiDev
  • Forum-Beiträge: 39

21.09.2018, 09:26:32 via Website

Hallihallo,
Ich habe, nachdem ich das Problem mit dem Hintergrund Service dank eurer Hilfe gelöst habe, ein neues Problem:
Meine Location Updates werden nur gemacht, wenn Android mit einem API Level => 26 installiert ist. Wenn der/das (?) API Level darunter liegt passiert nüscht...

Hier ist meine LocationUpdateService Klasse:

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

            //when the location changed
            //here is where the magic happens...
        }

        @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;
}

und hier meine Backround Service Klasse:

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);
    }


    try{
        MainActivity.imageViewShield.setImageResource(R.drawable.shield_green);
    }catch (Exception e){
        Log.e("Setting green Shield", ""+e);
    }

    return START_STICKY;
}


@Override
public void onDestroy() {
    MainActivity.imageViewShield.setImageResource(R.drawable.shield_red);
    super.onDestroy();
    try {
        unregisterReceiver(broadcastReceiverScreen);
    }catch (Exception e){
        Log.e("unregisterReceiver", ""+e);
    }
    try {
        stopService(new Intent(BackroundService.this, LocationUpdateService.class));
        isDestroy = true;
    }catch (Exception e){
        Log.e("RemovingUpdatesDestroy", ""+e);
    }
    try{
        MainActivity.imageViewShield.setImageResource(R.drawable.shield_red);
    }catch (Exception e){
        Log.e("Setting Red Shield", ""+e);
    }
}

Wenn ich meine Logfiles auslese, kann ich sehen, dass der LocationUpdateService gestartet wird, aber keine Gps updates empfangen.
Hab ihr ne idee, woran das liegen könnte?

Kommentieren
Jokel
  • Forum-Beiträge: 1.530

21.09.2018, 21:31:29 via Website

Hallo es könnte daran liegen das ab android 8 api 26 sich etwas bei den Notification geändert hat.
Bin deinen Code jetzt nicht durchgegangen.

Hilfreich?
Kommentieren
Ludy
  • Admin
  • Forum-Beiträge: 7.958

21.09.2018, 21:58:13 via App

Hallo SlartiDev,

ab API 14 wird/kann der LocationManager genutzt werden.

Siehe hier https://github.com/Ludy87/AndroidPIT

Gruß Ludy (App Entwickler)

Mein Beitrag hat dir geholfen? Lass doch ein "Danke" da.☺

☕ Buy Me A Coffee ☕

Lebensmittelwarnung-App

✨Meine Wunschliste✨

📲Telegram NextPit News📲

Hilfreich?
Kommentieren
Jokel
  • Forum-Beiträge: 1.530

21.09.2018, 22:18:32 via Website

@ludy es müßte eigentlich etwas sein was seit api 26 anders ist als zuvor und wenn er die app für api 26 optimiert hat also ein Funktion benutzt die es erst ab Api 26 gibt.

An dem Manager glaube ich in diesem Fall nicht.

Mich würde auch interessiert in wie weit da nichts passiert. Ob die app überhaupt auf einen handy mit zb android 6, 7 startet.
Die Infos sind hier etwas dürftig.

Meine Location Updates werden nur gemacht, wenn Android mit einem API Level => 26 installiert ist. Wenn der/das (?) API Level darunter liegt passiert nüscht...

Wie meist du das? Bei einen Handy mit adroid 8 geht es und daruter nicht oder?
Oder meinst wenn du es für ein anderes SDK Übersetzt (targetSdkVersion)?
Denn ab Android 8 brauchst du für deine Foreground Notification eine Permission im manifest vielliecht auch zur Laufzeit.

— geändert am 22.09.2018, 09:45:50

Hilfreich?
Kommentieren
SlartiDev
  • Forum-Beiträge: 39

22.09.2018, 16:21:52 via Website

Ich meine, dass alles unter api 26 nicht mehr funktioniert. Genau genommem startet mein BackroundServie den LocationUpdateService. Das kann ich an meinen Logfiles sehen. Bei >26 werden nun über die MethodelocationManager.requestLocationUpdates(2000, 0, criteria, locationListener, null); Location Updates gemacht und die Methode public void onLocationChanged(Location location) {...} aufgerufen und ausgeführt. Bei <26 passiert das aber nicht. irgendwie werden da keine Updates erfragt oder empfangen. Es liegt also wahrscheinlich nicht an irgendwelchen notifications sonder an dem request selber, da der service ja in jedem fall gestartet wird...

Hilfreich?
Kommentieren
Jokel
  • Forum-Beiträge: 1.530

22.09.2018, 17:36:06 via Website

Ja und wie sieht es mit deinen Permission aus wo und wie setzt du die?

Hilfreich?
Kommentieren
swa00
  • Forum-Beiträge: 3.704

22.09.2018, 18:17:05 via Website

Genau das ist mir auch Erstes in den Sinn gekommen - die Permissions.
Ich bin allerdings bis dato davon ausgegangen , dass er Diese natürlich gesetzt hat

Liebe Grüße - Stefan
[ App - Entwicklung ]

Hilfreich?
Kommentieren
SlartiDev
  • Forum-Beiträge: 39

24.09.2018, 10:20:07 via Website

im Manifest:

<uses-permission android:name="ACCESS-COARSE-LOCATION"></uses-permission>
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION"></uses-permission>

und im Code meiner Main in der onCreate:

//checking if permission to use gps location is given
    if (ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
        requestPermissions(new String[]{Manifest.permission.ACCESS_COARSE_LOCATION, Manifest.permission.ACCESS_FINE_LOCATION}, 10);
        return;
    }else{
        Toast.makeText(MainActivity.this,"Permission to use GPS is given!", Toast.LENGTH_SHORT).show();
    }

und als Methode in der Main:

@Override
public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
    //asks for the gps user permission
    switch (requestCode){
        case 10:
            if (grantResults.length>0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
                //(5000);
            }

    }
}
Hilfreich?
Kommentieren
swa00
  • Forum-Beiträge: 3.704

24.09.2018, 10:51:51 via Website

< uses-permission android:name="ACCESS-COARSE-LOCATION" > < /uses-permission >

a) Das kann nicht klappen - schau mal deine Typos
b) Und dazu mal in den Settings der App schauen , nachdem du die Permissions vom User angefordert hast

— geändert am 24.09.2018, 12:59:55

Liebe Grüße - Stefan
[ App - Entwicklung ]

Hilfreich?
Kommentieren
SlartiDev
  • Forum-Beiträge: 39

24.09.2018, 10:53:39 via Website

was sind Typos?
Ganz ehrlich, ich hab script kiddy like einfach nur den code bei nem tutorial abgeschrieben. Hab ne ungefähre idee, was da passiert, aber keine ahnung wie das funktioniert.
Schande auf mein Haupt :)

Hilfreich?
Kommentieren
swa00
  • Forum-Beiträge: 3.704

24.09.2018, 11:12:00 via Website

Na ja , ich denke nicht , dass das dort so geschrieben war :-)

Hinweis und ich möchte Dir bewusst nicht das silberne Tablett präsentieren :

Typos = Schreibweise/Schreibfehler

— geändert am 24.09.2018, 12:10:21

Liebe Grüße - Stefan
[ App - Entwicklung ]

Hilfreich?
Pascal P.
Kommentieren
SlartiDev
  • Forum-Beiträge: 39

24.09.2018, 12:39:51 via Website

ja, hast recht.
ich hab die zeile verbessert, jetzt funktionierts :)

Hilfreich?
Kommentieren
swa00
  • Forum-Beiträge: 3.704

24.09.2018, 12:48:30 via Website

Heute ein Wunder nach dem Anderen :-)

— geändert am 24.09.2018, 12:48:57

Liebe Grüße - Stefan
[ App - Entwicklung ]

Hilfreich?
Ludy
Kommentieren