summaryrefslogtreecommitdiffstats
path: root/src/com/android/settings/accessibility/VibrationPreferenceFragment.java
blob: 1803a8bafe23bca4dcd7af0631cf8f1b646a1f3d (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
/*
 * Copyright (C) 2018 The Android Open Source Project
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package com.android.settings.accessibility;

import static android.os.Vibrator.VibrationIntensity;

import android.content.Context;
import android.database.ContentObserver;
import android.graphics.drawable.Drawable;
import android.media.AudioAttributes;
import android.net.Uri;
import android.os.Handler;
import android.os.VibrationEffect;
import android.os.Vibrator;
import android.provider.Settings;
import android.text.TextUtils;
import android.util.ArrayMap;
import android.util.Log;

import androidx.annotation.VisibleForTesting;

import com.android.settings.R;
import com.android.settings.widget.RadioButtonPickerFragment;
import com.android.settingslib.widget.CandidateInfo;

import java.util.ArrayList;
import java.util.Comparator;
import java.util.List;
import java.util.Map;

/**
 * Fragment for changing vibration settings.
 */
public abstract class VibrationPreferenceFragment extends RadioButtonPickerFragment {
    private static final String TAG = "VibrationPreferenceFragment";

    @VisibleForTesting
    final static String KEY_INTENSITY_OFF = "intensity_off";
    @VisibleForTesting
    final static String KEY_INTENSITY_LOW = "intensity_low";
    @VisibleForTesting
    final static String KEY_INTENSITY_MEDIUM = "intensity_medium";
    @VisibleForTesting
    final static String KEY_INTENSITY_HIGH = "intensity_high";
    // KEY_INTENSITY_ON is only used when the device doesn't support multiple intensity levels.
    @VisibleForTesting
    final static String KEY_INTENSITY_ON = "intensity_on";

    private final Map<String, VibrationIntensityCandidateInfo> mCandidates;
    private final SettingsObserver mSettingsObserver;

    public VibrationPreferenceFragment() {
        mCandidates = new ArrayMap<>();
        mSettingsObserver = new SettingsObserver();
    }

    @Override
    public void onAttach(Context context) {
        super.onAttach(context);
        mSettingsObserver.register();
        if (mCandidates.isEmpty()) {
            loadCandidates(context);
        }
    }

    private void loadCandidates(Context context) {
        final boolean supportsMultipleIntensities = context.getResources().getBoolean(
                R.bool.config_vibration_supports_multiple_intensities);
        if (supportsMultipleIntensities) {
            mCandidates.put(KEY_INTENSITY_OFF,
                    new VibrationIntensityCandidateInfo(KEY_INTENSITY_OFF,
                        R.string.accessibility_vibration_intensity_off,
                        Vibrator.VIBRATION_INTENSITY_OFF));
            mCandidates.put(KEY_INTENSITY_LOW,
                    new VibrationIntensityCandidateInfo(KEY_INTENSITY_LOW,
                        R.string.accessibility_vibration_intensity_low,
                        Vibrator.VIBRATION_INTENSITY_LOW));
            mCandidates.put(KEY_INTENSITY_MEDIUM,
                    new VibrationIntensityCandidateInfo(KEY_INTENSITY_MEDIUM,
                        R.string.accessibility_vibration_intensity_medium,
                        Vibrator.VIBRATION_INTENSITY_MEDIUM));
            mCandidates.put(KEY_INTENSITY_HIGH,
                    new VibrationIntensityCandidateInfo(KEY_INTENSITY_HIGH,
                        R.string.accessibility_vibration_intensity_high,
                        Vibrator.VIBRATION_INTENSITY_HIGH));
        } else {
            mCandidates.put(KEY_INTENSITY_OFF,
                    new VibrationIntensityCandidateInfo(KEY_INTENSITY_OFF,
                        R.string.switch_off_text, Vibrator.VIBRATION_INTENSITY_OFF));
            mCandidates.put(KEY_INTENSITY_ON,
                    new VibrationIntensityCandidateInfo(KEY_INTENSITY_ON,
                        R.string.switch_on_text, getDefaultVibrationIntensity()));
        }
    }

    private boolean hasVibrationEnabledSetting() {
        return !TextUtils.isEmpty(getVibrationEnabledSetting());
    }

    private void updateSettings(VibrationIntensityCandidateInfo candidate) {
        boolean vibrationEnabled = candidate.getIntensity() != Vibrator.VIBRATION_INTENSITY_OFF;
        if (hasVibrationEnabledSetting()) {
            // Update vibration enabled setting
            final String vibrationEnabledSetting = getVibrationEnabledSetting();
            final boolean wasEnabled = TextUtils.equals(
                        vibrationEnabledSetting, Settings.Global.APPLY_RAMPING_RINGER)
                    ? true
                    : (Settings.System.getInt(
                            getContext().getContentResolver(), vibrationEnabledSetting, 1) == 1);
            if (vibrationEnabled != wasEnabled) {
                if (vibrationEnabledSetting.equals(Settings.Global.APPLY_RAMPING_RINGER)) {
                    Settings.Global.putInt(getContext().getContentResolver(),
                            vibrationEnabledSetting, 0);
                } else {
                    Settings.System.putInt(getContext().getContentResolver(),
                            vibrationEnabledSetting, vibrationEnabled ? 1 : 0);
                }

                int previousIntensity = Settings.System.getInt(getContext().getContentResolver(),
                        getVibrationIntensitySetting(), 0);
                if (vibrationEnabled && previousIntensity == candidate.getIntensity()) {
                    // We can't play preview effect here for all cases because that causes a data
                    // race (VibratorService may access intensity settings before these settings
                    // are updated). But we can't just play it in intensity settings update
                    // observer, because the intensity settings are not changed if we turn the
                    // vibration off, then on.
                    //
                    // In this case we sould play the preview here.
                    // To be refactored in b/132952771
                    playVibrationPreview();
                }
            }
        }
        // There are two conditions that need to change the intensity.
        // First: Vibration is enabled and we are changing its strength.
        // Second: There is no setting to enable this vibration, change the intensity directly.
        if (vibrationEnabled || !hasVibrationEnabledSetting()) {
            // Update vibration intensity setting
            Settings.System.putInt(getContext().getContentResolver(),
                    getVibrationIntensitySetting(), candidate.getIntensity());
        }
    }

    @Override
    public void onDetach() {
        super.onDetach();
        mSettingsObserver.unregister();
    }

    /**
     * Get the setting string of the vibration intensity setting this preference is dealing with.
     */
    protected abstract String getVibrationIntensitySetting();

    /**
     * Get the setting string of the vibration enabledness setting this preference is dealing with.
     */
    protected abstract String getVibrationEnabledSetting();

    /**
     * Get the default intensity for the desired setting.
     */
    protected abstract int getDefaultVibrationIntensity();

    /**
     * When a new vibration intensity is selected by the user.
     */
    protected void onVibrationIntensitySelected(int intensity) { }

    /**
     * Play a vibration effect with intensity just selected by user
     */
    protected void playVibrationPreview() {
        Vibrator vibrator = getContext().getSystemService(Vibrator.class);
        VibrationEffect effect = VibrationEffect.get(VibrationEffect.EFFECT_CLICK);
        AudioAttributes.Builder builder = new AudioAttributes.Builder();
        builder.setUsage(getPreviewVibrationAudioAttributesUsage());
        vibrator.vibrate(effect, builder.build());
    }

    /**
     * Get the AudioAttributes usage for vibration preview.
     */
    protected int getPreviewVibrationAudioAttributesUsage() {
        return AudioAttributes.USAGE_UNKNOWN;
    }

    @Override
    protected List<? extends CandidateInfo> getCandidates() {
        List<VibrationIntensityCandidateInfo> candidates = new ArrayList<>(mCandidates.values());
        candidates.sort(
                Comparator.comparing(VibrationIntensityCandidateInfo::getIntensity).reversed());
        return candidates;
    }

    @Override
    protected String getDefaultKey() {
        int vibrationIntensity = Settings.System.getInt(getContext().getContentResolver(),
                getVibrationIntensitySetting(), getDefaultVibrationIntensity());
        final String vibrationEnabledSetting = getVibrationEnabledSetting();
        final boolean vibrationEnabled = TextUtils.equals(
                        vibrationEnabledSetting, Settings.Global.APPLY_RAMPING_RINGER)
                    ? true
                    : (Settings.System.getInt(
                            getContext().getContentResolver(), vibrationEnabledSetting, 1) == 1);
        if (!vibrationEnabled) {
            vibrationIntensity = Vibrator.VIBRATION_INTENSITY_OFF;
        }
        for (VibrationIntensityCandidateInfo candidate : mCandidates.values()) {
            final boolean matchesIntensity = candidate.getIntensity() == vibrationIntensity;
            final boolean matchesOn = candidate.getKey().equals(KEY_INTENSITY_ON)
                    && vibrationIntensity != Vibrator.VIBRATION_INTENSITY_OFF;
            if (matchesIntensity || matchesOn) {
                return candidate.getKey();
            }
        }
        return null;
    }

    @Override
    protected boolean setDefaultKey(String key) {
        VibrationIntensityCandidateInfo candidate = mCandidates.get(key);
        if (candidate == null) {
            Log.e(TAG, "Tried to set unknown intensity (key=" + key + ")!");
            return false;
        }
        updateSettings(candidate);
        onVibrationIntensitySelected(candidate.getIntensity());
        return true;
    }

    @VisibleForTesting
    class VibrationIntensityCandidateInfo extends CandidateInfo {
        private String mKey;
        private int mLabelId;
        @VibrationIntensity
        private int mIntensity;

        public VibrationIntensityCandidateInfo(String key, int labelId, int intensity) {
            super(true /* enabled */);
            mKey = key;
            mLabelId = labelId;
            mIntensity = intensity;
        }

        @Override
        public CharSequence loadLabel() {
            return getContext().getString(mLabelId);
        }

        @Override
        public Drawable loadIcon() {
            return null;
        }

        @Override
        public String getKey() {
            return mKey;
        }

        public int getIntensity() {
            return mIntensity;
        }
    }

    private class SettingsObserver extends ContentObserver {
        public SettingsObserver() {
            super(new Handler());
        }

        public void register() {
            getContext().getContentResolver().registerContentObserver(
                    Settings.System.getUriFor(getVibrationIntensitySetting()), false, this);
        }

        public void unregister() {
            getContext().getContentResolver().unregisterContentObserver(this);
        }

        @Override
        public void onChange(boolean selfChange, Uri uri) {
            updateCandidates();
            playVibrationPreview();
        }
    }
}