Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Android create new thread in service class

I created a service class and now I'am trying to run a new thread in this class. Service is started in my MainActivity and this works well. The first Toast.Message in the onCreate() section shows up, but the message in my thread runa() doesn't come up. Thought that it should work with a 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

    }
}

Would be nice if anyone could help me:)

like image 620
user2295158 Avatar asked Jun 17 '26 00:06

user2295158


1 Answers

The Thread that you are creating, will not be executed on the MainThread, thus you can not show a Toast from it. To display a Toast from a background Thread you will have to 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 for your exact problem, although I don't consider it a good 'architecture' or practice as I don't know exactly what you want to achieve.

like image 172
Ovidiu Latcu Avatar answered Jun 19 '26 12:06

Ovidiu Latcu



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!