无法正确实现sleep()

时间:2014-05-29 12:10:30

标签: java android xml multithreading

我试图创建一个非常简单的应用程序,它具有通向主要活动的启动画面。有人可以指出为什么闪屏的睡眠会无限期地持续下去吗? 如果我删除了睡眠功能,该应用程序正常工作。

Splash class:

package com.example.myfirstapp.app;

import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;

public class Splash extends Activity {

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.splash);
    Thread timer = new Thread(){
        @Override
        public void run() {
            super.run();
            try {
                sleep(1000);
            } catch (InterruptedException e) {
                e.printStackTrace();
            } finally {
                Intent open = new Intent("android.intent.action.MAINACTIVITY");
                startActivity(open);

            }


        }
    };

}

}

清单:

<?xml version="1.0" encoding="utf-8"?>

<application
    android:allowBackup="true"
    android:icon="@drawable/ic_launcher"
    android:label="@string/app_name"
    android:theme="@style/AppTheme" >
    <activity
        android:name="com.example.myfirstapp.app.Splash"
        android:label="@string/app_name" >
        <intent-filter>
            <action android:name="android.intent.action.MAIN" />

            <category android:name="android.intent.category.LAUNCHER" />
        </intent-filter>
    </activity>

    <activity
        android:name="com.example.myfirstapp.app.MainActivity"
        android:label="@string/app_name" >
        <intent-filter>
            <action android:name="android.intent.action.MAINACTIVITY" />

            <category android:name="android.intent.category.DEFAULT" />
        </intent-filter>
    </activity>


</application>

2 个答案:

答案 0 :(得分:3)

需要启动线程。致电timer.start()

答案 1 :(得分:2)

您没有启动该主题。这就是问题的答案,但你真的不应该为此开始一个线索。

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.splash);
    new Handler().postDelayed(new Runnable(){
        @Override
        public void run() {
                Intent intent = new Intent(this, com.example.myfirstapp.app.MainActivity.class);
                startActivity(intent);
                finish();
            }
        }, 1000);    
}

我还向您展示了一种更好的方式来启动活动(不是通过字符串),我调用finish()来关闭启动画面,这样当他们按下它时它不再显示启动画面

关于帖子的快速说明

线程很昂贵,它们需要时间和内存才能启动。因此,将它们旋转为一次性任务永远不会有意义。此外,在它们上运行的代码需要考虑threadsafety,而我的解决方案将在请求它稍后运行的同一ui线程上运行。如果你确实要求代码并行运行(在这里你不是),我仍然建议你在99%的情况下使用AsyncTask过线程。

相关问题