Search code examples
javaandroidandroid-vibration

Android API, return a double value resulted from a function inside a class


Using the Android API, inside a Java class, I am trying to return whether the vibration feature is supported in the form of a double. I need it double because this is the datatype supported in a framework I am using. I tried it two ways but the first one crashes the compiler and the second just returns "undefined" in the app.

This crashes,

public static double vibration_supported() {

    double value = 0; // complains about it not being final, but you cannot set the value if it is

    Handler h = new Handler(RunnerJNILib.ms_context.getMainLooper());
    h.post(new Runnable() {

        @Override
        public void run() {
            Vibrator v = (Vibrator) RunnerJNILib.ms_context.getSystemService(Context.VIBRATOR_SERVICE);
            if (v.hasVibrator()) {
                value = 1;
            } else {
                value = 0;
            }
        }

    });

    return value;

}

This just returns undefined.

public static double vibration_supported() {

    double value = 0;

    Vibrator v = (Vibrator) RunnerJNILib.ms_context.getSystemService(Context.VIBRATOR_SERVICE);
    if (v.hasVibrator()) {
        value = 1;
        return value;
    } else {
        value = 0;
        return value;
    }


}

Solution

  • Found the answer, I needed to check against the build version before using hasVibrator(),

    if (android.os.Build.VERSION.SDK_INT >= 11) {
        Vibrator v = (Vibrator) RunnerJNILib.ms_context.getSystemService(Context.VIBRATOR_SERVICE);
        return ((v.hasVibrator()) ? 1 : 0);
    } else {
        return 1;
    }