1

我对 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();
    }

}

4

3 回答 3

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();
                }
            }
        }
    }
}
于 2013-05-03T12:23:38.437 回答
0

尝试:

@Override
public boolean onKeyDown(int keyCode, KeyEvent event) {
  if (keyCode == KeyEvent.KEYCODE_BACK) {
     finish();
     return true;
 }
  return super.onKeyDown(keyCode, event);
}
于 2013-05-03T12:07:37.900 回答
0

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

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

要么注释掉 super 部分以停止关闭您的应用程序的后退按钮,要么在 super 调用之前用这里的时间延迟中止线程。

于 2013-05-03T12:23:36.370 回答