关于android中service与线程

Android服务(service)默认在主线程运行,可能导致ANR错误。若需进行CPU密集型或阻塞操作,应在service内创建新线程。应当根据需求选择使用service(后台运行)还是线程(用户交互时)。例如,播放音乐时,若仅在活动(activity)运行时,可在活动中创建线程。同时,考虑使用IntentService或HandlerThread。确保理解进程和线程的概念,以避免主线程阻塞。
摘要由CSDN通过智能技术生成

android sdk中的描述

Caution: A service runs in the main thread of its hosting process—the service does not create its own thread and does not run in a separate process (unless you specify otherwise). This means that, if your service is going to do any CPU intensive work or blocking operations (such as MP3 playback or networking), you should create a new thread within the service to do that work. By using a separate thread, you will reduce the risk of Application Not Responding (ANR) errors and the application's main thread can remain dedicated to user interaction with your activities.

service是运行在主线程上的,而不是运行在另一个线程中,如果你想在service中处理很占时间的操作,你必须在service中开线程,这样可以降低activity没有响应的风险。


Should you use a service or a thread?

A service is simply a component that can run in the background even when the user is not interacting with your application. Thus, you should create a service only if that is what you need.

If you need to perform work outside your main thread, but only while the user is interacting with your application, then you should probably instead create a new thread and not a service. For example, if you want to play some music, but only while your activity is running, you might create a thread inonCreate(), start running it in onStart(), then stop it in onStop(). Also consider using AsyncTask orHandlerThread, instead of the traditional Threadclass. See the Processes and Threading document for more information about threads.

Remember that if you do use a service, it still runs in your application's main thread by default, so you should still create a new thread within the service if it performs intensive or blocking operations.



  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 2
    评论
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值