Java – Continues to vibrate even after the Android screen enters sleep mode

Continues to vibrate even after the Android screen enters sleep mode… here is a solution to the problem.

Continues to vibrate even after the Android screen enters sleep mode

In my application, I start VIBRATOR_SERVICE with the following code

long[] pattern = {50,100,1000}
Vibrator vibe=(Vibrator) context.getSystemService(Context.VIBRATOR_SERVICE);
vibe.vibrate(pattern, 0);

I

want the vibration to continue until I call

vibe.cancel();

The code runs fine, but the vibration disappears when the screen goes into sleep mode.

I expect the vibration to continue even after the screen goes into sleep mode. Is there any way to do this? Please help me.

Thanks in advance. 🙂

Solution

The correct answer to the question is as follows

BEFORE DOING THIS, DON’T FORGET TO ADD THE PERMISSION “ANDROID.PERMISSION.VIBRATE" TO YOUR APP LIST FILE.

public BroadcastReceiver vibrateReceiver = new BroadcastReceiver() {
    @Override
    public void onReceive(Context context, Intent intent) {
        if(intent.getAction().equals(Intent.ACTION_SCREEN_OFF)) {
            vibe.vibrate(pattern, 0);
        }
    }
};

IntentFilter filter = new IntentFilter(Intent.ACTION_SCREEN_OFF);
registerReceiver(vibrateReceiver, filter);

Wakelock doesn’t work here because the receiver only receives the intent after the screen goes off. Although we can get a wakelock after the screen goes into off mode, the vibration stops because it occurs at ACTION_SCREEN_OFF. So it can be done by restarting the vibration after receiving the broadcast.

Related Problems and Solutions