1 /* 2 * Copyright (C) 2018 The Android Open Source Project 3 * 4 * Licensed under the Apache License, Version 2.0 (the "License"); 5 * you may not use this file except in compliance with the License. 6 * You may obtain a copy of the License at 7 * 8 * http://www.apache.org/licenses/LICENSE-2.0 9 * 10 * Unless required by applicable law or agreed to in writing, software 11 * distributed under the License is distributed on an "AS IS" BASIS, 12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 * See the License for the specific language governing permissions and 14 * limitations under the License. 15 */ 16 17 package com.android.systemui.statusbar; 18 19 import android.content.Context; 20 import android.database.ContentObserver; 21 import android.media.AudioAttributes; 22 import android.os.AsyncTask; 23 import android.os.Handler; 24 import android.os.UserHandle; 25 import android.os.VibrationEffect; 26 import android.os.Vibrator; 27 import android.provider.Settings; 28 29 public class VibratorHelper { 30 31 private final Vibrator mVibrator; 32 private final Context mContext; 33 private boolean mHapticFeedbackEnabled; 34 private static final AudioAttributes STATUS_BAR_VIBRATION_ATTRIBUTES = 35 new AudioAttributes.Builder() 36 .setContentType(AudioAttributes.CONTENT_TYPE_SONIFICATION) 37 .setUsage(AudioAttributes.USAGE_ASSISTANCE_SONIFICATION) 38 .build(); 39 40 final private ContentObserver mVibrationObserver = new ContentObserver(Handler.getMain()) { 41 @Override 42 public void onChange(boolean selfChange) { 43 updateHapticFeedBackEnabled(); 44 } 45 }; 46 47 public VibratorHelper(Context context) { 48 mContext = context; 49 mVibrator = context.getSystemService(Vibrator.class); 50 51 mContext.getContentResolver().registerContentObserver( 52 Settings.System.getUriFor(Settings.System.HAPTIC_FEEDBACK_ENABLED), true, 53 mVibrationObserver); 54 mVibrationObserver.onChange(false /* selfChange */); 55 } 56 57 public void vibrate(final int effectId) { 58 if (mHapticFeedbackEnabled) { 59 AsyncTask.execute(() -> 60 mVibrator.vibrate(VibrationEffect.get(effectId, false /* fallback */), 61 STATUS_BAR_VIBRATION_ATTRIBUTES)); 62 } 63 } 64 65 private void updateHapticFeedBackEnabled() { 66 mHapticFeedbackEnabled = Settings.System.getIntForUser(mContext.getContentResolver(), 67 Settings.System.HAPTIC_FEEDBACK_ENABLED, 0, UserHandle.USER_CURRENT) != 0; 68 } 69 } 70