add file open

This commit is contained in:
2020-08-07 22:40:04 +08:00
parent c1e3f992aa
commit f9bedd2c62
115 changed files with 9835 additions and 1096 deletions

View File

@@ -0,0 +1,8 @@
fileFormatVersion: 2
guid: dbace2eb7405e9741a69754cce1dc4de
folderAsset: yes
DefaultImporter:
externalObjects: {}
userData:
assetBundleName:
assetBundleVariant:

View File

@@ -0,0 +1,239 @@
/*MIT License
Copyright(c) 2020 Mikhail5412
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
*/
using UnityEngine;
using UnityEditor;
using System.IO;
using System.Collections.Generic;
using ICSharpCode.SharpZipLib.Zip;
using ICSharpCode.SharpZipLib.Core;
using System;
#if UNITY_EDITOR
namespace UnityAndroidOpenUrl.EditorScripts
{
/// <summary>
/// Static class whose task is to update the package name in AndroidManifest.xml if it has been changed
/// </summary>
[InitializeOnLoad]
public static class PackageNameChanger
{
private const string PLUGINS_DIR = "3rd/AndroidOpener/Plugins";
private const string TEMP_DIR = "Temp";
private const string AAR_NAME = "release.aar";
private const string MANIFEST_NAME = "AndroidManifest.xml";
private const string PROVIDER_PATHS_NAME = "res/xml/filepaths.xml";
private static string pathToPluginsFolder;
private static string pathToTempFolder;
private static string pathToBinary;
private static string lastPackageName = "com.company.product";
private static bool stopedByError;
static PackageNameChanger()
{
pathToPluginsFolder = Path.Combine(Application.dataPath, PLUGINS_DIR);
if(!Directory.Exists(pathToPluginsFolder))
{
Debug.LogError("Plugins folder not found. Please re-import asset. See README.md for details...");
return;
}
pathToTempFolder = Path.Combine(pathToPluginsFolder, TEMP_DIR);
pathToBinary = Path.Combine(pathToPluginsFolder, AAR_NAME);
if (!File.Exists(pathToBinary))
{
Debug.LogError("File release.aar not found. Please re-import asset. See README.md for details...");
return;
}
EditorApplication.update += Update;
TryUpdatePackageName();
}
static void Update()
{
if (stopedByError)
return;
if (lastPackageName != PlayerSettings.applicationIdentifier)
{
TryUpdatePackageName();
}
}
private static void TryUpdatePackageName()
{
FileInfo fileInfo = new FileInfo(pathToBinary);
if(!IsFileAlreadyOpen(fileInfo))
{
RepackBinary();
}
}
private static void RepackBinary()
{
try
{
ExtractBinary();
}
catch (Exception e)
{
Debug.LogError("Extract release.aar error: " + e.Message);
stopedByError = true;
return;
}
ChangePackageName();
try
{
ZippingBinary();
}
catch (Exception e)
{
Debug.LogError("Zipping release.aar error: " + e.Message);
stopedByError = true;
return;
}
Directory.Delete(pathToTempFolder, true);
}
private static void ExtractBinary()
{
if (!File.Exists(pathToBinary))
{
throw new Exception("File release.aar not found. Please reimport asset. See README.md for details...");
}
if (!Directory.Exists(pathToTempFolder))
{
Directory.CreateDirectory(pathToTempFolder);
}
using (FileStream fs = new FileStream(pathToBinary, FileMode.Open))
{
using (ZipFile zf = new ZipFile(fs))
{
for (int i = 0; i < zf.Count; ++i)
{
ZipEntry zipEntry = zf[i];
string fileName = zipEntry.Name;
if (zipEntry.IsDirectory)
{
Directory.CreateDirectory(Path.Combine(pathToTempFolder, fileName));
continue;
}
byte[] buffer = new byte[4096];
using (Stream zipStream = zf.GetInputStream(zipEntry))
{
using (FileStream streamWriter = File.Create(Path.Combine(pathToTempFolder, fileName)))
{
StreamUtils.Copy(zipStream, streamWriter, buffer);
}
}
}
if (zf != null)
{
zf.IsStreamOwner = true;
zf.Close();
}
}
}
}
private static void ChangePackageName()
{
string manifestPath = Path.Combine(pathToTempFolder, MANIFEST_NAME);
string manifestText = File.ReadAllText(manifestPath);
int manifestPackageNameStartIndex = manifestText.IndexOf("package=\"") + 9;
int manifestPackageNameEndIndex = manifestText.IndexOf("\">", manifestPackageNameStartIndex);
string manifestPackageName = manifestText.Substring(manifestPackageNameStartIndex, manifestPackageNameEndIndex - manifestPackageNameStartIndex);
manifestText = manifestText.Replace("package=\"" + manifestPackageName, "package=\"" + PlayerSettings.applicationIdentifier);
manifestText = manifestText.Replace("android:authorities=\"" + manifestPackageName, "android:authorities=\"" + PlayerSettings.applicationIdentifier);
File.WriteAllText(manifestPath, manifestText);
string filepathsPath = Path.Combine(pathToTempFolder, PROVIDER_PATHS_NAME);
string filepathsText = File.ReadAllText(filepathsPath);
int filepathsPackageNameStartIndex = filepathsText.IndexOf("data/") + 5;
int filepathsPackageNameEndIndex = filepathsText.IndexOf("\" name", filepathsPackageNameStartIndex);
string filepathsPackageName = filepathsText.Substring(filepathsPackageNameStartIndex, filepathsPackageNameEndIndex - filepathsPackageNameStartIndex);
filepathsText = filepathsText.Replace("data/" + filepathsPackageName, "data/" + PlayerSettings.applicationIdentifier);
File.WriteAllText(filepathsPath, filepathsText);
lastPackageName = PlayerSettings.applicationIdentifier;
}
private static void ZippingBinary() // используется ДОзапись, обычным методом .Add(filePath, entryName), для перезаписи с нуля нужно использовать ZipOutputStream zipToWrite = new ZipOutputStream(zipStream) и FileStream targetFile
{
if (!File.Exists(pathToBinary))
{
throw new Exception("File release.aar not found. Please reimport asset. See README.md for details...");
}
if (!Directory.Exists(pathToTempFolder))
{
throw new Exception("Temp folder not found. See README.pdf for details...");
}
using (FileStream zipStream = new FileStream(pathToBinary, FileMode.Open))
{
using (ZipFile zipFile = new ZipFile(zipStream))
{
zipFile.BeginUpdate();
zipFile.Add(Path.Combine(pathToTempFolder, MANIFEST_NAME), MANIFEST_NAME);
zipFile.Add(Path.Combine(pathToTempFolder, PROVIDER_PATHS_NAME), PROVIDER_PATHS_NAME);
zipFile.CommitUpdate();
}
}
}
private static bool IsFileAlreadyOpen(FileInfo file)
{
try
{
using (FileStream stream = file.Open(FileMode.Open, FileAccess.Read, FileShare.None))
{
stream.Close();
}
}
catch (Exception e)
{
Debug.LogError(e.ToString() + ": " + e.Message);
stopedByError = true;
return true;
}
return false;
}
}
}
#endif

