首先,你不能從後臺線程更新UI。
其次,一個沒有延遲的無限後臺線程是非常糟糕的代碼。
三,請不要在onCreate()
內撥打setContentView()
兩次。你不需要第二個(setContentView(layout)
)。
最輕的方法是使用postDelayed()
(可用於任何View
(如layout
))來安排在延遲後取得控制權。你可以通過調用removeCallbacks()
取消postDelayed()
工作,通過在同一Runnable
爲您postDelayed()
使用:
/***
Copyright (c) 2012 CommonsWare, LLC
Licensed under the Apache License, Version 2.0 (the "License"); you may not
use this file except in compliance with the License. You may obtain a copy
of the License at http://www.apache.org/licenses/LICENSE-2.0. Unless required
by applicable law or agreed to in writing, software distributed under the
License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS
OF ANY KIND, either express or implied. See the License for the specific
language governing permissions and limitations under the License.
From _The Busy Coder's Guide to Android Development_
http://commonsware.com/Android
*/
package com.commonsware.android.post;
import android.app.Activity;
import android.os.Bundle;
import android.view.View;
import android.widget.Toast;
public class PostDelayedDemo extends Activity implements Runnable {
private static final int PERIOD=5000;
private View root=null;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
root=findViewById(android.R.id.content);
}
@Override
public void onResume() {
super.onResume();
run();
}
@Override
public void onPause() {
root.removeCallbacks(this);
super.onPause();
}
@Override
public void run() {
Toast.makeText(PostDelayedDemo.this, "Who-hoo!", Toast.LENGTH_SHORT)
.show();
root.postDelayed(this, PERIOD);
}
}
(從this sample project代碼)
在你的情況,run()
將更新您的雪花,而不是呈現出的Toast
。
如何初始化'snowArray'?你確定它可以從'myThread'中訪問嗎? – NitroNbg
你在一個線程上調用你的繪圖(?)代碼,這不是UI線程,並且可能試圖將雪花添加到窗口右側?嘗試將'letTheSnowFall()'發佈到'Activity's'' Handler'或者使用'runOnUiThread'方法。 – Darwind