Exception in Timer - java.lang.RuntimeException: Can't create handler inside thread that has not called Looper.prepare() - Android

StackOverflow https://stackoverflow.com/questions/12890400

Question

I'm using a Service for update a db4o file each 3 hours:

    @Override
public IBinder onBind(Intent intent) {
    // TODO Auto-generated method stub
    return null;
}

@Override
public void onCreate() {
    super.onCreate();
    Log.d("Service", "Service started");
    pref = new MyPreferences(getApplicationContext());
    addNotificacion();//update notifications

    timer.scheduleAtFixedRate(new TimerTask() {
        @Override
        public void run() {
            Looper.prepare();
                            Log.d(TAG, "updating...");
            updateInService();
            addNotificacion();
            Log.d(TAG, "End of update");
        }
    }, 40000, 60000);

}

I don't have problem with addNotificacion() method but updateInService throws the Exception of the subject. In this method, I access to db4o, use a http client, update the alarms of AlarmManager... but i don't modify the UI. I start the service in OnBootReceiver.

How can I solve my problem?

Thanks in advance.

After edited:

After added Looper.prepare(); The system does Ok the firs iteration, but in the second, I've an Exception in the instance Looper.prepare();: java.lang.RuntimeException: Only one Looper may be created per thread

Thanks!

Was it helpful?

Solution

You are updating UI from a worker thread. You need to call within the main thread. You could use a runOnUiThread

activity.runOnUiThread(new Runnable() {
  public void run() {
    //Update UI code
        updateInService();
        addNotificacion();

  }
});

OTHER TIPS

You may want to call Looper.loop() at the end of your run() method implementation.

See http://developer.android.com/reference/android/os/Looper.html

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