螺纹在Android中--->不幸的是ThreadApp已停止 [英] Thread in Android ---> Unfortunately ThreadApp has Stopped

查看:175
本文介绍了螺纹在Android中--->不幸的是ThreadApp已停止的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个TextView的,我可以用它来显示倒数计时。我想用Thread类这需要Runnable接口。

I have one textview, which i can use to show countdown timer. I wanted to use Thread class which takes Runnable interface.

我写了下面code为相同,但它提供了运行时错误的不幸的是ThreadApp已停止

I wrote the following code for the same but it is gives run time error Unfortunately ThreadApp has Stopped

import android.os.Bundle;
import android.app.Activity;
import android.view.Menu;
import android.widget.TextView;

public class MainActivity extends Activity implements Runnable
{

TextView tvTimer;
Thread timerThread;
int time=30;

@Override
protected void onCreate(Bundle savedInstanceState)
{
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    tvTimer =(TextView)findViewById(R.id.textView1);
    timerThread= new Thread(this);
    timerThread.start();
}

@Override
public boolean onCreateOptionsMenu(Menu menu)
{
    // Inflate the menu; this adds items to the action bar if it is present.
    getMenuInflater().inflate(R.menu.main, menu);
    return true;
}

@Override
public void run()
{
    try
    {
        Thread.sleep(1000);
        tvTimer.setText((String.valueOf(time)).toString());
        time--;
    }
    catch (InterruptedException e)
    {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }

}

}

(。(将String.valueOf(时间))的toString())

与此同时,当我删除的 tvTimer.setText; 它工作正常。任何人都可以向我提供了解决方案。我在android系统是新。

At the same time when i removed tvTimer.setText((String.valueOf(time)).toString()); it works fine. Can anyone provide me the solution. I am new in android.

推荐答案

您可以使用更新使用RunOnUiThread这样的UI

You can use updating UI using RunOnUiThread like this

 @Override
    public void run()
    {
    try
    {
        Thread.sleep(1000);
       runOnUiThread(new Runnable() {
      public void run() {
              tvTimer.setText((String.valueOf(time)).toString());                       
        }
        });
        time--;
      }
      catch (InterruptedException e)
      {
        // TODO Auto-generated catch block
        e.printStackTrace();
       }

     }

这篇关于螺纹在Android中--->不幸的是ThreadApp已停止的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