Erdem Cantürk Erdem Cantürk - 1 month ago 23
Java Question

Unity3D Vibrate Android

I am working on a simple plugin. Now I am trying to add a vibrate property. But this code is not working. Where am I going wrong? My code is as follows. Can you help me please.

Android:

import android.os.Vibrator;

public class Brid {

private Context context;
private static Brid instance;


public Brid()
{
this.instance = this;
}

public static Brid instance()
{
if(instance == null) {
instance = new Brid();
}
return instance;
}

public void setContext(Context context) {
this.context = context;
}



public void Vibrate()
{
Vibrator v = (Vibrator) this.context.getSystemService(Context.VIBRATOR_SERVICE);
v.vibrate(100);
}


}

Unity3D:

public static void Vibrate(AndroidJavaObject Brid, AndroidJavaObject context)
{
if (Brid == null)
{
using (AndroidJavaClass activityClass = new AndroidJavaClass("com.unity3d.player.UnityPlayer"))
{
context = activityClass.GetStatic<AndroidJavaObject>("currentActivity");
}

using (AndroidJavaClass pluginClass = new AndroidJavaClass("com.xxx.ultimatemobile.Brid"))
{
if (pluginClass != null)
{
Brid = pluginClass.CallStatic<AndroidJavaObject>("instance");
Brid.Call<AndroidJavaObject>("setContext", context);
Brid.Call<AndroidJavaObject>("Vibrate");
}
}
}
}


Button Event:

public void vibrate()
{
#if UNITY_ANDROID

Bridge.Vibrate(null, null);

#endif
}


Thanks in advance...

Answer

My solution as follows.

Unity:

        using (AndroidJavaClass pluginClass = new AndroidJavaClass("com.xx.ultimatemobile.Brid"))
        {
            if (pluginClass != null)
            {
                Brid = pluginClass.CallStatic<AndroidJavaObject>("instance");
                Brid.Call("setContext", context);
                context.Call("runOnUiThread", new AndroidJavaRunnable(() =>
                {
                    Brid.Call("Vibrate");
                }));
            }
        }

Also, I found Manifest.xml file example before 1 minute. Now the plugin is working.