开发者

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

I am exte开发者_Python百科nding 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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