Android线程问题(线程在后台运行)

时间:2013-02-01 01:42:21

标签: java android multithreading dialog

嘿伙计
我今天遇到的问题是关于线程,在Android活动中,我想显示一个带有消息,图标和标题以及三个按钮(正面,负面和中性)的对话框,我已经这样做了没有错误(加上听众和所有这些),我正确地再次执行没有错误,问题在于:

    alert.setPositiveButton("Yes", new android.content.DialogInterface.OnClickListener(){
        public void onClick(DialogInterface i, int j)
        {

            pb.setVisibility(0); //pb is a progress bar
            new Thread (new Runnable ()
            {
                public void run ()
                {
                    try {
                        tv.setText("Saved!");
                        Thread.sleep(5000);
                        tv.setText(null);  //tv is a text view
                        Thread.sleep(5000);
                        finish();

                    } catch (InterruptedException e) {
                        alerttmp.setIcon(R.drawable.ic_launcher);
                        alerttmp.setTitle("Error");
                        alerttmp.setMessage("Thread could not be executed Thread id: 100390");
                        alerttmp.show();
                    }

                }
            }).run();
        }
    }); 

请参阅,正面按钮突出显示并保持突出显示,直到活动关闭,同时我希望对话框消失,pb显示,电视有文本“已保存!!”在其中,然后没有文本,毕竟杀死了活动。

SOS伙计们!谢谢!

ps:英语不是我的母语所以请不要莎士比亚的话! :)请使语言尽可能简单!谢谢!

2 个答案:

答案 0 :(得分:1)

问题是你没有在UI线程中做你的UI。

您需要将可运行对象发布到UI处理程序,而不是仅为此生成新线程。

您可以使用new Handler().postDelayed(Runnable runnable, long millis)来实现这一目标。 这当然必须从UI线程运行 - 而不是从您生成的任何其他线程运行。

答案 1 :(得分:0)

使用两个处理程序进行管理,这里是代码: 注意:我仍然需要了解有关处理程序和postDelayed方法的更多信息,因此评论会有所帮助,并且肯定会受到赞赏,否则我会对其进行谷歌搜索(无论如何都会这样做)

    alert.setPositiveButton("Yes", new android.content.DialogInterface.OnClickListener(){
        public void onClick(DialogInterface i, int j)
        {
            pb.setVisibility(0);
            tv.setText("Saved!");
    new Handler().postDelayed(new Runnable() {
                public void run() {
                    tv.setText(null);
        }}, 5000);
    new Handler().postDelayed(new Runnable() {
        public void run() {
            finish();
}}, 5000);
        }});