-1

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;
    }


}
user780756
  • 1,376
  • 3
  • 19
  • 31
  • What's "undefined"? Why the Runnable/Thread? What non-obvious thing are you trying to accomplish which you can't just do with `return ((Vibrator)context.getSystemService( Context.VIBRATOR_SERVICE )).hasVibrator() ? 1.0 : 0.0;` – 323go Sep 14 '14 at 16:58
  • Okay it seems the Runnable() is not required. It does seem that I get "undefined" when I am trying to use hasVibrator(), perhaps my device doesn't support it? Should I use something like if (v) { return 1; } instead? – user780756 Sep 14 '14 at 18:10
  • 1
    What's your target API level? `hasVibrator()` was introduced in API 11. – 323go Sep 14 '14 at 23:42
  • Ah I needed to check against API level 11. So I used if (android.os.Build.VERSION.SDK_INT >= 11) { } and it worked. Thanks! – user780756 Sep 16 '14 at 12:15

1 Answers1

0

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;
}
user780756
  • 1,376
  • 3
  • 19
  • 31