Как остановить службу переднего плана после уничтожения приложения? - PullRequest
0 голосов
/ 27 апреля 2020

Я использую службу переднего плана с уведомлением. Я удаляю службу в методе основного действия onDestroy, вызывая stopForeground и stopService. Проблема заключается в том, что когда я удаляю свое приложение с последних приложений, чтобы убить его, сеанс отладки все еще выполняется, и когда я перезапускаю приложение, метод onCreate MyApplication расширяется с помощью класса Application not call.

Я вижу ответ здесь { ссылка }

<service
android:enabled="true"
android:name=".ExampleService"
android:exported="false"
android:stopWithTask="true" />

Когда я пишу android: stopWithTask = "true", он отлично работает в android ОС версии 9 и ниже, но не работает в android ОС версии 10. Странно, когда я пишу android: stopWithTask = "false", нормально работает в android ОС версии 10, но не работает ни в одной другой версии.

package com.example.myapplication;
import android.app.Notification;
import android.app.NotificationChannel;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.app.Service;
import android.content.Context;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.drawable.BitmapDrawable;
import android.os.IBinder;
import android.util.Log;

public class MyService extends Service {
private final String  VIDEO_SERVICE_CHANNEL = 
"VIDEO_SERVICE_CHANNEL";
public static final String TAG = "v_call";

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

@Override
public void onCreate() {
    super.onCreate();
    Log.i(TAG, "MyService onCreate()");
    startForeground(1, getMyNotification("Riaz"));
}

@Override
public int onStartCommand(Intent intent, int flags, int startId) {
    Log.i(TAG, "MyService onStartCommand()");
    return START_NOT_STICKY;
}

@Override
public void onTaskRemoved(Intent rootIntent) {
    super.onTaskRemoved(rootIntent);
    Log.i(TAG, "MyService onTaskRemoved()");
    this.stopSelf();
}

@Override
public void onDestroy() {
    super.onDestroy();
    Log.i(TAG, "MyService onDestroy()");
    this.stopSelf();
}

@Override
public void onLowMemory() {
    super.onLowMemory();
    Log.i(TAG, "onLowMemory()");
}

private Notification getMyNotification(String userName){
    NotificationManager notificationManager = (NotificationManager) getApplicationContext().getSystemService(Context.NOTIFICATION_SERVICE);
    if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.O) {
        NotificationChannel mChannel = new NotificationChannel(VIDEO_SERVICE_CHANNEL, getApplicationContext().getString(R.string.room_notification_channel_title), NotificationManager.IMPORTANCE_LOW);
        if (notificationManager != null) {
            notificationManager.createNotificationChannel(mChannel);
        }
    }
    Intent intent = new Intent(this, MainActivity.class);
    intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
    CharSequence title = getApplicationContext().getString(R.string.room_notification_title);
    PendingIntent contentIntent = PendingIntent.getActivity(this,
            0,intent , 0);



    return new Notification.Builder(this,VIDEO_SERVICE_CHANNEL)
            .setContentTitle(title)
            .setSmallIcon(R.mipmap.ic_launcher)
            .setContentIntent(contentIntent).build();
}}

Код активности

public class MainActivity extends AppCompatActivity {
Intent mServiceIntent;
@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
}

@Override
protected void onStart() {
    super.onStart();
    Log.i(MyService.TAG, "MainActivity onStart()");
    mServiceIntent = new Intent(MainActivity.this, MyService.class);
    startVideoService();
}

@Override
protected void onDestroy() {
    super.onDestroy();
    Log.i(MyService.TAG, "MainActivity onDestroy()");
    stopService(mServiceIntent);
}

private void startVideoService() {
    Log.i(MyService.TAG, "startVideoService()");

    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
        startForegroundService(mServiceIntent);
    } else {
        startService(mServiceIntent);
    }

}}

Есть идеи, пожалуйста?

Заранее спасибо

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...