简体   繁体   English

在 Unity 应用程序启动时读取 Android 意图额外数据

[英]Read Android intent extra data on Unity app launch

I am launching an Unity application from another Android application using a custom implicit intent.我正在使用自定义隐式意图从另一个 Android 应用程序启动 Unity 应用程序。 This is working fine, but I cannot figure out how to read the intent extra data in Unity?这工作正常,但我不知道如何在 Unity 中读取意图额外数据?

ANDROID INTENT TO LAUNCH UNITY APP 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 UNITY APP AndroidManifest.xml

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

I have a GameObject in my scene with a script attached.我的场景中有一个游戏对象,并附有脚本。 Inside the start method I have this code to try and read the extra data that was passed along with the intent在 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");
}

This is not working and arguments is always empty.这不起作用,参数始终为空。 Any help would be appreciated.任何帮助将不胜感激。

It took me quite some time to figure this out.我花了很长时间才弄清楚这一点。 All solutions found online were only partly complete.在网上找到的所有解决方案都只是部分完成。 Below is the full solution for launching a Unity application from another android application using a custom implicit Intent and also how to access the extra data sent with the Intent inside Unity.以下是使用自定义隐式Intent从另一个 android 应用程序启动 Unity 应用程序的完整解决方案,以及如何访问随 Unity 内部Intent发送的额外数据。

To accomplish this you need to create a Android plugin that will be used by Unity to access the Intent extra data.为此,您需要创建一个 Android 插件,Unity 将使用该插件访问Intent额外数据。

ANDROID PLUGIN:安卓插件:


You need to copy the classes.jar from Unity installation folder to the android plugin folder /lib/classes.jar您需要将 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 AndroidManifest.xml

Important here is the package name used: com.company.plugin这里重要的是使用的包名: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 build file: Gradle 构建文件:

Add the following to the app gradle build file to be able to create a .jar to be used with Unity将以下内容添加到应用程序 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)

Copy the created AndroidPlugin.jar to Unity Assets/Plugins/Android将创建的 AndroidPlugin.jar 复制到 Unity Assets/Plugins/Android

UNITY APP:团结应用程序:


Set the bundle identifier in PlayerSettings to be the same as set in the Android Plugin - com.company.pluginPlayerSettings的 bundle identifier 设置为与 Android Plugin - com.company.plugin设置的相同

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

Important here is to use the same package name as used in the plugin.这里重要的是使用与插件中使用的相同的package名。 Also note the Intent name: com.company.plugin.do还要注意意图名称:com.company.plugin.do

AndroidManifest.XML 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>

Create a unity script named AccessManager and attach the script to a game object in the scene.创建一个名为 AccessManager 的统一脚本并将该脚本附加到场景中的游戏对象。 OnAccessToken is the method that will receive the message sent from the android plugin and will contain the extra data sent from the intent. OnAccessToken 是接收从 android 插件发送的消息的方法,并将包含从意图发送的额外数据。

public class accessManager : MonoBehaviour {

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

ANDROID APP:安卓应用:

Create a standard Android application that will launch the Unity Application and send the Intent extra data创建一个标准的 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);
}

You don't need a plugin to achieve this.您不需要插件来实现这一点。 Do your intent from Android like this:像这样从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");
}

Then in your unity Monobehaviour Class, receive it like this然后在你的 unity Monobehaviour Class 中,像这样接收它

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;
}

Credit: https://wenrongdev.com/get-android-intent-data-for-unity/信用: https : //wenrongdev.com/get-android-intent-data-for-unity/

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM