首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >问答首页 >停止服务作为前台运行的正确方法是什么?

停止服务作为前台运行的正确方法是什么?
EN

Stack Overflow用户
提问于 2013-12-31 12:04:32
回答 8查看 60.2K关注 0票数 68

我试图停止作为前台服务运行的服务。

当前的问题是,当我调用stopService()时,通知仍然保持不变。

因此,在我的解决方案中,我添加了一个接收器,我在onCreate()中注册它

onReceive()方法中,我调用stopforeground(true),它隐藏通知。然后stopself()停止服务。

onDestroy()内部,我取消了接收器的注册。

有更合适的方法来处理这件事吗?因为stopService()根本无法工作。

代码语言:javascript
运行
复制
@Override
public void onDestroy(){
  unregisterReceiver(receiver);
  super.onDestroy();
}
EN

回答 8

Stack Overflow用户

回答已采纳

发布于 2013-12-31 12:22:58

  1. 从您的活动中,调用startService(intent)并传递一些数据,表示停止服务的键。
  2. 从你的服务中,打电话给stopForeground(true)
  3. 然后stopSelf()就在后面。
票数 97
EN

Stack Overflow用户

发布于 2018-06-16 14:02:25

要从活动中启动和停止前台服务,请使用:

代码语言:javascript
运行
复制
//start
    Intent startIntent = new Intent(MainActivity.this, ForegroundService.class);
    startIntent.setAction(Constants.ACTION.STARTFOREGROUND_ACTION);
    startService(startIntent);
//stop
    Intent stopIntent = new Intent(MainActivity.this, ForegroundService.class);
    stopIntent.setAction(Constants.ACTION.STOPFOREGROUND_ACTION);
    startService(stopIntent);

在前台服务中--使用(至少)以下代码:

代码语言:javascript
运行
复制
@Override
 public int onStartCommand(Intent intent, int flags, int startId) {
    if (intent.getAction().equals(Constants.ACTION.STARTFOREGROUND_ACTION)) {
        Log.i(LOG_TAG, "Received Start Foreground Intent ");
        // your start service code
    }
    else if (intent.getAction().equals( Constants.ACTION.STOPFOREGROUND_ACTION)) {
        Log.i(LOG_TAG, "Received Stop Foreground Intent");
    //your end servce code
        stopForeground(true);
        stopSelfResult(startId);
    }
    return START_STICKY;
}
票数 62
EN

Stack Overflow用户

发布于 2019-08-06 04:23:47

如前所述:https://developer.android.com/guide/components/services#Stopping

已启动的服务必须管理自己的生命周期。也就是说,除非系统必须恢复系统内存,而且服务在onStartCommand()返回后继续运行,否则系统不会停止或破坏服务。服务必须通过调用stopSelf()来停止自身,或者另一个组件可以通过调用stopSelf()来停止它

一旦请求停止使用stopSelf()或stopService(),系统就会尽快销毁服务。

因此,您可以从用于调用stopService()的活动中调用startService()。我就在这里做过:

代码语言:javascript
运行
复制
start_button.setOnClickListener {
            applicationContext.startForegroundService(Intent(this, ServiceTest::class.java))
        }
stop_button.setOnClickListener {
            applicationContext.stopService(Intent(this, ServiceTest::class.java))
        }

我创建了两个按钮来启动和停止服务,它可以工作。

票数 15
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/20857120

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档