处理线程,处理程序和消息:“重新启动”一个线程

时间:2010-08-17 16:25:58

标签: android

public class Connection extends Activity实现Runnable {

            public static final int CONNECTION_ERROR = 1;
            public static final int CONNECTION_DONE = 3;



            @Override
            public void onCreate(Bundle icicle) {
                super.onCreate(icicle);
                createConnection();
            }

            public void createConnection() {
                m_ProgressDialog = ProgressDialog.show(this, "Please wait...","Connection ...", true, false);
                thread = new Thread(this);
                thread.start();
            }

            public void run() {
                int i = connecTion();
                handler.sendEmptyMessage(i);
            }

            private Handler handler = new Handler() {

                @Override
                public void handleMessage(Message msg) {
                 if (msg.what == CONNECTION_ERROR) {                
                        m_ProgressDialog.dismiss();

                        AlertDialog.Builder alt_bld = new AlertDialog.Builder(thisA);
                        alt_bld.setMessage("Failed to connect to the server");
                        alt_bld.setCancelable(false);                                       
                        alt_bld.setNegativeButton("Quit",new DialogInterface.OnClickListener() {public void onClick(DialogInterface dialog, int id) {finish();}});
                        alt_bld.setPositiveButton("Try Again",new DialogInterface.OnClickListener() {
                                    public void onClick(DialogInterface dialog, int id) { 
//HERE IS THE PROBLEM
                                        /*m_ProgressDialog.show(thisA, "Please wait...", "Connection ...", true, false);
                                        connecTion();*/
                                    }
                                });

                        AlertDialog alert = alt_bld.create();
                        alert.setTitle("ChatApp");
                        alert.setIcon(R.drawable.icon);
                        alert.show();
                    }
                    else {          
                    m_ProgressDialog.dismiss();
                    finish();
                    }
                }
            };

            private int connecTion() {      
                /** Create a connection */        
                try {

                           //Function to create the connection (throwing error if there is a pb)

                } catch (Exception e) {
                    Log.e("App","Failed to connect");
                    return CONNECTION_ERROR;
                }               
                //If no error left, everything is OK
                return CONNECTION_DONE;

            }

我想实现一个“再试一次”按钮,它再次启动线程以并行创建连接和ProgressDialog。 如何杀死“旧”线程并正确创建新线程? 将同一个线程保持活动并处理Handler和Messages更好吗?使用服务?

谢谢!

2 个答案:

答案 0 :(得分:0)

您可以设置管道线程;我已经详细说明了如何做到这一点on my blog (Threading 5)。另请注意,一旦线程完成,就无法再次重新启动。但是,您可以保持单个线程处于活动状态并安排工作。

另一种方法是每次卸载后台任务时实例化一个线程;它将完成并过期 - 这是更简单的方法。可能值得研究AsyncTask。

答案 1 :(得分:0)

我通常使用的方法是通过一个帮助类来扩展Thread,所以:

public class DoAyncStuff extends Thread
{
     protected Handler mHandler;

     public DoAyncStuff(Handler handler)
     {
         mHandler = handler;
     }

     public void run()
     {
         // Do async stuff here
         // send message back once done

         Message msg = Message.obtain(mHandler, CONNECTION_ERROR_OR_OTHER_MESSAGE);
         mHandler.sendMessage(msg);
     }
}

// to use
DoAyncStuff asyncTask = new DoAyncStuff(mContext, mHandler)
asyncTask.start();

// Then in your handler you can check to async task results and restart if needed

     private Handler handler = new Handler() {

            @Override
            public void handleMessage(Message msg) {
             if (msg.what == CONNECTION_ERROR_OR_OTHER_MESSAGE) { 
                    // prompt to try again
                    // if trying again
                    DoAyncStuff asyncTask = new DoAyncStuff(handler)
                    asyncTask.start();
             }
     }