有可能需要在主线程中循环执行某个操作,但在主线程中延时超过5s,就会被系统强制结束。所以这种情况下必须要在子线程中完成这样的循环或费时的操作。
参考了网络上的资料:
handler/ runOnUiThread /AsyncTask
http://blog.csdn.net/qeqeqe236/article/details/6908701
解析Android中的main线程与子线程
http://blog.csdn.net/a3015440/article/details/5666647
下面是例子代码:
package com.phoneman.android.keydown;
import android.app.Activity;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.Toast;
public class KeyDownActivity extends Activity {
private final static int MSG_CLICK_BUTTON1 = 1;
/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
Button button = (Button)findViewById(R.id.button1);
button.setOnClickListener(pushListener);
newSubThread();
}
private OnClickListener pushListener = new OnClickListener()
{
public void onClick(View arg0) {
// TODO Auto-generated method stub
Toast.makeText(getApplicationContext(), "Push Button", Toast.LENGTH_SHORT).show();
// System.out.println("Push the Button");
// Log.i("Main", "Push The Button");
}
};
private void emulateClickButton() {
Button pushButton = (Button) findViewById(R.id.button1);
pushButton.requestFocus();
pushButton.performClick();
}
private Handler handle = new Handler() {
public void handleMessage(Message msg) {
switch (msg.what) {
case MSG_CLICK_BUTTON1:
emulateClickButton();
break;
}
super.handleMessage(msg);
}
};
private void newSubThread() {
new Thread() {
public void run() {
while (true) {
try {
sendMsg(MSG_CLICK_BUTTON1);
Thread.sleep(5000);
} catch (Exception e) {
e.printStackTrace();
}
}
}
}.start();
}
private void sendMsg(int m) {
Message msg = new Message();
msg.what = m;
handle.sendMessage(msg);
}
}