首页 > 解决方案 > 如何停止以自定义意图启动的 Android 服务

问题描述

我在 Android Studio 中构建了一个名为 MService 扩展服务的类,我像这样启动服务:-在与按钮关联的 onClick 内部-

Intent serviceIntent = new Intent(getApplicationContext(), MService.class);
serviceIntent.putExtra("ID", "1"); 
startService(serviceIntent);

服务onStartCommand方法午餐并且工作得很好..

问题是单击按钮时我不知道如何结束服务,我尝试这样做:

stopService(new Intent(getApplicationContext(), MService.class));

在 onClick 方法中, onDestroy午餐,但服务仍在运行我该如何停止它?

标签: androidandroid-studioandroid-intentservice

解决方案


在 onClick 方法中,onDestroy 午餐,但服务仍在运行

如果onDestroy()您的服务被调用,那么之后,该服务没有运行。您的代码可能仍在运行。

如果您在服务中启动事物,例如后台线程,则通常在您的方法中停止并清理它们是您的工作。onDestroy()


推荐阅读