Search Unity

How to transfer a parameter from an android application to a unity game on android?

Discussion in 'Android' started by Argument, Jun 3, 2020.

  1. Argument

    Argument

    Joined:
    Jul 5, 2015
    Posts:
    20
    I use Xamarin Form to create an android application.
    My code is:
    Code (CSharp):
    1. Intent intent = Android.App.Application.Context.PackageManager.GetLaunchIntentForPackage("com.myapp.game_unity");
    2. if (intent != null)
    3. {
    4.     intent.AddFlags(ActivityFlags.NewTask);
    5.     intent.PutExtra("test_key", "test_val");
    6.     Android.App.Application.Context.StartActivity(intent);
    7. }
    8. else
    9. {
    10.     intent = new Intent(Intent.ActionView);
    11.     intent.AddFlags(ActivityFlags.NewTask);
    12.     intent.SetData(Android.Net.Uri.Parse("market://details?id=com.myapp.game_unity"));
    13.     intent.PutExtra("test_key", "test_val");
    14.     Android.App.Application.Context.StartActivity(intent);
    15. }
    where I want to pass the parameter "test_val" to the game. The game starts, but I can’t get the parameter.

    In the game, I try to get this parameter, but nothing works.
    My code:
    Code (CSharp):
    1. var intent = new AndroidJavaClass("android.content.Intent");
    2. var extras = intent.Call<AndroidJavaObject>("getExtras");
    3. var val = extras.Call<string> ("getString", "test_key");
    How can I pass the parameter with android app to the unity game (android)?

    Unity version: 2019.3.0f6
     
    Last edited: Jun 3, 2020
  2. Argument

    Argument

    Joined:
    Jul 5, 2015
    Posts:
    20
    Answer: https://answers.unity.com/questions/610587/call-unity-apk-with-intent-and-read-extras.html

    Code (CSharp):
    1. string arguments = "";
    2.  
    3. AndroidJavaClass UnityPlayer = new AndroidJavaClass("com.unity3d.player.UnityPlayer");
    4. AndroidJavaObject currentActivity = UnityPlayer.GetStatic<AndroidJavaObject>("currentActivity");
    5.  
    6. AndroidJavaObject intent = currentActivity.Call<AndroidJavaObject>("getIntent");
    7. bool hasExtra = intent.Call<bool> ("hasExtra", "test_key");
    8.  
    9. if (hasExtra) {
    10.     AndroidJavaObject extras = intent.Call<AndroidJavaObject> ("getExtras");
    11.     arguments = extras.Call<string> ("getString", "test_key");
    12. }
    13.