LoginSignup
6

More than 5 years have passed since last update.

Homeボタンを押したときの挙動をプログラムで再現する

Posted at

サーバーメンテナンス時にアプリを動かしてもらいたくない(?)という要望があり、ダイアログを出してアプリを終了したい。アプリをキルするよりもHomeボタンを押下時の挙動の方がアプリに優しいと思って調べた。

サンプルコード


    public void alertServerMaintenance(String message) {
        new AlertDialog.Builder(this)
                .setMessage(message)
                .setPositiveButton("OK", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        onClickHomeBehavior();
                    }
                })
                .setCancelable(false)
                .show();
    }

    public void onClickHomeBehavior() {
        Intent intent = new Intent(Intent.ACTION_MAIN);
        intent.addCategory(Intent.CATEGORY_HOME);
        intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        startActivity(intent);
    }

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
6