Android,创建一个简单的线程,将更新我的秒计数器

Rya*_*yan 6 multithreading android ui-thread

基本上,我试图运行一个秒计数器和一个水平计数器.每10秒我想要++级别.
但是那还没有实现,到目前为止我只是试图让秒显示但是我得到运行时异常和崩溃.
谷歌搜索我看到它,因为我试图从我的线程更新UI,这是不允许的.所以我想我将需要asyncTask,但我不知道如何用我简单的小程序做到这一点.请帮忙或给我一些替代方案......

package com.ryan1;

import android.app.Activity;
import android.os.Bundle;
import android.util.Log;
import android.widget.TextView;

public class main extends Activity {

int level = 1;
int seconds_running=0;

TextView the_seconds;

@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.main);
    the_seconds = (TextView) findViewById(R.id.textview_seconds);



    Thread thread1 = new Thread(){
        public void run(){
            try {
                sleep(1000); Log.d("RYAN", " RYAN ");

                updated_secs();
            } catch (Exception e) {
                e.printStackTrace();
                Log.d("RYAN", " "+e);
            }
        }
    };
    thread1.start();
}

public void updated_secs(){
    seconds_running++;
    the_seconds.setText(" "+seconds_running);
}
}
Run Code Online (Sandbox Code Playgroud)

Rya*_*ves 6

在UI线程中创建一个Handler,然后在worker线程中向处理程序发送一条消息(Handler.sendMessage(...)).

消息将在UI线程上处理,因此您可以正确更新文本小部件.像这样:

private Handler myUIHandler = new Handler()
{
    @Override
    public void handleMessage(Message msg)
    {
        if (msg.what == some_id_you_created)
        {
            //Update UI here...
        }
    }
};

Then in your thread, to send a message to the handler you do this:

Message theMessage = myHandler.obtainMessage(some_id_you_created);
myUIHandler.sendMessage(theMessage);//Sends the message to the UI handler.
Run Code Online (Sandbox Code Playgroud)