【问题标题】:Read Android intent extra data on Unity app launch阅读有关 Unity 应用启动的 Android Intent 额外数据
【发布时间】:2016-03-19 05:54:17
【问题描述】:

我正在使用自定义隐式 Intent 从另一个 Android 应用程序启动 Unity 应用程序。这工作正常,但我不知道如何在 Unity 中读取意图额外数据?

Android 打算推出 UNITY 应用程序

i=new Intent();
i.setAction("com.company.unityapp.MyMethod");
i.putExtra("KEY","This is the message string");
startActivity(i);

UNITY APP AndroidManifest.xml

<intent-filter>
     <action android:name="com.company.unityapp.MyMethod" />
     <category android:name="android.intent.category.DEFAULT" />
</intent-filter>

我的场景中有一个带有脚本的游戏对象。在 start 方法中,我有这段代码来尝试读取与意图一起传递的额外数据

AndroidJavaClass UnityPlayer = new AndroidJavaClass("com.unity3d.player.UnityPlayer"); 
AndroidJavaObject currentActivity = UnityPlayer.GetStatic<AndroidJavaObject>("currentActivity");

AndroidJavaObject intent = currentActivity.Call<AndroidJavaObject>("getIntent");
bool hasExtra = intent.Call<bool> ("hasExtra", "arguments");

if (hasExtra) {
 AndroidJavaObject extras = intent.Call<AndroidJavaObject> ("getExtras");
 arguments = extras.Call<string> ("getString", "arguments");
}

这不起作用,并且参数始终为空。任何帮助将不胜感激。

