不支持弃用的线程方法

时间:2011-12-31 06:59:41

标签: android

我正在制作一个项目,我需要显示主页,当主页显示时,在此之后或继续3到5秒我的其他欢迎自定义对话框显示。但这样做,发生以下错误但我的应用程序没有停止工作.. LogCat显示这些错误。 申请代码:

  final Dialog d=new Dialog(Main.this);
    d.setContentView(R.layout.SplashScreen);
    Thread splashTread = new Thread() {
        @Override
        public void run() {
            try {
                d.show();

                int waited = 0;
                while(_active && (waited < _splashTime)) {
                    sleep(100);
                    if(_active) {
                        waited += 100;
                    }
                }
            } catch(InterruptedException e) {
                // do nothing
            } finally {
                d.cancel();
                    stop();
            }
        }
    };
    splashTread.start();
}

@Override
public boolean onTouchEvent(MotionEvent event) {
    if (event.getAction() == MotionEvent.ACTION_DOWN) {
        _active = false;
    }
    return true;
}

LogCat中的错误:

12-30 14:54:54.044: E/global(1232): Deprecated Thread methods are not supported.
12-30 14:54:54.044: E/global(1232): java.lang.UnsupportedOperationException.
12-30 14:54:54.044: E/global(1232):     at java.lang.VMThread.stop(VMThread.java:85)
12-30 14:54:54.044: E/global(1232):     at java.lang.Thread.stop(Thread.java:1280)
12-30 14:54:54.044: E/global(1232):     at java.lang.Thread.stop(Thread.java:1247)
12-30 14:54:54.044: E/global(1232):     at com.droidnova.android.SplashScreen$1.run(SplashScreen.java:35)

3 个答案:

答案 0 :(得分:11)

在Android中,最好使用Handler来管理ThreadRunnables

创建一个处理程序实例

Handler handler = new Handler();

创建一个Runnable线程

Runnable runnable = new Runnable() {

        @Override
        public void run() {
            Log.d("runnable started", "inside run");
            handler.removeCallbacks(runnable);
            handler.postDelayed(runnable, 1000);
        }
    };

使用Handler启动Runnable

handler.postDelayed(runnable, 1000);

并停止使用Runnable

handler.removeCallbacks(runnable);

答案 1 :(得分:1)

此链接准确告诉您问题所在,以及如何解决问题:

What is this log, when I coded thread.stop()?

  

Thread.stop是不推荐使用的API,而弃用的线程方法则不是   Android支持。因此,它正在投掷   UnsupportedOperationException异常。

     

答案是不要使用Thread.stop - 关闭你的线程   更优雅的方式,例如通过设置线程的标志   定期检查。

此链接讨论为什么不推荐使用thread.stop()(很久以前在 Java 中不推荐使用,而不仅仅是Android!):

http://docs.oracle.com/javase/1.4.2/docs/guide/misc/threadPrimitiveDeprecation.html

答案 2 :(得分:1)

以最佳方式进行启动画面

int SPLASH_TIME = 1300;
    Handler HANDLER = new Handler();

                    // thread for displaying the SplashScreen
                    HANDLER.postDelayed(new Runnable() {
                        @Override
                        public void run() {
                         finish();
                         startActivity (new Intent(getApplicationContext(),Alpha.class));
                        }
                      }, SPLASH_TIME);
相关问题