闪屏不会在按下后退按钮时破坏

时间:2013-05-03 10:23:14

标签: android splash-screen

我是Android开发的新手,刚刚完成了我的第一个大学项目申请。我添加了一个完美的启动画面,它在主菜单之前加载,然后在3秒后切换,但如果在启动画面期间按下后退按钮,则会在3秒后退出应用程序传递主菜单将显示。如果在启动画面期间按下后退按钮,我有什么方法可以销毁应用程序吗?

这是我的splash.java文件

公共类Splash扩展了Activity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        requestWindowFeature(Window.FEATURE_NO_TITLE);
        setContentView(R.layout.splash);

        Thread SplashTimer = new Thread(){
            public void run(){
            try {
                sleep(3000);//3 seconds
                Intent menuIntent = new Intent("com.example.Main");
                    startActivity(menuIntent);
                }   
                catch (InterruptedException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                }

                finally {
                        finish();                   
                }
            }
        };
        SplashTimer.start();
    }

}

3 个答案:

答案 0 :(得分:2)

此代码应以无内存泄漏的方式执行此操作:

public class Splash extends Activity {

    private static final int SPLAH = 1;
    private final MyHandler mHandler = new MyHandler(this);

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        requestWindowFeature(Window.FEATURE_NO_TITLE);
        setContentView(R.layout.splash);
        Message m = Message.obtain();
        m.what = SPLAH;
        mHandler.sendMessageDelayed(m, 3000);
    }

    @Override
    public void onBackPressed() {
        super.onBackPressed();
        mHandler.removeMessages(SPLAH);
    }

    private static class MyHandler extends Handler {
        private final WeakReference<Splash> mActivity;

        public MyHandler(Splash activity) {
            mActivity = new WeakReference<Splash>(activity);
        }

        @Override
        public void handleMessage(Message msg) {
            if (msg.what == SPLAH) {
                Splash s = mActivity.get();
                if (s != null) {
                    Intent menuIntent = new Intent("com.example.Main");
                    s.startActivity(menuIntent);
                    s.finish();
                }
            }
        }
    }
}

答案 1 :(得分:0)

尝试:

@Override
public boolean onKeyDown(int keyCode, KeyEvent event) {
  if (keyCode == KeyEvent.KEYCODE_BACK) {
     finish();
     return true;
 }
  return super.onKeyDown(keyCode, event);
}

答案 2 :(得分:0)

您可以在启动活动代码中使用此功能,更轻松地阻止或更改后退按钮的行为(我认为是API 5):

  @Override
  public void onBackPressed()
  {     
        super.onBackPressed();
  }

注释掉超级部分以停止后退按钮关闭你的应用程序,或者在超级调用之前将时间延迟中止线程。