Android 中的服务与线程 [英] Service vs Thread in Android

查看:18
本文介绍了Android 中的服务与线程的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在寻找应该在 android 应用程序中使用什么服务.

I am looking for what service should be used in android applicaton.

文档说

服务是一个应用程序组件,可以在后台执行长时间运行的操作,并且不提供用户界面.

A Service is an application component that can perform long-running operations in the background and does not provide a user interface.

我读过这个线程 应用线程 vs 服务线程 说相同的服务是用于在后台运行操作.

I have read this thread Application threads vs Service threads that saying same services are for running operation in background.

但是这里也可以使用 Thread 来完成.它们之间的任何区别以及您应该在哪里使用它们

But here this can be done using Thread also. Any difference between them and where you should use them

推荐答案

服务旨在独立于 Activity 运行您的任务,它允许您在后台运行任何任务.它在主 UI 线程上运行,因此当您想要执行任何网络或高负载操作时,您必须在那里使用 Thread.

A Service is meant to run your task independently of the Activity, it allows you to run any task in background. This run on the main UI thread so when you want to perform any network or heavy load operation then you have to use the Thread there.

示例:假设您想每天在后台备份即时消息,那么在这里您将使用 Service.

Example : Suppose you want to take backup of your instant messages daily in the background then here you would use the Service.

Threads 用于在它自己的线程而不是主 UI 线程中运行您的任务.当您想要执行一些繁重的网络操作(例如连续向服务器发送字节)时,您会使用它,并且它与 Android 组件相关联.当您的组件破坏了谁启动它时,您也应该停止它.

Threads is for run your task in its own thread instead of main UI thread. You would use when you want to do some heavy network operation like sending bytes to the server continuously, and it is associated with the Android components. When your component destroy who started this then you should have stop it also.

示例:您在 Activity 中使用 Thread 出于某种目的,当您的 Activity 销毁时停止它是一种很好的做法.

Example : You are using the Thread in the Activity for some purpose, it is good practice to stop it when your activity destroy.

这篇关于Android 中的服务与线程的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