Continue vibration even after the screen goes to s

2019-05-14 12:47发布

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. :)

2条回答
相关推荐>>
2楼-- · 2019-05-14 13:16

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"/>
查看更多
该账号已被封号
3楼-- · 2019-05-14 13:19

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.

查看更多
登录 后发表回答