从活动停止IntentService

编程入门 行业动态 更新时间:2024-10-19 05:28:55
本文介绍了从活动停止IntentService的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

我需要这样的情况帮助:

  • 我有活动,有什么开始IntentService。
  • 服务做了一些工作,而在周期和睡眠一段时间。
  • 服务的主循环是无止境的,所以我需要再次从活动的停止。
  • 我必须能够结束的活动,再次启动它,并从新的活动的实例停止IntentService。

    公共类的MyService扩展IntentService {    公众为MyService()    {        超(则将MyService);    }    公共则将MyService(字符串名称){        超(名);    }    @覆盖    保护无效onHandleIntent(意向意图){        Log.d(服务,开始);        而(真)        {            SystemClock.sleep(1000);            Log.d(服务,嘀);        }    }    @覆盖    公共无效的onDestroy(){        Log.d(服务,结束);        super.onDestroy();    }

  • ...

    意向意图=新意图(getApplicationContext(),MyService.class);startService(意向);

    我打过电话 stopService(),但它不工作。是否有任何解决方案是如何做到这一点?先谢谢了。

    解决方案   

    服务做好,而周期和睡眠的一些工作有一段时间了。

    恕我直言,这是一个不恰当的使用 IntentService 的。请创建一个普通的服务,用自己的后台线程,你自己管理。

      

    有没有什么解决方案是如何做到这一点?

    创建一个普通的服务,用您自己管理自己的后台线程。例如,你可以使用 ScheduledExecutorService的,而不是你的睡眠()循环,用关机()或 shutdownNow时()在服务的的onDestroy()。

    I need help with this situation:

  • I have activity, what starts IntentService.
  • Service do some job in while cycle and sleep for some time.
  • Main cycle of service is endless, so I need to stop it from activity again.
  • I must be able to end activity, start it again and stop IntentService from new "instance" of activity.

    public class MyService extends IntentService { public MyService() { super("MyService"); } public MyService(String name) { super(name); } @Override protected void onHandleIntent(Intent intent) { Log.d("SERVICE", "start"); while(true) { SystemClock.sleep(1000); Log.d("SERVICE", "tick"); } } @Override public void onDestroy() { Log.d("SERVICE", "end"); super.onDestroy(); }

  • ...

    Intent intent = new Intent(getApplicationContext(), MyService.class); startService(intent);

    I tried calling stopService(), but it's not working. Is there any solution how to do this? Thanks in advance.

    解决方案

    Service do some job in while cycle and sleep for some time.

    IMHO, this is an inappropriate use of IntentService. Please create a regular Service, with your own background thread that you manage yourself.

    Is there any solution how to do this?

    Create a regular Service, with your own background thread that you manage yourself. For example, you could use a ScheduledExecutorService instead of your sleep() loop, using shutdown() or shutdownNow() in the service's onDestroy().

    更多推荐

    从活动停止IntentService

    本文发布于:2023-11-27 03:59:36,感谢您对本站的认可!
    本文链接:https://www.elefans.com/category/jswz/34/1636491.html
    版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
    本文标签:IntentService

    发布评论

    评论列表 (有 0 条评论)
    草根站长

    >www.elefans.com

    编程频道|电子爱好者 - 技术资讯及电子产品介绍!