View File

@@ -0,0 +1,11 @@
fileFormatVersion: 2
guid: ee86983896a431840a78dbe69fb91189
MonoImporter:
externalObjects: {}
serializedVersion: 2
defaultReferences: []
executionOrder: 0
icon: {instanceID: 0}
userData:
assetBundleName:
assetBundleVariant:

View File

@@ -0,0 +1,8 @@
fileFormatVersion: 2
guid: 01dcac85b4f1656418d69de13cafc0e6
folderAsset: yes
DefaultImporter:
externalObjects: {}
userData:
assetBundleName:
assetBundleVariant:

Binary file not shown.

View File

@@ -0,0 +1,32 @@
fileFormatVersion: 2
guid: cbf7fb971dec3432db468a27adbc4fcb
PluginImporter:
externalObjects: {}
serializedVersion: 2
iconMap: {}
executionOrder: {}
defineConstraints: []
isPreloaded: 0
isOverridable: 0
isExplicitlyReferenced: 0
validateReferences: 1
platformData:
- first:
Android: Android
second:
enabled: 1
settings: {}
- first:
Any:
second:
enabled: 0
settings: {}
- first:
Editor: Editor
second:
enabled: 0
settings:
DefaultValueInitialized: true
userData:
assetBundleName:
assetBundleVariant:

