How To Start An Activity From A Thread Class In Android?
I am extending a thread class and from that class I want to start an activity. How to do this?
Solution 1:
You need to call startActivity()
on the application's main thread. One way to do that is by doing the following:
Initialize a
Handler
and associate it with the application's main thread.Handlerhandler=newHandler(Looper.getMainLooper());
Wrap the code that will start the
Activity
inside an anonymousRunnable
class and pass it to theHandler#post(Runnable)
method.handler.post(new Runnable() { @Override publicvoidrun() { Intent intent = new Intent (MyActivity.this, NextActivity.class); startActivity(intent); } });
Solution 2:
you can use Something like this.
publicclassMyActivityextendsActivity
{
Handlerhander=newHandler(){
publicvoidhandleMessage(Message m){
Intentintent=newIntent (MyActivity.this, Next.class);
startActivity(intent);
}
};
pubilc voidonCreate(Bundle ic)
{
//your code setContentView() etc....ThreadtoRun=newThread()
{
publicvoidrun()
{
hander.sendMessage(1);
}
}
toRun.start();
}
}
Solution 3:
Well to start an activity of an class, a class should extends with activity according to me.
But if you want to start activity with some threading function you can do these things.
Instead of extends Thread, use implements Runnable. After that some class that have an Activity you just call the start thread and put your logic and that start Intent.
I think this is the good solution for you.
Post a Comment for "How To Start An Activity From A Thread Class In Android?"