0

I created simple plugin for android apps. But for some strange reason the result of calling of my function is always "false". My plugin should inform the app about is phone muted or not. Here is code of my plugin:

import android.app.Fragment;
import android.content.Context;
import android.media.AudioManager;

public class AndroidMuteCtrl extends Fragment  {

    public static String debugThis()
    {
        return "Test message from AndroidMuteCtrl plugin.";
    }

    public boolean isMuted()
    {
        AudioManager audio = (AudioManager) this.getActivity().getApplicationContext().getSystemService(Context.AUDIO_SERVICE);
        if (audio.getRingerMode() ==  AudioManager.RINGER_MODE_NORMAL) return false;
        else  return  true;
    }

}

And my c# code:

//...
AndroidJavaClass pluginClass = new AndroidJavaClass("com.overly.mutecontrol.AndroidMuteCtrl");
//...
bool isMuted = pluginClass.Call<bool>("isMuted"); // ALWAYS FALSE
//...
Programmer
  • 121,791
  • 22
  • 236
  • 328

1 Answers1

0

This is because AudioManager requires a reference to Activity or Context to work.

The line:

(AudioManager) this.getActivity()

should fail miserably since there is non. You need to send the current Activity or Context from Unity plugin to a static function then you can call that.

Also, it is totally useless to extend Fragment here.

This is how to send Context to java plugin and this is how to send Activity to java plugin.

In this case, I will send Context to the plugin.

Java:

public final class AndroidMuteCtrl{

    static Context myContext;
    // Called From C# to get the Context Instance
    public static void receiveContextInstance(Context tempContext) {
        myContext = tempContext;
    }

    public static String debugThis()
    {
        return "Test message from AndroidMuteCtrl plugin.";
    }

    public static boolean isMuted()
    {
        AudioManager audio = myContext.getSystemService(Context.AUDIO_SERVICE);
        if (audio.getRingerMode() ==  AudioManager.RINGER_MODE_NORMAL) return false;
        else  return  true;
    }
}

C#:

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

AndroidJavaClass pluginClass = new AndroidJavaClass("com.overly.mutecontrol.AndroidMuteCtrl");
//Send the Context
pluginClass.CallStatic("receiveContextInstance", unityContext);
bool isMuted = pluginClass.CallStatic<bool>("isMuted"); 

This was typed into the Editor directly and is not tested, so you may have to modify it a little bit to get it working.

Programmer
  • 121,791
  • 22
  • 236
  • 328