1. 程式人生 > >Unity3D工程在Android解決關閉屏保

Unity3D工程在Android解決關閉屏保

	//獲取許可權
	<uses-permission android:name="android.permission.WAKE_LOCK" />
	
	//java實現 在OnCreate中呼叫,getWindow().addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);
	
	//Unity C#實現
	public static AndroidJavaObject Activity 
	{
		get {
			AndroidJavaClass jcPlayer = new AndroidJavaClass("com.unity3d.player.UnityPlayer");	
			return jcPlayer.GetStatic<AndroidJavaObject>("currentActivity");
		}
	}

	const int FLAG_KEEP_SCREEN_ON = 128;
	public static void KeepScreenOn()
	{
		try
		{
			Activity.Call("runOnUiThread", new AndroidJavaRunnable(() => {
				//需要在UI執行緒中呼叫
				Activity.Call<AndroidJavaObject>("getWindow").Call ("addFlags",FLAG_KEEP_SCREEN_ON);
			}));
		}
		catch(Exception e)
		{
			Log.E(e.Message);
		}
	}