Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    primarykey
    data
    text
    <blockquote> <p>What will happen if I don't use Android Service for long running task?</p> </blockquote> <p><strong>You might get lucky and your code finishes. Then again, you might not get lucky, and your code gets killed at a random point in time.</strong></p> <p>Aside from the textbook descriptions of what an Android <code>Service</code> is and what a <code>Thread</code> is, the main difference between the two which is directly relevant to your question is how the OS threats them.</p> <p>A <strong>thread</strong> is a way to <strong>execute code in the background</strong>, while a <strong>service</strong> is a way to <strong>make Android aware</strong> you are executing code in the background.</p> <p>As far as the underlying Linux kernel is concerned, it knows only about threads, and cares about them only with regards to thread switching and prioritization. Whether there is a service has no impact on this.</p> <p>However, as far as the Android device memory management and task prioritization goes, Android does not know or care about threads in your process. It only knows about services, and interacts with them on the main app process thread only.</p> <p>Thus, for as long as you have a thread alive, the kernel will happily try to keep the process alive and allocate CPU time for that thread execution.</p> <p>However, unless you have an activity, service, content provider, or a broadcast receiver alive, the Android memory manager might decide to <strong>kill your process</strong> to reclaim its resources for another higher priority process, no matter what threads might be working at this point.</p> <p>Therefore, while you could go away with running stuff on a separate thread if the user is interacting with your activity, if you want to make sure the background task finishes successfully and is not interrupted at a random point, you need to wrap it in a service (preferably one that is bound by an activity, or is elevated to UI priority by showing a notification).</p> <p>Note that having a service does not guarantee you that its code will be running in the background. Android will call the lifecycle methods (onStartCommand/onBind/onCreate/OnDestroy) on the main thread of the application process. Your code will have to start a thread to ensure true background execution.</p>
    singulars
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload