Search code examples
javac#unity-game-engineaugmented-realityarcore

What is function of _ShowAndroidToastMessage() in ARCore?


I found this method while reading script of HelloARController in HelloAR, but I couldn't understand this function: private void _ShowAndroidToastMessage(string message)).

Can someone explain this function for me?

/// <summary>
/// Show an Android toast message.
/// </summary>
/// <param name="message">Message string to show in the toast.</param>
private void _ShowAndroidToastMessage(string message)
{
    AndroidJavaClass unityPlayer = new AndroidJavaClass("com.unity3d.player.UnityPlayer");
    AndroidJavaObject unityActivity = unityPlayer.GetStatic<AndroidJavaObject>("currentActivity");

    if (unityActivity != null)
    {
        AndroidJavaClass toastClass = new AndroidJavaClass("android.widget.Toast");
        unityActivity.Call("runOnUiThread", new AndroidJavaRunnable(() =>
        {
            AndroidJavaObject toastObject = toastClass.CallStatic<AndroidJavaObject>("makeText", unityActivity,
                message, 0);
            toastObject.Call("show");
        }));
    }
}

Solution

  • Toasts in Android are used to show Notification within an Activity. You may be knowing what alert messages are in HTML. Using javaScript alert() function we can Alert the user about something using a popup message, the user sees the message and clicks the OK button to dismiss the dialog.

    Toast messages in Android Programming are similar but they are terminated/dismissed by itself (we do not have any buttons). We need to set a time period for which the message has to be displayed, when the time is reached the message fades away, it is usually shown at the bottom of the Activity page.

    _ShowAndroidToastMessage() method is one of the varieties for Toast messaging.

    Here's one more simple example of Toast:

    public class MainActivity extends ActionBarActivity {
    
        @Override
        protected void onCreate(Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
            setContentView(R.layout.activity_main);
    
            View toastView = toast.getView();
            Toast toast = Toast.makeText(this,
                                         "This is a Toast message!", 
                                         Toast.LENGTH_LONG);
    
            toast.setTextColor(Color.WHITE);
            toast.setGravity(Gravity.BOTTOM, 0, 0);
            toastView.setBackgroundColor(Color.RED);
            toast.show();
        }
    }
    

    enter image description here

    Hope this helps.