从线程内停止 Android 服务

发布于 2024-12-14 10:18:11 字数 283 浏览 2 评论 0原文

我有一个服务在 onCreate() 期间启动一个线程。该线程正在监视硬件(IOIO),一旦断开连接就会结束,因此本质上是一个无限循环。从 Activity 停止服务工作正常,线程也会停止(以 onDestory() 结束)。

我的问题是,如果线程死亡(比如由于异常),是否可以停止生成它的服务。

我尝试在线程代码中使用 stopSelf() 但服务不会停止。

谢谢 ps 我的第一篇文章,所以请原谅我应该遵循的任何遗漏约定。

I have a Service which starts a thread during onCreate(). The thread is monitoring hardware (IOIO) and will end once it is disconnected so essesentially is an infinite loop. Stopping the service from an Activity works fine and the thread also stops (ended in onDestory()).

My problem is that if the thread dies (say because of an exception) is it possible to stop the service that spawned it.

I've tried using stopSelf() from within the thread code but the service does not stop.

Thank you
ps my first post so please excuse any missing conventions I should have followed.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

一场春暖 2024-12-21 10:18:12

存储服务的Intent并直接停止怎么样?
在服务中:

private Intent thisIntent;

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

    thisIntent = intent;

在服务内的线程中:

stopService(thisIntent);

How about storing the Intent of the service and stopping it directly?
In the service:

private Intent thisIntent;

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

    thisIntent = intent;

In the thread inside the service:

stopService(thisIntent);
琴流音 2024-12-21 10:18:11

我认为您在这里可能想要使用 Handler。本质上,为您的 Sevrice 创建一个处理程序(确保它是最终的,以便您可以在所有线程中使用)。然后在另一个线程中调用:

myServiceHandler.post(new Runnable(){
  public void run(){
    stopSelf();
  }
}

I think what you want here might be to use a Handler. Eseentially, create a handler for your Sevrice (make sure it's final so you can use across all threads). Then in your other thread, call:

myServiceHandler.post(new Runnable(){
  public void run(){
    stopSelf();
  }
}
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文