1

I'm currently trying to show a toast from IntentService, if a device detects an accelerometer. To do so, I searched and learned that I can implement an Handler. However, it is not quite working. The code compiles and runs on an emulator without any error, but the toast doesn't show. I was wondering if I could get some help to spot mistakes in my code. The code is shown below.

Any help would be appreciated!

public class AccelService extends IntentService implements SensorEventListener{
    private SensorManager mySensorManager;
    private Handler toastHandler;

    public AccelService(){
        super("AccelerometerIntentService");
    }
    ...
    private class ToastRunnable implements Runnable{
        String toastText;
        public ToastRunnable(String text){
            toastText = text;
        }
        @Override
        public void run(){
            Toast.makeText(getApplicationContext(), toastText, Toast.LENGTH_SHORT).show();
        }
    }
    @Override
    protected void onHandleIntent(Intent intent){
        toastHandler = new Handler();
        initialize();
    }
    public void initialize(){
        mySensorManager = (SensorManager) getSystemService(SENSOR_SERVICE);
        if(mySensorManager.getDefaultSensor(Sensor.TYPE_ACCELEROMETER) != null){
            toastHandler.post(new ToastRunnable("Accelerometer Detected!"));
        }
    }
    ...
}
blahdiblah
  • 33,069
  • 21
  • 98
  • 152
ElectroJunkie
  • 301
  • 5
  • 16
  • http://stackoverflow.com/questions/5346980/intentservice-wont-show-toast?rq=1 – marcinj Feb 10 '14 at 16:04
  • Log if runnable is executed & try getBaseContext() as Context parameter – Sam Feb 10 '14 at 16:05
  • @ marcin_j : I am not too sure the solution to the suggested post is correct. IntentService reference mentions that 'onStartCommand' method is not to be overwritten. Also, the whole point of having Handler is because the IntentService is running in different thread and as a work around. – ElectroJunkie Feb 10 '14 at 17:18

1 Answers1

1

Creating the handler for the Toast messages in onHandleIntent binds it to the wrong thread:

This method is invoked on the worker thread with a request to process.

Either explicitly set the handler's thread, with, e.g., new Handler(getMainLooper()) or create the handler in onCreate.

blahdiblah
  • 33,069
  • 21
  • 98
  • 152