Question

I have an application that runs a background thread which periodically performs a task. The UI thread moves through several different activities.

The tutorial I used can be found at this blog, the gist of it is the following:

  • Create a class that extends Thread

public final class JSONThread extends Thread {

  • Define a method in this class that adds a task to the MessageQueue, prompting executing when able.

public synchronized void enqueueJSON(final JSON.JSON task) {

However, after creating the initial object in my main activity, navigating to another activity obviously loses the Object bound to my Thread. I am no longer able to call methods on that Object (hence unable to add to queue).

I am unsure if this is caused by a wrong decision in architecture on my part or by overseeing the obvious solution. Any ideas? Note that I am trying to avoid AsyncTask for this purpose, since a pool of five threads for a simple task seems a little too much.

Was it helpful?

Solution

You need to store a Thread object as member of some other object with lifetime longer than Activity.

Two ideas for you:

a) It could be a member of Application (http://developer.android.com/reference/android/app/Application.html)

You may have problems with this, if you don't have a Service running. There is no guarantee that your application won't be killed (as example if any system dialog will pop up on top of your activities)

b) It could be a member of Service (http://developer.android.com/reference/android/app/Service.html)

OTHER TIPS

You should be using a service, not a thread. A service will remain in the background so long as there is an activity bound to it, and it won't be reset when an activity exits.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top