1 /*
2  * Copyright (C) 2014 Google Inc. All Rights Reserved.
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.example.android.wearable.jumpingjack;
18 
19 import android.content.Context;
20 import android.content.SharedPreferences;
21 import android.os.Vibrator;
22 import android.preference.PreferenceManager;
23 
24 /**
25  * A utility class for some helper methods.
26  */
27 public class Utils {
28 
29     private static final int DEFAULT_VIBRATION_DURATION_MS = 200; // in millis
30     private static final String PREF_KEY_COUNTER = "counter";
31 
32     /**
33      * Causes device to vibrate for the given duration (in millis). If duration is set to 0, then it
34      * will use the <code>DEFAULT_VIBRATION_DURATION_MS</code>.
35      */
vibrate(Context context, int duration)36     public final static void vibrate(Context context, int duration) {
37         if (duration == 0) {
38             duration = DEFAULT_VIBRATION_DURATION_MS;
39         }
40         Vibrator v = (Vibrator) context.getSystemService(Context.VIBRATOR_SERVICE);
41         v.vibrate(duration);
42     }
43 
44     /**
45      * Saves the counter value in the preference storage. If <code>value</code>
46      * is negative, then the value will be removed from the preferences.
47      */
saveCounterToPreference(Context context, int value)48     public static void saveCounterToPreference(Context context, int value) {
49         SharedPreferences pref = PreferenceManager.getDefaultSharedPreferences(context);
50         if (value < 0) {
51             // we want to remove
52             pref.edit().remove(PREF_KEY_COUNTER).apply();
53         } else {
54             pref.edit().putInt(PREF_KEY_COUNTER, value).apply();
55         }
56     }
57 
58     /**
59      * Retrieves the value of counter from preference manager. If no value exists, it will return
60      * <code>0</code>.
61      */
getCounterFromPreference(Context context)62     public static int getCounterFromPreference(Context context) {
63         SharedPreferences pref = PreferenceManager.getDefaultSharedPreferences(context);
64         return pref.getInt(PREF_KEY_COUNTER, 0);
65     }
66 
67 }
68