unity下載安裝包並且安裝的過程
本方法可以通過沒有熱更新,下載需要升級的版本,並且安裝。不過安裝包不要太大,通過unity中www的方法下載。呼叫安卓自身的安卓方法,具體程式碼如下:
IEnumerator DownFile(string url)
{
Debug.Log("開始下載");
WWW www = new WWW(url);
while (!www.isDone)
{
string LoadPro = (((int)(www.progress * 100)) % 100) + "%";
Debug.Log("進度:" + LoadPro);
yield return 1;
}
yield return www;
if (www.isDone)
{
Debug.Log("下載完成");
byte[] bytes = www.bytes;
CreatFile(bytes);
this.InstallAPK(holdPath, true);
//yield return 1;
}
}
void CreatFile(byte[] bytes)
{
Stream stream;
//text_test.GetComponent<Text>().text = holdPath;
Debug.Log("下載地址" + holdPath);
FileInfo file1 = new FileInfo(holdPath);
stream = file1.Create();
stream.Write(bytes, 0, bytes.Length);
stream.Close();
stream.Dispose();
}
/// <summary>
/// 安裝apk包
/// </summary>
/// <param name="path">路徑</param>
/// <param name="bReTry"></param>
/// <returns></returns>
public bool InstallAPK(string path, bool bReTry)
{
try
{
var Intent = new AndroidJavaClass("android.content.Intent");
var ACTION_VIEW = Intent.GetStatic<string>("ACTION_VIEW");
var FLAG_ACTIVITY_NEW_TASK = Intent.GetStatic<int>("FLAG_ACTIVITY_NEW_TASK");
var intent = new AndroidJavaObject("android.content.Intent", ACTION_VIEW);
var file = new AndroidJavaObject("java.io.File", path);
var Uri = new AndroidJavaClass("android.net.Uri");
var uri = Uri.CallStatic<AndroidJavaObject>("fromFile", file);
intent.Call<AndroidJavaObject>("setDataAndType", uri, "application/vnd.android.package-archive");
if (!bReTry)
{
intent.Call<AndroidJavaObject>("addFlags", FLAG_ACTIVITY_NEW_TASK);
intent.Call<AndroidJavaObject>("setClassName", "com.android.packageinstaller", "com.android.packageinstaller.PackageInstallerActivity");
}
var UnityPlayer = new AndroidJavaClass("com.unity3d.player.UnityPlayer");
var currentActivity = UnityPlayer.GetStatic<AndroidJavaObject>("currentActivity");
currentActivity.Call("startActivity", intent);
Debug.Log("Install New Apk Ok");
return true;
}
catch (System.Exception e)
{
Debug.LogError("Error Install APK:" + e.Message + " -- " + e.StackTrace + " bRetry=" + bReTry);
return false;
}
}
這個方法適合在安卓7.0以下的版本,如果是7.0以上的版本就需要使用