-2

在我的应用程序中,我创建了一个SplashScreen将 b 显示 5 秒的 a,然后根据存储在 Preference 文件中的值执行 if else case。如果首选项文件包含值,则AsyncTask代码将运行,否则将加载登录表单。当我尝试运行我的应用程序时。该线程将在意图的帮助下进入登录表单,但是当涉及到AsyncTask我的应用程序时,会显示强制关闭错误消息。

这是我的SplashScreen代码:

public class SplashScreen extends Activity {

@Override
protected void onCreate(Bundle savedInstanceState) {
    // TODO Auto-generated method stub
    super.onCreate(savedInstanceState);
    setContentView(R.layout.splashscreen);

    Thread timer = new Thread()
    {
        public void run()
        {
            try
            {
                sleep(5000);
            }
            catch(InterruptedException e)
            {
                e.printStackTrace();
            }
            finally
            {
                if(GoGolfPref.getEmail(SplashScreen.this)!=null && GoGolfPref.getPass(SplashScreen.this)!=null)
                {
                    new LoadingScreen(SplashScreen.this, SplashScreen.this).execute("login_page", Login.url+GoGolfPref.getEmail(SplashScreen.this)+"/"+GoGolfPref.getPass(SplashScreen.this));
                }
                else
                {
                    Intent in = new Intent(SplashScreen.this, Login.class);
                    startActivity(in);
                    finish();
                }
            }
        }
    };
    timer.start();
}

}

这是我得到的错误:

08-29 07:25:58.040: E/AndroidRuntime(2365): FATAL EXCEPTION: Thread-10
08-29 07:25:58.040: E/AndroidRuntime(2365): java.lang.RuntimeException: Can't create handler inside thread that has not called Looper.prepare()
08-29 07:25:58.040: E/AndroidRuntime(2365):     at android.os.Handler.<init>(Handler.java:121)
08-29 07:25:58.040: E/AndroidRuntime(2365):     at android.app.Dialog.<init>(Dialog.java:101)
08-29 07:25:58.040: E/AndroidRuntime(2365):     at android.app.AlertDialog.<init>(AlertDialog.java:63)
08-29 07:25:58.040: E/AndroidRuntime(2365):     at android.app.ProgressDialog.<init>(ProgressDialog.java:80)
08-29 07:25:58.040: E/AndroidRuntime(2365):     at android.app.ProgressDialog.<init>(ProgressDialog.java:76)
08-29 07:25:58.040: E/AndroidRuntime(2365):     at com.pnf.gogolf.LoadingScreen.<init>(LoadingScreen.java:130)
08-29 07:25:58.040: E/AndroidRuntime(2365):     at com.pnf.gogolf.SplashScreen$1.run(SplashScreen.java:32)

如何让这个工作?

提前致谢...

4

2 回答 2

2

The problem is you're making changes to the UI somewhere, but they're not being done on the UI thread. Anything to do with the user interface has to be done on the UI thread. You do that by encapsulating your code in another runnable and calling runOnUiThread():

runOnUiThread(new Runnable() {
  @Override
  public void run() {
   // set some text views or something
  }
}
于 2012-09-01T21:19:28.380 回答
2

使用处理程序而不是线程的最佳实践,因为处理程序可以在执行期间在 UI 中更改以了解有关处理程序和线程的更多信息,只需在 Android 中检查此处理程序和线程

于 2012-09-01T21:34:10.023 回答