错误:java.lang.NullPointerException:尝试调用虚拟方法'android.content.res.XmlResourceParser

时间:2017-07-13 12:31:22

标签: c# android unity3d android-context android-fileprovider

我收到此错误。我是android studio的新手,我需要创建这个插件,以便在运行时安装apk

错误 - 尝试在空对象引用上调用虚拟方法'android.content.Context Android.content.Context.getApplicationContext()'

插件类 -

package com.example.unitypluginappinstall;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.net.Uri;
import android.support.v4.content.FileProvider;

import java.io.File;

public class PluginClass extends Activity  {
static String errMessage;

public static String InstallApp(String ApkPath){
 try {
     errMessage = "test";
     File toInstall = new File(ApkPath);
     Uri apkUri = FileProvider.getUriForFile(ContextClass.context(), 
ContextClass.context().getApplicationContext().getPackageName() + 
".fileprovider", toInstall);
     Intent intent = new Intent(Intent.ACTION_INSTALL_PACKAGE);
     intent.setData(apkUri);
     intent.setFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
     ContextClass.context().startActivity(intent);
 }
 catch (Exception e){
    errMessage = e.getMessage();
 }
    return errMessage;
}

}

ContextClass -

package com.example.unitypluginappinstall;

import android.app.Application;
import android.content.Context;

public class ContextClass extends Application {
private  static ContextClass instance;

public ContextClass(){
    instance = this;
}

public static ContextClass instance(){
    return instance;
}

public static Context context() {
    return instance.getApplicationContext();
}
}

清单文件 -

<manifest xmlns:android="http://schemas.android.com/apk/res/android"

package="com.example.unitypluginappinstall">

<application android:allowBackup="true" android:label="@string/app_name"
    android:supportsRtl="true">
    <provider
        android:name="android.support.v4.content.FileProvider"
        android:authorities="${applicationId}.fileprovider"
        android:exported="false"
        android:grantUriPermissions="true">
        <meta-data android:name="android.support.FILE_PROVIDER_PATHS"
            android:resource="@xml/filepaths"></meta-data>
    </provider>
    android:name=".ContextClass">
</application>

PluginWrapper:

public class PluginWrapper : MonoBehaviour {
string savePath;
void Start () {
    savePath = Path.Combine(Application.persistentDataPath, "data");
    savePath = Path.Combine(savePath, "applaunchtest.apk");
    Install();
}

void Install(){
try
    {
        //Install APK
        GameObject.Find("TextDebug").GetComponent<Text().text"Installing...";
        var plugin = new 
   AndroidJavaClass("com.example.unitypluginappinstall.PluginClass");
        GameObject.Find("TextDebug").GetComponent<Text>().text = 
   plugin.CallStatic<string>("InstallApp", savePath);
    }
    catch(Exception e)
    {
        GameObject.Find("TextDebug").GetComponent<Text>().text = e.Message;
    }
}
}

编辑 - 插件类

package com.example.unitypluginappinstall;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.net.Uri;
import android.support.v4.content.FileProvider;

import java.io.File;

public class PluginClass extends Activity  {
static String errMessage;

public static String InstallApp(Context context, String ApkPath){
 try {
     errMessage = "test";
     File toInstall = new File(ApkPath);
     Uri apkUri = FileProvider.getUriForFile(context,
             context.getApplicationContext().getPackageName() +
                     ".fileprovider", toInstall);
     Intent intent = new Intent(Intent.ACTION_INSTALL_PACKAGE);
     intent.setData(apkUri);
     intent.setFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
     context.startActivity(intent);
 }
 catch (Exception e){
    errMessage = e.getMessage();
 }
    return errMessage;
}

}

插件包装 -

public class PluginWrapper : MonoBehaviour {
string savePath;
void Start () {
    savePath = Path.Combine(Application.persistentDataPath, "data");
    savePath = Path.Combine(savePath, "applaunchtest.apk");
    Install();
}

void Install(){
try
    {
        //Install APK
AndroidJavaClass unityClass = new AndroidJavaClass("com.unity3d.player.UnityPlayer");
        AndroidJavaObject unityActivity = unityClass.GetStatic<AndroidJavaObject>("currentActivity");
        AndroidJavaObject unityContext = unityActivity.Call<AndroidJavaObject>("getApplicationContext");
        GameObject.Find("TextDebug").GetComponent<Text().text"Installing...";
        var plugin = new 
   AndroidJavaClass("com.example.unitypluginappinstall.PluginClass");
        GameObject.Find("TextDebug").GetComponent<Text>().text = 
   plugin.CallStatic<string>("InstallApp",unityContext, savePath);
    }
    catch(Exception e)
    {
        GameObject.Find("TextDebug").GetComponent<Text>().text = e.Message;
    }
}
}

修改

Plugins/Android

1 个答案:

答案 0 :(得分:2)

来自Java插件的Contect是null。如果需要,您必须将Unity的上下文发送到Java插件。

添加另一个接收Context的参数,然后使用参数中的上下文而不是来自Android.content.Context.getApplicationContext()的参数。

<强>爪哇:

public static String InstallApp(Context context, String ApkPath){
 try {
     errMessage = "test";
     File toInstall = new File(ApkPath);
     Uri apkUri = FileProvider.getUriForFile(context, 
context.getPackageName() + 
".fileprovider", toInstall);
     Intent intent = new Intent(Intent.ACTION_INSTALL_PACKAGE);
     intent.setData(apkUri);
     intent.setFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
     context.startActivity(intent);
 }
 catch (Exception e){
    errMessage = e.getMessage();
 }
    return errMessage;
}

<强> C#:

发送Unity Context以及您要传递给该功能的路径。

void Install()
{
    try
    {
        GameObject.Find("TextDebug").GetComponent<Text>().text = "Installing...";

        //Get Unity Context
        AndroidJavaClass unityClass = new AndroidJavaClass("com.unity3d.player.UnityPlayer");
        AndroidJavaObject unityActivity = unityClass.GetStatic<AndroidJavaObject>("currentActivity");
        AndroidJavaObject unityContext = unityActivity.Call<AndroidJavaObject>("getApplicationContext");


        AndroidJavaClass plugin = new AndroidJavaClass("com.example.unitypluginappinstall.PluginClass");
        string result = plugin.CallStatic<string>("InstallApp", unityContext, savePath);
    }
    catch (Exception e)
    {
        GameObject.Find("TextDebug").GetComponent<Text>().text = e.Message;
    }
}

您可能有其他无关的错误,但Context null问题应该消失。

修改

如果你得到例外:

  

尝试调用虚方法   “android.content.res.XmlResourceParser   android.content.pm.packageItemInfo.loadXmlMetaData(android.c ontent.pm.PackageMan ager.java.lang.Strin克)'

你必须做一些事情。

1 。将“.jar”插件插入 UnityProject / Assets / Plugins / Android 目录。

2 。从“AndroidSDK / extras / android / support / v4 / android-support-v4.jar”复制“android-support-v4.jar”  目录到“UnityProject / Assets / Plugins / Android”目录。

3 。在 UnityProject / Assets / Plugins / Android 目录中创建名为“AndroidManifest.xml”的文件,并将下面的代码放入其中。

确保将“com.company.product”替换为您自己的软件包名称。这出现了 2 个实例。你必须更换它们:

可在 package =“com.company.product” android:authorities =“com.company.product.fileprovider”中找到。请勿更改或删除“fileprovider”,也不要更改任何其他内容。

这是“AndroidManifest.xml”文件:

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android" package="com.company.product" xmlns:tools="http://schemas.android.com/tools" android:installLocation="preferExternal" android:versionName="1.0" android:versionCode="1">
  <supports-screens android:smallScreens="true" android:normalScreens="true" android:largeScreens="true" android:xlargeScreens="true" android:anyDensity="true" />
  <application android:theme="@style/UnityThemeSelector" android:icon="@drawable/app_icon" android:label="@string/app_name" android:debuggable="true">
    <activity android:name="com.unity3d.player.UnityPlayerActivity" android:label="@string/app_name">
      <intent-filter>
        <action android:name="android.intent.action.MAIN" />
        <category android:name="android.intent.category.LAUNCHER" />
      </intent-filter>
      <meta-data android:name="unityplayer.UnityActivity" android:value="true" />
    </activity>

    <provider
          android:name="android.support.v4.content.FileProvider"
          android:authorities="com.company.product.fileprovider"
          android:exported="false"
          android:grantUriPermissions="true">
      <meta-data
          android:name="android.support.FILE_PROVIDER_PATHS"
          android:resource="@xml/provider_paths"/>
    </provider>

  </application>
  <uses-sdk android:minSdkVersion="16" android:targetSdkVersion="23" />
</manifest>

4 。在“UnityProject / Assets / Plugins / Android / res / xml”中创建名为“ provider_paths.xml ”的新文件目录并将下面的代码放入其中。如您所见,您必须创建 res ,然后创建 xml 文件夹。

确保将“com.company.product”替换为您自己的软件包名称。 它只出现一次

以下是您应该在“ provider_paths.xml ”文件中添加的内容:

<?xml version="1.0" encoding="utf-8"?>
<paths xmlns:android="http://schemas.android.com/apk/res/android">
  <!--<external-path name="external_files" path="."/>-->
  <external-path path="Android/data/com.company.product" name="files_root" />
  <external-path path="." name="external_storage_root" />
</paths>

就是这样。