Unity 模擬點擊Home鍵和啟動其他app


using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class NewBehaviourScript : MonoBehaviour {


    private AndroidJavaObject currentActivity{

        get{ 
            return new AndroidJavaClass("com.unity3d.player.UnityPlayer").GetStatic<AndroidJavaObject>("currentActivity");
        }

    }
    //啟動應用
    public void StartApp(string packageName,bool isExitThisApp){
        if(Application.platform != RuntimePlatform.Android)
            return;
        AndroidJavaObject launch = currentActivity.Call<AndroidJavaObject>("getPackageManager").Call<AndroidJavaObject>("getLaunchIntentForPackage",packageName);
        currentActivity.Call("startActivity",launch);
        if(isExitThisApp){
            Application.Quit();
        }
    }
    //模擬點擊Home鍵
    void GoHome1()
    {
        string ACTION_MAIN = "android.intent.action.MAIN";
        int FLAG_ACTIVITY_NEW_TASK = 268435456;
        string CATEGORY_HOME = "android.intent.category.HOME";

        AndroidJavaObject intent=new AndroidJavaObject("android.content.Intent",ACTION_MAIN);
        intent.Call<AndroidJavaObject> ("setFlags",FLAG_ACTIVITY_NEW_TASK);
        intent.Call<AndroidJavaObject> ("addCategory", CATEGORY_HOME);
        currentActivity.Call("startActivity",intent);
    }
    //模擬點擊Home鍵
    void GoHome2()
    {
        AndroidJavaClass Intent = new AndroidJavaClass ("android.content.Intent");
        AndroidJavaObject intent=new AndroidJavaObject("android.content.Intent",Intent.GetStatic<AndroidJavaObject>("ACTION_MAIN"));

        //        intent.Call<AndroidJavaObject> ("setFlags",Intent.GetStatic<AndroidJavaObject> ("FLAG_ACTIVITY_NEW_TASK"));//不知道什么原因,這樣寫居然報錯,
        int FLAG_ACTIVITY_NEW_TASK = Intent.GetStatic<int> ("FLAG_ACTIVITY_NEW_TASK");//非得需要用個變量接收一下,而且用AndroidJavaObject接收也報錯,坑
        intent.Call<AndroidJavaObject> ("setFlags",FLAG_ACTIVITY_NEW_TASK);

        intent.Call<AndroidJavaObject> ("addCategory",Intent.GetStatic<AndroidJavaObject> ("CATEGORY_HOME"));
        currentActivity.Call("startActivity",intent);
    }

    void Update()
    {
        if (Input.GetMouseButtonDown(0)) {
//            GoHome1 ();
            GoHome2 ();
        }
    }


}

已上代碼不需要引用任何 jar 包,直接可以用

是通過以下java代碼變形而來的

Intent intent = new Intent(Intent.ACTION_MAIN);  

intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);

intent.addCategory(Intent.CATEGORY_HOME);

startActivity(intent);  


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM