Метод stopService () не останавливает службу - PullRequest
0 голосов
/ 21 апреля 2020

Я изучал службы переднего плана и создал канал уведомлений, чтобы убедиться, что он поддерживает службу активной. Дело в том, что приложение не останавливается, даже когда я вызываю метод stopService. Уведомление действительно исчезает, но приложение по-прежнему работает на странице «Запущенные приложения» моего телефона.

В этом конкретном приложении я создал службу, которая выбрасывает случайные числа до тех пор, пока она не будет запущена. , Дело в том, что когда я нажимаю кнопку, чтобы остановить, он удаляет уведомление. Но тосты продолжаются и продолжаются, и приложение отображается на странице запущенных приложений. Вот код:

MainActivity.class

import androidx.appcompat.app.AppCompatActivity;
import androidx.core.content.ContextCompat;

import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;

public class MainActivity extends AppCompatActivity implements View.OnClickListener {

    TextView timerTextView;
    private Button startButton;
    private Button stopButton;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        timerTextView = findViewById(R.id.timerTextView);
        startButton = findViewById(R.id.startButton);
        stopButton = findViewById(R.id.stopButton);

        startButton.setOnClickListener(this);
        stopButton.setOnClickListener(this);
    }

    @Override
    public void onClick(View v) {
        Intent intent = new Intent(getApplicationContext(), MyService.class);

        if(v == startButton)
            ContextCompat.startForegroundService(this, intent);

        if (v == stopButton)
            stopService(intent);
    }
}

MyService.class

import android.app.Notification;
import android.app.PendingIntent;
import android.app.Service;
import android.content.Intent;
import android.os.CountDownTimer;
import android.os.IBinder;
import android.widget.Toast;

import androidx.annotation.Nullable;
import androidx.core.app.NotificationCompat;

import java.util.Random;

import static com.example.servicespractice.NotificationClass.CHANNEL_ID;

public class MyService extends Service {

    Random randomGenerator;


    @Override
    public void onCreate() {
        super.onCreate();
    }

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

        Intent notificationIntent = new Intent(this, MainActivity.class);
        final PendingIntent pendingIntent = PendingIntent.getActivity(this,0, notificationIntent, 0);

        Notification notification = new NotificationCompat.Builder(getApplicationContext(), CHANNEL_ID)
                .setContentTitle("Example Service")
                .setContentText("Countdown In Progress")
                .setSmallIcon(R.drawable.ic_android)
                .setContentIntent(pendingIntent)
                .build();

        new CountDownTimer(60000, 1000) {
            @Override
            public void onTick(long millisUntilFinished) {
                randomGenerator = new Random();
                Toast.makeText(getApplicationContext(), Integer.toString(randomGenerator.nextInt(1000)), Toast.LENGTH_SHORT).show();
            }

            @Override
            public void onFinish() {
                Toast.makeText(getApplicationContext(), "All Numbers Generated", Toast.LENGTH_SHORT).show();
                onDestroy();
            }
        }.start();

        startForeground(1, notification);
        return START_NOT_STICKY;
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
    }

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

NotificationClass . java

import android.app.Application;
import android.app.NotificationChannel;
import android.app.NotificationManager;
import android.os.Build;

public class NotificationClass extends Application {
    public static final String CHANNEL_ID = "exampleServiceChannel";

    public void onCreate() {
        super.onCreate();
        createNotificationChannel();
    }

    public void createNotificationChannel(){
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O){

            NotificationChannel notificationChannel = new NotificationChannel(
                    CHANNEL_ID,
                    "Example Service Channel",
                    NotificationManager.IMPORTANCE_DEFAULT
            );

            NotificationManager notificationManager = getSystemService(NotificationManager.class);
            notificationManager.createNotificationChannel(notificationChannel);
        }
    }

}

1 Ответ

1 голос
/ 21 апреля 2020

Вы останавливаете службу, но поток все еще выполняется, вам нужно остановить CountDownTimer, возможно, это будет работать. Я предлагаю вам назначить глобальную переменную CountDownTimer timer и в вызове уничтожения timer.cancel();

• Попробуйте позвонить stopSelf();

...