Служба Android переднего плана не остановится - PullRequest
0 голосов
/ 07 сентября 2018

Я наконец-то настроил свое приложение (отслеживание GPS в реальном времени) для отслеживания с помощью службы переднего плана.Однако проблема, с которой я сталкиваюсь сейчас, заключается в том, что служба никогда не останавливается, даже после того, как я ей об этом скажу.Я продолжаю получать журналы всякий раз, когда я получаю новое местоположение от клиента местоположения.Кажется, я нигде не могу найти ничего, что объясняет это, поэтому любая помощь будет принята.

Первые несколько соответствующих методов службы выглядят так ...

@Override
public void onCreate() {
    NotificationManager notificationManager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
    String channelId = Build.VERSION.SDK_INT >= Build.VERSION_CODES.O ? createNotificationChannel(notificationManager) : "";
    NotificationCompat.Builder notificationBuilder = new NotificationCompat.Builder(this, channelId);
    Notification notification = notificationBuilder.setOngoing(true)
            .setSmallIcon(R.mipmap.ic_launcher)
            .setPriority(PRIORITY_MIN)
            .setCategory(NotificationCompat.CATEGORY_SERVICE)
            .build();

    startForeground(ID_SERVICE, notification);
}

@RequiresApi(Build.VERSION_CODES.O)
private String createNotificationChannel(NotificationManager notificationManager){
    String channelId = "my_service_channelid";
    String channelName = "My Foreground Service";
    NotificationChannel channel = new NotificationChannel(channelId, channelName, NotificationManager.IMPORTANCE_HIGH);
    // omitted the LED color
    channel.setImportance(NotificationManager.IMPORTANCE_NONE);
    channel.setLockscreenVisibility(Notification.VISIBILITY_PRIVATE);
    notificationManager.createNotificationChannel(channel);
    return channelId;
}

@Override
public int onStartCommand(Intent intent, int flags, int startId) {
    super.onStartCommand(intent, flags, startId);
    if (intent.getAction().equals(Constants.STARTFOREGROUND_ACTION)) {
        Log.i(TAG, "Received Start Foreground Intent");
        mLocationClient = new GoogleApiClient.Builder(this)
                .addConnectionCallbacks(this)
                .addOnConnectionFailedListener(this)
                .addApi(LocationServices.API)
                .build();

        mLocationRequest.setInterval(LOCATION_INTERVAL);
        mLocationRequest.setFastestInterval(FASTEST_LOCATION_INTERVAL);

        mLocationRequest.setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY);
        mLocationClient.connect();
    } else if (intent.getAction().equals(Constants.STOPFOREGROUND_ACTION)) {
        Log.i(TAG, "Received Stop Foreground Intent");
        mLocationClient.disconnect();
        mLocationClient.unregisterConnectionCallbacks(this);
        stopForeground(true);
        stopSelf();
    }
    //Make it stick to the notification panel so it is less prone to get cancelled by the Operating System.
    return START_STICKY;
}

mLocationRequestcom.google.android.gms.location.LocationRequest

mLocationClient - это com.google.android.gms.common.api.GoogleApiClient

Активность запускается так: ContextCompat.startForegroundService(this, buildLocationServiceIntent(true));

И пытается остановить еекак это: ContextCompat.startForegroundService(this, buildLocationServiceIntent(false)); Эта строка в методе onDestroy для действия, если это имеет значение.

Log.i, которые вы видите, появляются в моем журнале приложений именно тогда, когда вы этого ожидаете.Но журналы из моего onLocationChanged метода продолжают приходить бесконечно после «остановки» службы.Я уверен, что упускаю что-то простое, я просто не вижу этого.

Редактировать

Сервисный код -> https://codeshare.io/5D7LvZ Код активности-> https://codeshare.io/5g4nO8

Edit v2

Вот мой app.gradle

apply plugin: 'com.android.application'

android {
    compileSdkVersion 27
    defaultConfig {
        applicationId "[[appid]]"
        minSdkVersion 18
        targetSdkVersion 27
        versionCode 1
        versionName "1.0"
        testInstrumentationRunner "android.support.test.runner.AndroidJUnitRunner"
    }
    buildTypes {
        release {
            minifyEnabled false
            proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
        }
    }
}

ext {
    androidSupportVersion = "27.1.1"
    playServicesVersion = "15.0.1"
}

dependencies {
    implementation fileTree(include: ['*.jar'], dir: 'libs')
    implementation "com.android.support:appcompat-v7:${androidSupportVersion}"
    implementation "com.android.support:design:${androidSupportVersion}"
    implementation 'com.android.support.constraint:constraint-layout:1.1.2'
    implementation 'com.android.support:support-v4:27.1.1'
    implementation 'com.android.support:recyclerview-v7:27.1.1'
    testImplementation 'junit:junit:4.12'
    androidTestImplementation 'com.android.support.test:runner:1.0.2'
    androidTestImplementation 'com.android.support.test.espresso:espresso-core:3.0.2'
    implementation('com.mikepenz:materialdrawer:6.0.7') {
        transitive = true
    }
    //required support lib modules
    implementation "com.android.support:appcompat-v7:${androidSupportVersion}"
    implementation "com.android.support:recyclerview-v7:${androidSupportVersion}"
    implementation "com.android.support:support-annotations:${androidSupportVersion}"
    implementation "com.android.support:design:${androidSupportVersion}"

    implementation "com.google.android.gms:play-services-maps:${playServicesVersion}"
    implementation "com.google.android.gms:play-services-location:${playServicesVersion}"

    implementation 'javax.annotation:jsr250-api:1.0'
    implementation 'com.google.dagger:dagger:2.0.1'
    annotationProcessor 'com.google.dagger:dagger-compiler:2.0.1'

    implementation "com.mikepenz:iconics-core:3.0.4@aar"
    implementation "com.mikepenz:iconics-views:3.0.4@aar"
    implementation 'com.mikepenz:google-material-typeface:3.0.1.2.original@aar'
    implementation 'com.mikepenz:material-design-iconic-typeface:2.2.0.4@aar'
    implementation 'com.mikepenz:fontawesome-typeface:5.0.13.0@aar'
    implementation 'com.google.android.gms:play-services-maps:15.0.1'
    implementation 'com.google.code.gson:gson:2.8.5'
}

1 Ответ

0 голосов
/ 07 сентября 2018

Явная остановка службы не приведет к прерыванию службы, если есть связанные компоненты, а процесс отмены привязки всех компонентов не завершит ее до тех пор, пока она не будет явно остановлена ​​(если она когда-либо была запущена). Также обратите внимание, что независимо от того, сколько раз вы вызываете метод startService (), один вызов stopService () или stopSelf () остановит его. Я думаю, что эта концепция поможет вам решить вашу проблему.

Edit: Поскольку у меня недостаточно репутации, я не могу комментировать. Поэтому я редактирую свой ответ.

Если вы разрешаете запускать и связывать свою службу, то когда служба запущена, система не уничтожает службу, когда все клиенты отменяют привязку. Вместо этого вы должны явно остановить службу, вызвав stopSelf () или stopService (). Тогда служба остановится.

Эта ссылка может вам помочь,

https://developer.android.com/guide/components/bound-services

...