Note that there are some explanatory texts on larger screens.

plurals
  1. POHow to start long running background task in android service
    primarykey
    data
    text
    <p>Having read most of the available documentation on Android services on the developer site and here in stackoverflow, I'm still confused by several aspects of running a service in a separate task. Hopefully someone can put me on the right track.</p> <p>Let's say we have trival service framework such as</p> <pre><code>public class HliService extends Service { @Override public void onCreate() { } @Override public int onStartCommand(Intent intent, int flags, int startId) { // If we get killed, after returning from here, restart return START_STICKY; } @Override public IBinder onBind(Intent intent) { // We don't provide binding, so return null return null; } @Override public void onDestroy() { } } </code></pre> <p>and in the manifest, I have </p> <pre><code>&lt;service android:name=".HliService" android:process=":HLI_Comms"/&gt; </code></pre> <p>so that the service runs in its own thread.</p> <p>The intent of the service is to provide a background task that will communicate to a device using a TCP socket and do some other stuff. At the risk of ignoring battery issues etc, basically I'd like it to run forever.</p> <p>Something like</p> <pre><code>// Method that communicates using a TCP socket, and needs to send // information back to the activity and receive messages from activity // not shown here. private void dummytask() { boolean keepGoing = true; while (keepGoing) { // do useful stuff in here // sets keepGoing false at some point } stopSelf(); } </code></pre> <p>What is the best way to initiate this method/task ?</p> <p>I have looked at code in the developer site that uses a message handler and a looper, which I only partly understand, but it seems very complicated and perhaps more than I require?</p> <p>I don't believe I can call this method from either <code>onCreate()</code> or <code>onStartCommand()</code> since then neither would complete when invoked from the system ? Should I start it with a timer or alarm?</p> <p>I will need to add a message handler to communicate with the the gui activity, but since I'm starting the service in another thread (by virtue of the manifest "process" instruction), do I need to use AIDL instead?</p> <p>I have also looked at using AysnchTask rather than extending Service, but it seems better suited to running a task and then terminating.</p>
    singulars
    1. This table or related slice is empty.
    plurals
    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