我在网上找到了这段代码。我是新手,所以我对 java 和 android 处理程序不太了解。我知道如何Runnables
在处理程序中使用在 ui 线程上发布。但是在这段代码中handler.sendMessage(handler.obtainMessage)
我没有得到它。atomic boolean
我也对和之间的区别感到困惑boolean
。所以请解释一下。帮助表示赞赏。
package com.example.watch;
import java.util.Calendar;
import java.util.concurrent.atomic.AtomicBoolean;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.widget.TextView;
import android.app.Activity;
public class MainActivity extends Activity {
TextView watch;
AtomicBoolean ContinueThread = new AtomicBoolean(false);
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
watch = (TextView) findViewById(R.id.txtWatch);
displayCurrentTime();
}
public void displayCurrentTime() {
Calendar c = Calendar.getInstance();
// String curTime = String.valueOf(c.getTime());
int hours = c.get(Calendar.HOUR);
int minutes = c.get(Calendar.MINUTE);
int seconds = c.get(Calendar.SECOND);
String curTime = hours + ":" + minutes + ":" + seconds;
watch.setText(curTime);
}
public void onStart() {
super.onStart();
Thread background = new Thread(new Runnable() {
@Override
public void run() {
try {
while(ContinueThread.get()) {
Thread.sleep(1000);
handler.sendMessage(handler.obtainMessage());
}
} catch (Throwable t) {
}
}
});
ContinueThread.set(true);
background.start();
}
Handler handler = new Handler() {
@Override
public void handleMessage(Message msg) {
displayCurrentTime();
}
};
public void onStop() {
super.onStop();
ContinueThread.set(false);
}
}