1
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 1 year has passed since last update.

【Unity】Android バックキー操作でアプリを終了する

Posted at

バックキー操作を受け付ける

Update メソッド内で Escapeキーの入力を受け付けることで、バックキーの入力も受け付けるようになります。

private void Update()
{
    if(Input.GetKeyDown(KeyCode.Escape))
    {
        // バックキー押下時処理.
    }
}

アプリの終了に関して

3パターン挙動を記載します。

  • プロセスの終了
  • バックグラウンドに移動
  • タスクの終了

プロセスの終了

Unity に標準で用意されている Application.Quit を使用します。

private void Update()
{
    if(Input.GetKeyDown(KeyCode.Escape))
    {
        Application.Quit();
        return;
    }
}
ファイル名

バックグラウンドに移動

AndroidJavaObject を使用して moveTaskToBackメソッド をコールします。

private void Update()
{
    if(Input.GetKeyDown(KeyCode.Escape))
    {
        AndroidJavaObject activity = new AndroidJavaClass("com.unity3d.player.UnityPlayer").GetStatic<AndroidJavaObject>("currentActivity");
        activity.Call<bool>("moveTaskToBack", true);
        return;
    }
}
ファイル名

タスクの終了

finishAndRemoveTaskメソッド をコールします。

private void Update()
{
    if(Input.GetKeyDown(KeyCode.Escape))
    {
        AndroidJavaObject activity = new AndroidJavaClass("com.unity3d.player.UnityPlayer").GetStatic<AndroidJavaObject>("currentActivity");
        activity.Call("finishAndRemoveTask");
        return;
    }
}
ファイル名

注意点

Unity 側としては、開発者側に独自処理を記述してほしくないようです。
リンク内では、バックグラウンドに移動する方法を勧めています。
https://docs.unity3d.com/2023.3/Documentation/Manual/android-quit.html

1
0
0

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
1
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?