Friday, May 24, 2013

[android help] How to start an activity from a thread class in android?

multithreading - How to start an activity from a thread class in android? - Stack Overflow







Tell me more ×

Stack Overflow is a question and answer site for professional and enthusiast programmers. It's 100% free, no registration required.

















I am extending a thread class and from that class I want to start an activity. How to do this?





























You need to call startActivity() on the application's main thread. One way to do that is by doing the following:



  1. Initialize a Handler and associate it with the application's main thread.



    Handler handler = new Handler(Looper.getMainLooper());



  2. Wrap the code that will start the Activity inside an anonymous Runnable class and pass it to the Handler#post(Runnable) method.



    handler.post(new Runnable() {
    @Override
    public void run() {
    Intent intent = new Intent (MyActivity.this, NextActivity.class);
    startActivity(intent);
    }
    });























you can use Something like this.



public class MyActivity extends Activity
{
Handler hander = new Handler(){
public void handleMessage(Message m){
Intent intent = new Intent (MyActivity.this, Next.class);
startActivity(intent);
}
};
pubilc void onCreate(Bundle ic)
{
//your code setContentView() etc....
Thread toRun = new Thread()
{
public void run()
{
hander.sendMessage(1);
}
}
toRun.start();
}
}
























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.























default






.

stackoverflow.comm

No comments:

Post a Comment

Google Voice on T-Mobile? [General]

Google Voice on T-Mobile? So I recently switched from a GNex on Verizon to a Moto X DE on T-Mobile. I had always used Google Voice for my v...