4
我写了一个小应用程序,每3秒更改应用程序背景。我使用Handler和Runnable对象来实现这一点。它工作正常。这里是我的代码:请问handler.post(new Runnable());在Android中创建新线程?
public class MainActivity extends Activity {
private RelativeLayout backgroundLayout;
private int count;
private Handler hand = new Handler();
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Button clickMe = (Button) findViewById(R.id.btn);
backgroundLayout = (RelativeLayout) findViewById(R.id.background);
clickMe.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View arg0) {
count = 0;
hand.postDelayed(changeBGThread, 3000);
}
});
}
private Runnable changeBGThread = new Runnable() {
@Override
public void run() {
if(count == 3){
count = 0;
}
switch (count) {
case 0:
backgroundLayout.setBackgroundColor(getResources().getColor(android.R.color.black));
count++;
break;
case 1:
backgroundLayout.setBackgroundColor(Color.RED);
count++;
break;
case 2:
backgroundLayout.setBackgroundColor(Color.BLUE);
count++;
break;
default:
break;
}
hand.postDelayed(changeBGThread, 3000);
}
};
}
在这里,我改变非UI线程UI背景,即backgroundLayout.setBackgroundColor(Color.RED);
里面的run();它是如何工作的?
感谢,因为我在这里请参阅http: //developer.android.com/reference/android/os/Looper.html线程默认没有与它们相关的消息循环,我们必须通过调用prepare()来创建它。然后默认主线程有Looper,bcoz我没有在我的应用程序中创建任何循环。 – Pradeep
是的,主要的UI线程有一个与它相关的looper,你可以用Looper.getMainLooper()来获得它(如果你想检查一个处理器绑定的是什么looper.getMainLooper() – FunkTheMonk