Search code examples
androidbeaconaltbeaconforeground-servicevibration

Android Play Vibration from Foreground Service


What I am doing:

I am making one app using Android Beacon library. I am using RegionBootstrap for implementation of foreground ranging and transmission of Altbeacons.

What I want:

I want to make the phone vibrate for suppose 500 ms when I can find a beacon within certain meters of range even when my app is running as foreground service.

Logic:

Logic is simple, I am performing scanning at a specific interval. Suppose I found beacons A, B, C with distance 1m, 1.5m, 0.6m. Now my threshold distance is 0.8m so I will make the phone vibrate as long as the above condition satisfies, that means user has to go out to make the distance larger so as to stop vibration.

Code I used:

I have found one code snippet to make the vibration

import android.os.Vibrator;
...
Vibrator v = (Vibrator) getSystemService(Context.VIBRATOR_SERVICE);
// Vibrate for 500 milliseconds
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
    v.vibrate(VibrationEffect.createOneShot(500, VibrationEffect.DEFAULT_AMPLITUDE));
} else {
    //deprecated in API 26 
    v.vibrate(500);
}

Issue I am facing:

This works perfectly when my app is open. Once I close the app and the foreground service keeps scanning and transmitting, the vibration doesn't occur.

I am new to android development, kindly help me to resolve this issue.


Solution

  • Try sending a local notification with vibration on the beacon nearby event. This may overcome background restrictions on vibration on your phone model and give you a easy way to confirm the event is firing. If you do not want the visual notification to stick around, you can dismiss it after a few second delay. You can even resend the notification after a second or so to continue the vibration effect until the condition clears.

    A friendly word of caution: take care that these Bluetooth distance estimates are accurate enough for your use case. Other apps like OnePointFive have made the mistake of sending too many false notifications, leading to very unhappy users. You will surely want to be cautious not to repeat their mistake. See the Misusing Bluetooth Estimates section of my blog post here.