公共类连接扩展活动实现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会更好吗?使用服务?
谢谢!