0

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()
Mithun Sreedharan
  • 49,883
  • 70
  • 181
  • 236

4 Answers4

3

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().

Mithun Sreedharan
  • 49,883
  • 70
  • 181
  • 236
sparkymat
  • 9,938
  • 3
  • 30
  • 48
  • I believe so. It is just a matter of replacing the `startActivityForResult` call in `run()` with a `runOnUiThread(startRunnable)` call, and in the `run()` of the `startRunnable` object, you can call `startActivityForResult`. – sparkymat Jul 27 '11 at 09:49
  • @Mithun P, You shouldn't really use `TimerTask` for polling in your case, use `Handler.postDelayed()`. This is more robust and resource efficient approach for Activity component. – inazaruk Jul 27 '11 at 09:53
  • @inazaruk You mean '@Mithun P' ? – sparkymat Jul 27 '11 at 09:53
1

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?

Community
  • 1
  • 1
inazaruk
  • 74,247
  • 24
  • 188
  • 156
0

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

Community
  • 1
  • 1
Vincent Mimoun-Prat
  • 28,208
  • 16
  • 81
  • 124
0

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!!

Community
  • 1
  • 1
Ash
  • 1,391
  • 15
  • 20