View File

@@ -0,0 +1,8 @@
fileFormatVersion: 2
guid: 17969fed461284447af370c88b439a3e
folderAsset: yes
DefaultImporter:
externalObjects: {}
userData:
assetBundleName:
assetBundleVariant:

View File

@@ -0,0 +1,75 @@
/*MIT License
Copyright(c) 2020 Mikhail5412
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
*/
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
namespace UnityAndroidOpenUrl
{
//string[] mimeTypes =
// {"application/msword","application/vnd.openxmlformats-officedocument.wordprocessingml.document", // .doc & .docx
// "application/vnd.ms-powerpoint","application/vnd.openxmlformats-officedocument.presentationml.presentation", // .ppt & .pptx
// "application/vnd.ms-excel","application/vnd.openxmlformats-officedocument.spreadsheetml.sheet", // .xls & .xlsx
// "text/plain",
// "application/pdf",
// "application/zip"};
public static class AndroidOpenUrl
{
public static void OpenFile(string url, string dataType = "")//"application/pdf"
{
AndroidJavaObject clazz = new AndroidJavaClass("com.unity3d.player.UnityPlayer");
AndroidJavaObject currentActivity = clazz.GetStatic<AndroidJavaObject>("currentActivity");
AndroidJavaObject intent = new AndroidJavaObject("android.content.Intent");
intent.Call<AndroidJavaObject>("addFlags", intent.GetStatic<int>("FLAG_GRANT_READ_URI_PERMISSION"));
intent.Call<AndroidJavaObject>("setAction", intent.GetStatic<string>("ACTION_VIEW"));
var apiLevel = new AndroidJavaClass("android.os.Build$VERSION").GetStatic<int>("SDK_INT");
AndroidJavaObject uri;
if (apiLevel > 23)
{
AndroidJavaClass fileProvider = new AndroidJavaClass("android.support.v4.content.FileProvider");
AndroidJavaObject file = new AndroidJavaObject("java.io.File", url);
AndroidJavaObject unityContext = currentActivity.Call<AndroidJavaObject>("getApplicationContext");
string packageName = unityContext.Call<string>("getPackageName");
string authority = packageName + ".fileprovider";
uri = fileProvider.CallStatic<AndroidJavaObject>("getUriForFile", unityContext, authority, file);
}
else
{
var uriClazz = new AndroidJavaClass("android.net.Uri");
var file = new AndroidJavaObject("java.io.File", url);
uri = uriClazz.CallStatic<AndroidJavaObject>("fromFile", file);
}
if (!string.IsNullOrEmpty(dataType))
{
intent.Call<AndroidJavaObject>("setType", dataType);
}
intent.Call<AndroidJavaObject>("setData", uri);
currentActivity.Call("startActivity", intent);
}
}
}

View File

@@ -0,0 +1,11 @@
fileFormatVersion: 2
guid: b07f4973c298676448f66cb780c4f6b2
MonoImporter:
externalObjects: {}
serializedVersion: 2
defaultReferences: []
executionOrder: 0
icon: {instanceID: 0}
userData:
assetBundleName:
assetBundleVariant: