我注意到即使应用程序关闭,线程仍在运行!怎么可能,Asnctask 的行为是一样的。我以为所有线程都是在 UIThread 中执行的,但显然不是,所以如果我理解正确,外部线程是独立于 UIThread 的吗?你能帮我理解一个Android应用程序的执行架构吗?
这是一个小程序说明我的观点:
package com.example.thread;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.app.Activity;
import android.util.Log;
import android.view.Menu;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.TextView;
public class ThreadActivity extends Activity {
private final String TAG = "ThreadActivity";
private TextView textView;
private Button buttonStart;
private Thread t = null;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_thread);
textView = (TextView) findViewById(R.id.screen_thread_textview);
buttonStart = (Button) findViewById(R.id.screen_thread_button);
buttonStart.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
startThread();
}
});
}
private void startThread() {
if (t == null) {
t = new Thread(new Runnable() {
@Override
public void run() {
for (int i = 0; i < 10; i++) {
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
Message msg = handler.obtainMessage(i);
handler.sendMessage(msg);
Log.v(TAG, "Thread running: i=" + i);
}
t = null;
}
});
t.start();
}
}
private Handler handler = new Handler() {
public void handleMessage(Message msg) {
textView.setText("Thread running: i=" + msg.what);
}
};
@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.thread, menu);
return true;
}
}
和布局:
<TextView
android:id="@+id/screen_thread_textview"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_margin="10dp"
android:background="#AACCCCCC"
android:textSize="20sp" />
<Button
android:id="@+id/screen_thread_button"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerInParent="true"
android:text="Start Thread" />
</RelativeLayout>
预先感谢您的澄清