Continue vibration even after the screen goes to sleep mode in Android

元气小坏坏 提交于 2020-01-23 10:04:21

问题


In my application, I am starting the VIBRATOR_SERVICE through the following code

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

I want the vibration continue till I call

vibe.cancel();

The Code is working fine, but the vibration getting off when the screen goes to sleep mode.

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

Thanks in advance. :)


回答1:


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 manifest 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 will not work here, because the receiver will receive the intent only after the screen goes off. Though we can acquire the wakelock after the screen goes to off mode the vibration stops, because it happens with the ACTION_SCREEN_OFF. So it can be done by starting the vibration again after receiving the broadcast.




回答2:


Try this it might help you. First make broadcast receiver for this such that when mobile light screen off then write logic of vibrate mobile.

 public BroadcastReceiver wakeLockReceiver = new BroadcastReceiver() {
    @Override
    public void onReceive(Context context, Intent intent)
    {
        if(intent.getAction().equals(Intent.ACTION_SCREEN_OFF)) {
            //WRITE LOGIC OF VIBRATION.
        }
    }
};

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

Add permission in AndroidManifest.xml

<uses-permission android:name="android.permission.VIBRATE"/>


来源:https://stackoverflow.com/questions/14561551/continue-vibration-even-after-the-screen-goes-to-sleep-mode-in-android

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!