Java – Android creates new threads in service classes

Android creates new threads in service classes… here is a solution to the problem.

Android creates new threads in service classes

I

created a service class and now I’m trying to run a new thread in this class. The service started in my MainActivity and worked great. The first Toast.Message in the onCreate() section appears, but the message in my thread runa() doesn’t. Thought it should work with the new Runnable().

public class My Service extends Service {
    private static final String TAG = "MyService";
    Thread readthread;

@Override
    public IBinder onBind(Intent intent) {
        return null;
    }

@Override
    public void onCreate() {
        Toast.makeText(this, "My Service Created", Toast.LENGTH_LONG).show(); is shown

readthread = new Thread(new Runnable() { public void run() { try {
            runa();
        } catch (Exception e) {
             TODO Auto-generated catch block
            e.printStackTrace();
        } } });

readthread.start(); 

Log.d(TAG, "onCreate");

}

@Override
    public void onDestroy() {
        Toast.makeText(this, "My Service Stopped", Toast.LENGTH_LONG).show();
        Log.d(TAG, "onDestroy");

}

@Override
    public void onStart(Intent intent, int startid) {

Toast.makeText(this, "My Service Started", Toast.LENGTH_LONG).show();

Log.d(TAG, "onStart");

}
    public void runa() throws Exception{

Toast.makeText(this, "test", Toast.LENGTH_LONG).show(); doesn't show up

}
}

It would be great if someone could help me 🙂

Solution

The Thread you’re creating doesn’t execute on MainThread, so you can’t display a toast from it. To display a toast from a background Thread, you must use a Handler and use that Handler to display the toast.

private MyService extends Service {
    Handler mHandler=new Handler();
    //...

public void runa() throws Exception{
        mHandler.post(new Runnable(){
            public void run(){
                Toast.makeText(MyService.this, "test", Toast.LENGTH_LONG).show()
            }
        }
    }    
}

This would be the solution to your exact problem, although I don’t think it’s a good “architecture” or practice because I don’t know exactly what you’re trying to achieve.

Related Problems and Solutions