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);