Mithun Sreedharan
Mithun Sreedharan

Reputation: 51272

Exception while Starting an Activity from TimerTask

I'm trying to start a an activity only after some data is ready in the Service I'm trying this with a timer task which constantly polls the service for the data readness

public class SplashTask extends TimerTask {
    @Override
    public void run() {
        Log.i(MY_DEBUG_TAG, "Internet is accessible, Running some Spalsh screen Tasks ");
        if(mBoundService.isDataReady()) {
            Log.e(MY_DEBUG_TAG, "Data is ready in service..");
            startActivityForResult(new Intent(SplashDroid.this, FunWithDataActivity.class), 3);
        } else {
            Log.e(MY_DEBUG_TAG, "Data not ready in service..");
        }
        Log.i(MY_DEBUG_TAG, "Spalsh Tasks fnished..");
    }
}

Issue is that when data is ready and FunWithDataActivity about to start, i'm getting the following error

07-27 14:53:40.614: ERROR/AndroidRuntime(1042): java.lang.RuntimeException: Can't create handler inside thread that has not called Looper.prepare()

Upvotes: 0

Views: 800

Answers (4)

sparkymat
sparkymat

Reputation: 10028

startActivityForResult has to be called from the UI thread (which is not the thread in which the handler executes). To achieve this, move the startActivityForResult code to a Runnable and run it using runOnUiThread inside the run().

Upvotes: 3

Ash
Ash

Reputation: 1461

Worth looking into these post:

Can't create handler inside thread that has not called Looper.prepare()

Can't create handler inside thread that has not called Looper.prepare() inside AsyncTask for ProgressDialog

If not resolved,Could u post your code where u r facing the problem!!

Upvotes: 0

inazaruk
inazaruk

Reputation: 74780

You can't use startActivityForResult from non-UI thread. You can either use runOnUiThread() or Handler.post().

Also, you shouldn't really use separate thread for polling. Use Handler's postDelayed() function for polling. This way you won't wasted whole thread for simple polling. For an example see: Repeat a task with a time delay?

Upvotes: 1

Vincent Mimoun-Prat
Vincent Mimoun-Prat

Reputation: 28541

Try to use the CountDownTimer class instead. You can also see this answer for an example: TimerTask in Android?

Upvotes: 0

Related Questions