Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Vibration on widget click not working since API 29

EDIT Thanks to YP D's answer, I have a solution. Added at the end


Ever since updating my Pixel 3 to android version 10 (API 29), my application's vibration is not working.

My app requests vibration permission, and has vibration working on earlier (< API 29) versions. Permissions:

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

When connecting my phone to Android Studio and looking at the logcat, I noticed these errors:

2019-09-11 18:46:28.622 1474-1546/? E/NotificationService: Suppressing notification from package by user request.
2019-09-11 18:46:28.816 1474-3294/? E/VibratorService: Ignoring incoming vibration as process with uid = 10284 is background, usage = USAGE_UNKNOWN

My vibration code (durationMs is 50, but I tested with 500 too):

Vibrator v = (Vibrator) context.getSystemService(VIBRATOR_SERVICE);
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
    v.vibrate(VibrationEffect.createOneShot(durationMs, VibrationEffect.DEFAULT_AMPLITUDE));
} else {
    v.vibrate(durationMs);
}

I am running this code via an AppWidgetProvider class, that uses a Handler.postDelayed() thread to do some work.

I have not found anything related to this issue online. What I assume is that since API 29, VibratorService has an issue with background apps.

If that is the case, I am not sure what approach should I take to bring the vibration to the foreground.

I have considered using a Service for the background work, but I found it easier to do work on Handler threads, so I could easily find my Widget view after I am done calculating, and wish to update the on-screen text.


Here is a solution based on YP D's answer:

Vibrator v = (Vibrator) context.getSystemService(VIBRATOR_SERVICE);
AudioAttributes audioAttributes = new AudioAttributes.Builder()
        .setContentType(AudioAttributes.CONTENT_TYPE_SONIFICATION)
        .setUsage(AudioAttributes.USAGE_ALARM)
        .build();
VibrationEffect ve = VibrationEffect.createOneShot(durationMs,
        VibrationEffect.DEFAULT_AMPLITUDE);
v.vibrate(ve, audioAttributes);

The AudioAttributes seem to fix the vibration issue.

like image 378
GalL Avatar asked Sep 11 '19 16:09

GalL


1 Answers

I also encountered the same problem, You can use the following methods to solve

like this

Vibrator mVibrator = (Vibrator) App.getInstance().getSystemService(Context.VIBRATOR_SERVICE);
        long[] pattern = {100, 1000, 100, 1000};
        if (mVibrator != null) {
            AudioAttributes audioAttributes = new AudioAttributes.Builder()
                    .setContentType(AudioAttributes.CONTENT_TYPE_SONIFICATION)
                    .setUsage(AudioAttributes.USAGE_ALARM) //key
                    .build();
            mVibrator.vibrate(pattern, 2, audioAttributes);
}
like image 151
YP D Avatar answered Oct 19 '22 21:10

YP D