【问题讨论】:

    标签: c# android android-intent unity3d android-implicit-intent


    【解决方案1】:

    我花了很长时间才弄清楚这一点。在网上找到的所有解决方案都只是部分完成。以下是使用自定义隐式 Intent 从另一个 Android 应用程序启动 Unity 应用程序的完整解决方案,以及如何访问 Unity 内部使用 Intent 发送的额外数据。

    为此,您需要创建一个 Android 插件,Unity 将使用该插件来访问 Intent 额外数据。

    安卓插件:


    您需要将Unity安装文件夹中的classes.jar复制到android插件文件夹/lib/classes.jar

    public class MainActivity extends UnityPlayerActivity {
    
      @Override
      protected void onNewIntent(Intent intent) {
          super.onNewIntent(intent);
          handleNewIntent(intent);
      }
    
      private void handleNewIntent(Intent intent){
          String text = intent.getStringExtra("KEY");
          UnityPlayer.UnitySendMessage("AccessManager","OnAccessToken", text);
      }
    }
    

    AndroidManifest.xml

    这里重要的是使用的包名:com.company.plugin

    <?xml version="1.0" encoding="utf-8"?>
    <manifest xmlns:android="http://schemas.android.com/apk/res/android" package="com.company.plugin">
        <application
            android:allowBackup="true" android:icon="@mipmap/ic_launcher" android:label="@string/app_name"
            android:supportsRtl="true" android:theme="@style/AppTheme">
            <activity
                android:name=".MainActivity"
                android:label="@string/app_name"
                android:theme="@style/AppTheme.NoActionBar">
                <intent-filter>
                    <action android:name="android.intent.action.MAIN" />
                    <category android:name="android.intent.category.LAUNCHER" />
                </intent-filter>
            </activity>
        </application>
    </manifest>
    

    Gradle 构建文件:

    将以下内容添加到 app gradle 构建文件中,以便能够创建与 Unity 一起使用的 .jar

    android {
        compileSdkVersion 23
        buildToolsVersion "23.0.2"
        sourceSets {
            main {
                java {
                    srcDir 'src/main/java'
                }
            }
        }       
    ...
    ...
    
    dependencies {
        compile fileTree(dir: 'libs', include: ['*.jar'])
        compile 'com.android.support:appcompat-v7:23.2.1'
        compile 'com.android.support:design:23.2.1'
        compile files('libs/classes.jar')
    }
    
    //task to delete the old jar
    task deleteOldJar(type: Delete) {
        delete 'release/AndroidPlugin.jar'
    }
    
    //task to export contents as jar
    task exportJar(type: Copy) {
        from('build/intermediates/bundles/release/')
        into('release/')
        include('classes.jar')
        ///Rename the jar
        rename('classes.jar', 'AndroidPlugin.jar')
    }
    
    exportJar.dependsOn(deleteOldJar, build)
    

    将创建的AndroidPlugin.jar复制到Unity Assets/Plugins/Android

    统一应用程序:


    PlayerSettings中的包标识符设置为与Android插件中设置的相同 - com.company.plugin

    在 Assets/Plugins/Android 中创建自定义 AndroidManifest.xml 文件

    这里重要的是使用与插件中相同的package 名称。 还要注意 Intent 名称:com.company.plugin.do

    AndroidManifest.XML

    <?xml version="1.0" encoding="utf-8"?>
    <manifest xmlns:android="http://schemas.android.com/apk/res/android" package="com.company.plugin"
          android:versionCode="1" android:versionName="1.0">
        <uses-sdk android:minSdkVersion="9" />
        <application android:label="@string/app_name">
            <activity android:name=".MainActivity" android:label="@string/app_name"
              android:launchMode="singleTask" android:configChanges="fontScale|keyboard|keyboardHidden|locale|mnc|mcc|navigation|orientation|screenLayout|screenSize|smallestScreenSize|uiMode|touchscreen" android:screenOrientation="sensor">
                <intent-filter>
                    <action android:name="android.intent.action.MAIN" />
                    <category android:name="android.intent.category.LAUNCHER" />
                </intent-filter>
                <intent-filter>
                    <action android:name="com.company.plugin.do" />
                    <category android:name="android.intent.category.DEFAULT" />
                <data android:mimeType="text/plain"/>
                </intent-filter>
            </activity>
        </application>
    </manifest>
    

    创建一个名为 AccessManager 的统一脚本,并将该脚本附加到场景中的游戏对象。 OnAccessToken 是接收从 android 插件发送的消息并包含从 Intent 发送的额外数据的方法。

    public class accessManager : MonoBehaviour {
    
        public void OnAccessToken(string accessToken)
        {
            Debug.Log("Message Received!!!! :" + accessToken);
        }
    }
    

    安卓应用:

    创建一个标准的 Android 应用程序,它将启动 Unity 应用程序并发送 Intent 额外数据

    public void LaunchUnityApp(){
        Intent i=new Intent();
        i.setAction("com.company.plugin.do");
        i.setType("text/plain");
        i.putExtra("KEY","This is the text message sent from Android");
        startActivity(i);
    }
    

    【讨论】:

    • 嘿哈代,感谢您的简短解释。我遵循了整个程序。 Native App 确实会启动 Unity App 但无法获取消息。知道我可能做错了什么吗?
    • 我也看到了同样的行为。如果应用程序正在运行,则很好,但如果应用程序必须启动,则游戏对象尚未生成以接收消息
    • 解决方案有一个问题:获取启动参数应该在onCreate()调用而不是onNewIntent()中完成。这就是其他人看到上述问题的原因。
    【解决方案2】:

    您不需要插件来实现这一点。像这样从 Android 中实现你的意图:

    Intent launchIntent = getPackageManager().getLaunchIntentForPackage("com.package.game");
    launchIntent.putExtra("my_text", "Some data params");
    if(launchIntent != null){
        startActivity(launchIntent);
    }else{
        Log.d("Unity", "Couldnt start unity game");
    }
    

    然后在你的统一 Monobehaviour 类中,像这样接收它

    private void Awake () {
        getIntentData ();
    }
    
    private bool getIntentData () {
    #if (!UNITY_EDITOR && UNITY_ANDROID)
        return CreatePushClass (new AndroidJavaClass ("com.unity3d.player.UnityPlayer"));
    #endif
        return false;
    }
    
    public bool CreatePushClass (AndroidJavaClass UnityPlayer) {
    #if UNITY_ANDROID
        AndroidJavaObject currentActivity = UnityPlayer.GetStatic<AndroidJavaObject> ("currentActivity");
        AndroidJavaObject intent = currentActivity.Call<AndroidJavaObject> ("getIntent");
        AndroidJavaObject extras = GetExtras (intent);
    
        if (extras != null) {
            string ex = GetProperty (extras, "my_text");
            return true;
        }
    #endif
        return false;
    }
    
    private AndroidJavaObject GetExtras (AndroidJavaObject intent) {
        AndroidJavaObject extras = null;
    
        try {
            extras = intent.Call<AndroidJavaObject> ("getExtras");
        } catch (Exception e) {
            Debug.Log (e.Message);
        }
    
        return extras;
    }
    
    private string GetProperty (AndroidJavaObject extras, string name) {
        string s = string.Empty;
    
        try {
            s = extras.Call<string> ("getString", name);
        } catch (Exception e) {
            Debug.Log (e.Message);
        }
    
        return s;
    }
    

    来源:https://wenrongdev.com/get-android-intent-data-for-unity/

    (更新)https://wenrongdev.com/posts/get-android-intent-data-for-unity/

    【讨论】:

    • 仅供参考:bundle id 必须是 "com.unity3d.player.UnityPlayer" - 我尝试使用我的包名 / Application.identifier,但它在运行时总是失败,AndroidJavaException: java.lang.ClassNotFoundException: com.company.project.UnityPlayer
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-08-20
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多