线程错误而不显示我的吐司

时间:2015-01-08 22:21:19

标签: java android

我是Android新手。睡眠运行后,我的应用程序崩溃并出现错误(5000),然后我的finally块中没有显示我的toast。我的代码中导致这些错误的原因是什么?

public class LoginActivity extends ActionBarActivity {

TextView textview;
Toast toast;

@Override
protected void onCreate(Bundle ThisisLoginActivity) {
    super.onCreate(ThisisLoginActivity);
    setContentView(R.layout.activity_login);

    textview = (TextView) findViewById(R.id.textView1);

    Thread thread = new Thread() {
        public void run() {
            try{
                sleep(5000);
            } catch(InterruptedException e) {
                e.printStackTrace();
            }
            finally {
                toast = Toast.makeText(getApplicationContext(), "Sleep Runing", Toast.LENGTH_SHORT);
                toast.show();
            }
        }
    };
    thread.start();
}
}

这是我的LogCat:

01-08 22:30:32.782: E/Trace(3503): error opening trace file: No such file or directory (2)
01-08 22:30:33.322: I/Choreographer(3503): Skipped 47 frames!  The application may be doing too                     much work on its main thread.
01-08 22:30:33.402: D/gralloc_goldfish(3503): Emulator without GPU emulation detected.
01-08 22:30:33.531: I/Choreographer(3503): Skipped 62 frames!  The application may be doing too      much work on its main thread.
01-08 22:30:39.122: I/Choreographer(3503): Skipped 31 frames!  The application may be doing too much work on its main thread.
01-08 22:30:39.272: I/Choreographer(3503): Skipped 43 frames!  The application may be doing too much work on its main thread.
01-08 22:30:45.772: W/dalvikvm(3503): threadid=11: thread exiting with uncaught exception (group=0x40a71930)
01-08 22:30:45.792: E/AndroidRuntime(3503): FATAL EXCEPTION: Thread-153
01-08 22:30:45.792: E/AndroidRuntime(3503): java.lang.RuntimeException: Can't create handler inside thread that has not called Looper.prepare()
01-08 22:30:45.792: E/AndroidRuntime(3503):     at android.os.Handler.<init>(Handler.java:197)
01-08 22:30:45.792: E/AndroidRuntime(3503):     at android.os.Handler.<init>(Handler.java:111)
01-08 22:30:45.792: E/AndroidRuntime(3503):     at android.widget.Toast$TN.<init>(Toast.java:324)
01-08 22:30:45.792: E/AndroidRuntime(3503):     at android.widget.Toast.<init>(Toast.java:91)
01-08 22:30:45.792: E/AndroidRuntime(3503):     at android.widget.Toast.makeText(Toast.java:238)
01-08 22:30:45.792: E/AndroidRuntime(3503):     at com.example.incrementdecrement.LoginActivity$1.run(LoginActivity.java:48)
01-08 22:30:46.462: I/Choreographer(3503): Skipped 34 frames!  The application may be doing too much work on its main thread.

2 个答案:

答案 0 :(得分:1)

您不能直接从另一个线程操纵用户界面。主线程负责所有UI更改。

要解决类似问题,请参阅:Android: Toast in a thread

答案 1 :(得分:0)

从您的主题中使用活动runOnUiThread方法:

runOnUiThread(new Runnable() {
    public void run()
    {
        Toast.makeText(LoginActivity.this, "Sleep Runing", Toast.LENGTH_SHORT).show();
    }
});
相关问题