我前段时间偶然发现了这一点,但仍然不确定为什么 Unity 构建要求这些权限。无论如何,要摆脱它们,您可以使用编辑器脚本作为解决方法:
protected void BuildAPKCustom(string buildPath)
{
bool manifestFileExists = false;
if(File.Exists(Path.Combine(Application.dataPath, "Plugins/Android/AndroidManifest.xml")))
{
manifestFileExists = true;
File.Copy(Path.Combine(Application.dataPath, "Plugins/Android/AndroidManifest.xml"), Path.Combine(Application.dataPath, "Plugins/Android/tmpManifestFile.xml"));
File.Delete(Path.Combine(Application.dataPath, "Plugins/Android/AndroidManifest.xml"));
}
string[] levels = new string[EditorSceneManager.sceneCount];
for (int i = 0; i < levels.Length; i++)
{
levels[i] = EditorSceneManager.GetSceneAt(i).path;
}
BuildPipeline.BuildPlayer(levels, buildPath, BuildTarget.Android, BuildOptions.None);
XNamespace android = "http://schemas.android.com/apk/res/android";
string generatedXMLFilePath = Path.Combine(Application.dataPath, "../Temp/StagingArea/AndroidManifest.xml");
XDocument doc = XDocument.Load(generatedXMLFilePath);
IEnumerable<XElement> permissionElements = doc.Root.Elements("uses-permission");
foreach(XElement permission in permissionElements)
{
int potentialIndex = PERMISSIONS_NAMES_TO_DELETE.IndexOf(permission.Attribute(android + "name").Value.Replace("android.permission.", ""));
if(potentialIndex >= 0)
{
UnityEngine.Debug.Log("Permission deleted : " + PERMISSIONS_NAMES_TO_DELETE[potentialIndex]);
permission.Remove();
}
}
XElement overwritenPermission;
for(int i = 0; i < PERMISSIONS_NAMES_TO_DELETE.Length; i++)
{
overwritenPermission = new XElement("uses-permission");
overwritenPermission.Add(new XAttribute(android + "name", "android.permission." + PERMISSIONS_NAMES_TO_DELETE[i]));
overwritenPermission.Add(new XAttribute(android + "maxSdkVersion", "18"));
doc.Element("manifest").Add(overwritenPermission);
}
if(!Directory.Exists(Path.Combine(Application.dataPath, "Plugins/Android")))
{
Directory.CreateDirectory(Path.Combine(Application.dataPath, "Plugins/Android"));
}
doc.Save(Path.Combine(Application.dataPath, "Plugins/Android/AndroidManifest.xml"));
BuildPipeline.BuildPlayer(levels, buildPath, BuildTarget.Android, BuildOptions.None);
if(manifestFileExists)
{
File.Delete(Path.Combine(Application.dataPath, "Plugins/Android/AndroidManifest.xml"));
File.Copy(Path.Combine(Application.dataPath, "Plugins/Android/tmpManifestFile.xml"), Path.Combine(Application.dataPath, "Plugins/Android/AndroidManifest.xml"));
File.Delete(Path.Combine(Application.dataPath, "Plugins/Android/tmpManifestFile.xml"));
}
Process.Start(Path.GetDirectoryName(buildPath));
}
(PERMISSIONS_NAMES_TO_DELETE
作为string[]
要删除的权限名称之一。要获取权限名称列表,您可以查看此处)
它的作用是:
- 在/Android/Plugins/文件夹中获取之前的AndroidManifest.xml文件(如果存在),将其复制到一个临时文件并删除它
- 执行第一次构建,让 Unity 自己生成一个AndroidManifest.xml文件
- 编辑清单以“删除”不必要的权限
- 将编辑后的清单保存到/Android/Plugins/
- 使用正确设置的清单执行第二次构建
权限删除背后的想法是将最大 API 级别设置为这样的较低级别,权限将不可用(请注意权限必须存在于此 API 级别)。
希望这可以帮助,