简体   繁体   English

stopService() 方法不会停止服务

[英]The stopService() Method does not stop the service

I was learning foreground services and I created a notification channel to make sure that it keeps the service active.我正在学习前台服务,并创建了一个通知通道以确保它保持服务处于活动状态。 The thing is, the app doesn't stop even when I invoke the stopService method.问题是,即使我调用 stopService 方法,应用程序也不会停止。 The notification sure does disappear, but the app is still shown to be running in the Running Apps page of my phone.通知确实会消失,但该应用程序仍显示在我手机的“正在运行的应用程序”页面中运行。

In this particular app, I have created a Service that Toasts out Random numbers until the Service is running.在这个特定的应用程序中,我创建了一个服务,它会输出随机数,直到服务运行。 The thing is when I press the button to stop, it removes the notification.问题是当我按下按钮停止时,它会删除通知。 But the Toasts continue on and on and the app is shown to be in progress in the Running Apps page.但是 Toast 会一直持续下去,并且应用程序在 Running Apps 页面中显示为正在进行中。 Here's the code.这是代码。

MainActivity.class 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我的服务.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 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);
        }
    }

}

You are stopping the service, but the thread is still executing, you need to stop CountDownTimer , maybe this will work.您正在停止服务,但线程仍在执行,您需要停止CountDownTimer ,也许这会起作用。 I suggest that you assign a global variable CountDownTimer timer and in the destroy call timer.cancel();我建议您分配一个全局变量CountDownTimer timer并在销毁调用timer.cancel();

• Try calling stopSelf(); • 尝试调用stopSelf();

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM