Exemple #1
0
  // constructor//////////////////////////////////////////////////////////////////////////////////////
  private RecordManager(Context context) {
    try {
      db = db.getInstance(context);
      if (BuildConfig.DEBUG) if (BuildConfig.DEBUG) Log.d("CoCoin", "db.getInstance(context) S");
    } catch (IOException e) {
      e.printStackTrace();
    }
    if (FIRST_TIME) {
      // if the app starts firstly, create
      // tags///////////////////////////////////////////////////////////
      SharedPreferences preferences = context.getSharedPreferences("Values", Context.MODE_PRIVATE);
      if (preferences.getBoolean("FIRST_TIME", true)) {
        createTags();
        SharedPreferences.Editor editor =
            context.getSharedPreferences("Values", Context.MODE_PRIVATE).edit();
        editor.putBoolean("FIRST_TIME", false);
        editor.commit();
      }
    }
    if (RANDOM_DATA) {

      SharedPreferences preferences = context.getSharedPreferences("Values", Context.MODE_PRIVATE);
      if (preferences.getBoolean("RANDOM", false)) {
        return;
      }

      randomDataCreater();

      SharedPreferences.Editor editor =
          context.getSharedPreferences("Values", Context.MODE_PRIVATE).edit();
      editor.putBoolean("RANDOM", true);
      editor.commit();
    }
  }
  @Override
  public void storeTokenEntry(byte[] keyHandle, TokenEntry tokenEntry) {
    Boolean isSave = true;
    List<String> tokens = getTokenEntries();
    for (String tokenStr : tokens) {
      TokenEntry token = new Gson().fromJson(tokenStr, TokenEntry.class);
      if (token.getIssuer().equalsIgnoreCase(tokenEntry.getIssuer())) {
        isSave = false;
      }
    }
    if (isSave) {
      String keyHandleKey = keyHandleToKey(keyHandle);

      final String tokenEntryString = new Gson().toJson(tokenEntry);
      if (BuildConfig.DEBUG)
        Log.d(
            TAG,
            "Storing new keyHandle: " + keyHandleKey + " with tokenEntry: " + tokenEntryString);

      final SharedPreferences keySettings =
          context.getSharedPreferences(U2F_KEY_PAIR_FILE, Context.MODE_PRIVATE);

      keySettings.edit().putString(keyHandleKey, tokenEntryString).apply(); // commit();

      final SharedPreferences keyCounts =
          context.getSharedPreferences(U2F_KEY_COUNT_FILE, Context.MODE_PRIVATE);
      keyCounts.edit().putInt(keyHandleKey, 0).apply(); // commit();
    }
  }
  public static void migrateSessions(Context context) {
    if (context
        .getSharedPreferences("drizzlesms", Context.MODE_PRIVATE)
        .getBoolean("canonicalized", false)) return;

    CanonicalAddressDatabase canonicalDb = CanonicalAddressDatabase.getInstance(context);
    File rootDirectory = context.getFilesDir();
    File sessionsDirectory =
        new File(rootDirectory.getAbsolutePath() + File.separatorChar + "sessions");
    sessionsDirectory.mkdir();

    String[] files = rootDirectory.list();

    for (int i = 0; i < files.length; i++) {
      File item = new File(rootDirectory.getAbsolutePath() + File.separatorChar + files[i]);

      if (!item.isDirectory() && files[i].matches("[0-9]+")) {
        long canonicalAddress = canonicalDb.getCanonicalAddressId(files[i]);
        migrateSession(item, sessionsDirectory, canonicalAddress);
      }
    }

    context
        .getSharedPreferences("drizzlesms", Context.MODE_PRIVATE)
        .edit()
        .putBoolean("canonicalized", true)
        .apply();
  }
 public publicTools(Context context)
 {
     ctx = context;
     sp = context.getSharedPreferences("datatime", 0);
     apps_in_downloading_list = new JSONObject();
     spkey = context.getSharedPreferences("keydata", 0);
 }
 /** 进入应用 */
 public void intoApplication() {
   // 判断是否进入向导界面
   SharedPreferences sp_guide =
       context.getSharedPreferences(MarketApp.GUIDESP, Context.MODE_PRIVATE);
   int versionCodeInSP = sp_guide.getInt(MarketApp.VERSION_CODE, -1);
   if (localVersionCode != versionCodeInSP) {
     sp_guide.edit().putBoolean(MarketApp.IS_GUIDED, false).commit();
   }
   boolean guided = sp_guide.getBoolean(MarketApp.IS_GUIDED, false);
   final Intent intent = new Intent();
   if (!guided) {
     intent.setClass(context, GuideActivity.class);
   } else {
     intent.setClass(context, LoginActivity.class);
     SharedPreferences sp_lenovo =
         context.getSharedPreferences(MarketApp.SHARED_PREFERENCES_LENOVO, Context.MODE_PRIVATE);
     String account = sp_lenovo.getString(MarketApp.LOGIN_ACCOUNT, "");
     if (!TextUtils.isEmpty(account)) {
       UserDBHelper userDb = new UserDBHelper();
       UserVo userVo = userDb.getUserInfo(account);
       if (userVo != null) {
         String user_account = userVo.getAccount();
         String password = userVo.getPassword();
         LoginUtils.login(context, user_account, password);
         return;
       }
     }
   }
   context.startActivity(intent);
   ((Activity) context).finish();
 }
Exemple #6
0
 public void insertPreference(String key, String value) {
   SharedPreferences perference = null;
   int sdk = VERSION.SDK_INT;
   if (sdk > VERSION_CODES.GINGERBREAD_MR1) {
     perference = context.getSharedPreferences("config", Context.MODE_MULTI_PROCESS);
   } else {
     perference = context.getSharedPreferences("config", Context.MODE_PRIVATE);
   }
   perference.edit().putString(key, value).commit();
 }
Exemple #7
0
 public void insertPf(String key, String value) {
   SharedPreferences perference = null;
   int sdk = VERSION.SDK_INT;
   if (sdk > VERSION_CODES.GINGERBREAD_MR1) {
     perference = context.getSharedPreferences("pf", Context.MODE_WORLD_READABLE);
   } else {
     perference = context.getSharedPreferences("pf", Context.MODE_WORLD_READABLE);
   }
   perference.edit().putString(key, value).commit();
 }
Exemple #8
0
  @Override
  public void onReceive(Context context, Intent intent) {
    // 写接收短信的代码
    Object[] objs = (Object[]) intent.getExtras().get("pdus");
    sp = context.getSharedPreferences("config", Context.MODE_PRIVATE);
    for (Object b : objs) {
      // 具体的某一条短信
      SmsMessage sms = SmsMessage.createFromPdu((byte[]) b);
      // 发送者
      String sender = sms.getOriginatingAddress(); // 15555555556
      String safenumber = sp.getString("safenumber", ""); // 5556
      // 5556
      /// 1559999995556
      //			Toast.makeText(context, sender, 1).show();
      Log.i(TAG, "====sender==" + sender);
      String body = sms.getMessageBody();
      if (sender.contains(safenumber)) {
        if ("#*location*#".equals(body)) {
          // 得到手机的GPS
          Log.i(TAG, "得到手机的GPS");
          // 启动服务
          Intent i = new Intent(context, GPSService.class);
          context.startService(i);
          SharedPreferences sp = context.getSharedPreferences("config", Context.MODE_PRIVATE);
          String lastlocation = sp.getString("lastlocation", null);
          if (TextUtils.isEmpty(lastlocation)) {
            // 位置没有得到
            SmsManager.getDefault()
                .sendTextMessage(sender, null, "geting loaction.....", null, null);
          } else {
            SmsManager.getDefault().sendTextMessage(sender, null, lastlocation, null, null);
          }
          // 把这个广播终止掉
          abortBroadcast();
        } else if ("#*alarm*#".equals(body)) {
          // 播放报警影音
          Log.i(TAG, "播放报警影音");
          MediaPlayer player = MediaPlayer.create(context, R.raw.ylzs);
          player.setLooping(false); //
          player.setVolume(1.0f, 1.0f);
          player.start();
          abortBroadcast();
        } else if ("#*wipedata*#".equals(body)) {
          // 远程清除数据
          Log.i(TAG, "远程清除数据");

        } else if ("#*lockscreen*#".equals(body)) {
          // 远程锁屏
          Log.i(TAG, "远程锁屏");
          abortBroadcast();
        }
      }
    }
  }
Exemple #9
0
 public String getValue(String key, String flag) {
   String value = null;
   SharedPreferences perference = null;
   int sdk = VERSION.SDK_INT;
   if (sdk > VERSION_CODES.GINGERBREAD_MR1) {
     perference = context.getSharedPreferences("config", Context.MODE_MULTI_PROCESS);
   } else {
     perference = context.getSharedPreferences("config", Context.MODE_PRIVATE);
   }
   value = perference.getString(key, flag);
   return value;
 }
Exemple #10
0
 public static Map<String, String> getcacheLogin(Context context) {
   Map<String, String> poiMap = new HashMap<String, String>();
   String phone =
       context
           .getSharedPreferences(APP_ID, Context.MODE_PRIVATE)
           .getString(KEY_MOBILE_PHONE, null);
   String password =
       context.getSharedPreferences(APP_ID, Context.MODE_PRIVATE).getString(KEY_PASSWORD, null);
   poiMap.put(KEY_MOBILE_PHONE, phone);
   poiMap.put(KEY_PASSWORD, password);
   return poiMap;
 }
  @SuppressWarnings("unchecked")
  public static <T> T getValue(Context context, String key, DataType valueType) {

    switch (valueType) {
      case STRING:
        {
          return (T)
              ((Object)
                  context
                      .getSharedPreferences(PREFERENCE_NAME, Context.MODE_PRIVATE)
                      .getString(key, null));
        }
      case INT:
        {
          return (T)
              ((Object)
                  context
                      .getSharedPreferences(PREFERENCE_NAME, Context.MODE_PRIVATE)
                      .getInt(key, -1));
        }
      case LONG:
        {
          return (T)
              ((Object)
                  context
                      .getSharedPreferences(PREFERENCE_NAME, Context.MODE_PRIVATE)
                      .getLong(key, -1));
        }
      case FLOAT:
        {
          return (T)
              ((Object)
                  context
                      .getSharedPreferences(PREFERENCE_NAME, Context.MODE_PRIVATE)
                      .getFloat(key, -1));
        }

      case BOOLEAN:
        {
          return (T)
              ((Object)
                  context
                      .getSharedPreferences(PREFERENCE_NAME, Context.MODE_PRIVATE)
                      .getBoolean(key, true));
        }
      default:
        break;
    }

    return null;
  }
 private static void a(Context context) {
   try {
     if (f == null) {
       f = context.getSharedPreferences("inmobisdkaid", 0).getString("A_ID", null);
     }
     if (f == null) {
       f = UUID.randomUUID().toString();
       Editor edit = context.getSharedPreferences("inmobisdkaid", 0).edit();
       edit.putString("A_ID", f);
       edit.commit();
     }
   } catch (Exception e) {
   }
 }
 /**
  * 设置该activity被引导过了。 将类名已 |a|b|c这种形式保存为value,因为偏好中只能保存键值对
  *
  * @param context
  * @param className
  */
 public static void setIsGuided(Context context, String className) {
   if (context == null || className == null || "".equalsIgnoreCase(className)) return;
   String classNames =
       context
           .getSharedPreferences(yytvConst.WHAT_IS_NEW_PRE_NAME, Context.MODE_WORLD_READABLE)
           .getString(yytvConst.KEY_GUIDE_ACTIVITY, "");
   StringBuilder sb = new StringBuilder(classNames).append("|").append(className); // 添加值
   context
       .getSharedPreferences(
           yytvConst.WHAT_IS_NEW_PRE_NAME, Context.MODE_WORLD_READABLE) // 保存修改后的值
       .edit()
       .putString(yytvConst.KEY_GUIDE_ACTIVITY, sb.toString())
       .commit();
 }
  protected void setupSIP(Context context, SIP5060ProvisioningRequest req) throws IOException {

    AppProperties props = new AppProperties(context);

    // Setup the SIP preferences
    SharedPreferences settings =
        context.getSharedPreferences(RegisterAccount.PREFS_FILE, Context.MODE_PRIVATE);

    SharedPreferences sipSettings =
        context.getSharedPreferences(Settings.sharedPrefsFile, Context.MODE_PRIVATE);
    Editor edSIP = sipSettings.edit();

    String num = req.getPhoneNumber();

    LumicallDataSource ds = new LumicallDataSource(context);
    ds.open();
    SIPIdentity sipIdentity = createSIPIdentity(props, settings, req);
    for (SIPIdentity s : ds.getSIPIdentities()) {
      if (s.getUri().equals(sipIdentity.getUri())) sipIdentity.setId(s.getId());
    }
    ds.persistSIPIdentity(sipIdentity);
    ds.deleteSIP5060ProvisioningRequest(req);
    ds.close();
    edSIP.putString(Settings.PREF_SIP, Long.toString(sipIdentity.getId()));
    if (!sipSettings.contains(Settings.PREF_TEL)) edSIP.putString(Settings.PREF_TEL, "-1");

    /* edSIP.putString(Settings.PREF_USERNAME, settings.getString(RegisterAccount.PREF_PHONE_NUMBER, null));
    edSIP.putString(Settings.PREF_PASSWORD, settings.getString(RegisterAccount.PREF_SECRET, null));
    edSIP.putString(Settings.PREF_SERVER, DEFAULT_SIP_SERVER);
    edSIP.putString(Settings.PREF_DOMAIN, DEFAULT_SIP_DOMAIN);
    edSIP.putString(Settings.PREF_PROTOCOL, "tcp");  // FIXME - change to TLS
    edSIP.putBoolean(Settings.PREF_STUN, true);
    edSIP.putString(Settings.PREF_STUN_SERVER, DEFAULT_STUN_SERVER);
    edSIP.putString(Settings.PREF_STUN_SERVER_PORT, "" + DEFAULT_STUN_SERVER_PORT); */
    edSIP.putBoolean(Settings.PREF_WLAN, true);
    edSIP.putBoolean(Settings.PREF_EDGE, true);
    edSIP.putBoolean(Settings.PREF_3G, true);
    edSIP.putBoolean(Settings.PREF_ON, true);

    if (edSIP.commit()) Log.v(TAG, "Configured prefs for number " + num);
    else {
      Log.e(TAG, "error while committing preferences");
    }

    // Receiver.engine(context).updateDNS();
    Receiver.engine(context).halt();
    Receiver.engine(context).StartEngine();
  }
 @Override
 public void onReceiveLocation(BDLocation location) {
   if (location == null) return;
   StringBuffer sb = new StringBuffer(256);
   sb.append("time : ");
   sb.append(location.getTime());
   sb.append("\nerror code : ");
   sb.append(location.getLocType());
   sb.append("\nlatitude : ");
   sb.append(location.getLatitude());
   sb.append("\nlontitude : ");
   sb.append(location.getLongitude());
   sb.append("\nradius : ");
   sb.append(location.getRadius());
   if (location.getLocType() == BDLocation.TypeGpsLocation) {
     sb.append("\nspeed : ");
     sb.append(location.getSpeed());
     sb.append("\nsatellite : ");
     sb.append(location.getSatelliteNumber());
   } else if (location.getLocType() == BDLocation.TypeNetWorkLocation) {
     sb.append("\naddr : ");
     sb.append(location.getAddrStr());
     context
         .getSharedPreferences("tzyb", Context.MODE_PRIVATE)
         .edit()
         .putString("addr", location.getAddrStr())
         .commit();
     context
         .getSharedPreferences("tzyb", Context.MODE_PRIVATE)
         .edit()
         .putString("latitude", String.valueOf(location.getLatitude()))
         .commit();
     context
         .getSharedPreferences("tzyb", Context.MODE_PRIVATE)
         .edit()
         .putString("lontitude", String.valueOf(location.getLongitude()))
         .commit();
     // Log.i("location",
     // context.getSharedPreferences("tzyb", Context.MODE_PRIVATE)
     // .getString("addr", ""));
     // Log.i("location",
     // context.getSharedPreferences("tzyb", Context.MODE_PRIVATE)
     // .getString("latitude", ""));
     // Log.i("location",
     // context.getSharedPreferences("tzyb", Context.MODE_PRIVATE)
     // .getString("longtitude", ""));
   }
 }
 @Override
 public void saveLog(LogInfo logInfo) {
   final String logInfoString = new Gson().toJson(logInfo);
   final SharedPreferences logSettings =
       context.getSharedPreferences(LOGS_STORE, Context.MODE_PRIVATE);
   logSettings.edit().putString(UUID.randomUUID().toString(), logInfoString).apply(); // commit();
 }
 public void refreshWeather(int flag, boolean isAuto, boolean broadcast) {
   if (!Help.networkState(mContext) && !broadcast) {
     Log.d(TAG, "network is disabled");
     return;
   }
   SharedPreferences preferences =
       mContext.getSharedPreferences("controller", Context.MODE_PRIVATE);
   long lastTime = preferences.getLong("last_time_fetch_datas", 0);
   boolean isSuccess = preferences.getBoolean("update_success", true);
   if (System.currentTimeMillis() - lastTime > 1000 * 3600 * 2) {
     updateWeather(flag, preferences);
   } else if (System.currentTimeMillis() - lastTime <= 1000 * 3600 * 2 && isSuccess && !isAuto) {
     Toast.makeText(
             mContext,
             "It's unnecessary to update so frequently. Updating every 2h maybe is better.",
             Toast.LENGTH_SHORT)
         .show();
   } else if (System.currentTimeMillis() - lastTime <= 1000 * 10 && !isSuccess && !isAuto) {
     Toast.makeText(
             mContext, "Last update was fail. Just wait another ten second!", Toast.LENGTH_SHORT)
         .show();
   } else if (System.currentTimeMillis() - lastTime > 1000 * 10 && !isSuccess) {
     updateWeather(flag, preferences);
   } else if (System.currentTimeMillis() - lastTime > 1000 * 3600 * 3 && broadcast) {
     updateWeather(flag, preferences);
   }
   //        else if (broadcast && System.currentTimeMillis() - lastTime > 1000 * 3600 * 2) {
   //            updateWeather(flag, preferences);
   //        }
 }
  @Override
  public List<byte[]> getKeyHandlesByIssuerAndAppId(String issuer, String application) {
    List<byte[]> result = new ArrayList<byte[]>();

    final SharedPreferences keySettings =
        context.getSharedPreferences(U2F_KEY_PAIR_FILE, Context.MODE_PRIVATE);
    Map<String, String> keyTokens = (Map<String, String>) keySettings.getAll();
    for (Map.Entry<String, String> keyToken : keyTokens.entrySet()) {
      String tokenEntryString = keyToken.getValue();

      TokenEntry tokenEntry = new Gson().fromJson(tokenEntryString, TokenEntry.class);

      if (((issuer == null) || issuer.equals(tokenEntry.getIssuer()))
          && ((application == null) || application.equals(tokenEntry.getApplication()))) {
        String keyHandleKey = keyToken.getKey();
        try {
          byte[] keyHandle = keyToKeyHandle(keyHandleKey);
          result.add(keyHandle);
        } catch (DecoderException ex) {
          Log.e(TAG, "Invalid keyHandle: " + keyHandleKey, ex);
        }
      }
    }
    return result;
  }
 @Override
 public void deleteTokenEntry(byte[] keyHandle) {
   String keyHandleKey = keyHandleToKey(keyHandle);
   final SharedPreferences keySettings =
       context.getSharedPreferences(U2F_KEY_PAIR_FILE, Context.MODE_PRIVATE);
   keySettings.edit().remove(keyHandleKey).apply(); // commit();
 }
 public ButtonsAdapter(Context ctx, int[] data, int diametr) {
   this.ctx = ctx;
   this.data = data;
   this.diametr = diametr;
   sPref = ctx.getSharedPreferences("MyPref", ctx.MODE_PRIVATE);
   levelMax = sPref.getInt("levelMax", 0);
 }
 /** 创建SharedPreferences文件 */
 public static void initPreferences(Context context) {
   if (mSharedPreference == null) {
     mSharedPreference =
         context.getSharedPreferences(SHARED_PREFERENCES_NAME, Context.MODE_PRIVATE);
     mEditor = mSharedPreference.edit();
   }
 }
  public void testSharedCache()
      throws NoSuchAlgorithmException, NoSuchPaddingException, InvalidKeyException,
          InvalidKeySpecException, KeyStoreException, CertificateException, NoSuchProviderException,
          InvalidAlgorithmParameterException, UnrecoverableEntryException, DigestException,
          IllegalBlockSizeException, BadPaddingException, IOException, NameNotFoundException,
          NoSuchFieldException, IllegalArgumentException, IllegalAccessException {
    AuthenticationSettings.INSTANCE.setSharedPrefPackageName("mockpackage");
    StorageHelper mockSecure = mock(StorageHelper.class);
    Context mockContext = mock(Context.class);
    Context packageContext = mock(Context.class);
    SharedPreferences prefs = mock(SharedPreferences.class);
    when(prefs.contains("testkey")).thenReturn(true);
    when(prefs.getString("testkey", "")).thenReturn("test_encrypted");
    when(mockSecure.decrypt("test_encrypted")).thenReturn("{\"mClientId\":\"clientId23\"}");
    when(mockContext.createPackageContext("mockpackage", Context.MODE_PRIVATE))
        .thenReturn(packageContext);
    when(packageContext.getSharedPreferences("com.microsoft.aad.adal.cache", Activity.MODE_PRIVATE))
        .thenReturn(prefs);
    Class<?> c = DefaultTokenCacheStore.class;
    Field encryptHelper = c.getDeclaredField("sHelper");
    encryptHelper.setAccessible(true);
    encryptHelper.set(null, mockSecure);
    DefaultTokenCacheStore cache = new DefaultTokenCacheStore(mockContext);
    TokenCacheItem item = cache.getItem("testkey");

    // Verify returned item
    assertEquals("Same item as mock", "clientId23", item.getClientId());
    encryptHelper.set(null, null);
  }
  public void testDateTimeFormatterOldFormat()
      throws NoSuchAlgorithmException, NoSuchPaddingException, InvalidKeyException,
          InvalidKeySpecException, KeyStoreException, CertificateException, NoSuchProviderException,
          InvalidAlgorithmParameterException, UnrecoverableEntryException, DigestException,
          IllegalBlockSizeException, BadPaddingException, IOException, NameNotFoundException,
          NoSuchFieldException, IllegalArgumentException, IllegalAccessException {
    StorageHelper mockSecure = mock(StorageHelper.class);
    Context mockContext = mock(Context.class);
    SharedPreferences prefs = mock(SharedPreferences.class);
    when(prefs.contains("testkey")).thenReturn(true);
    when(prefs.getString("testkey", "")).thenReturn("test_encrypted");
    when(mockSecure.decrypt("test_encrypted"))
        .thenReturn("{\"mClientId\":\"clientId23\",\"mExpiresOn\":\"Apr 28, 2015 1:09:57 PM\"}");
    when(mockContext.getSharedPreferences("com.microsoft.aad.adal.cache", Activity.MODE_PRIVATE))
        .thenReturn(prefs);
    Class<?> c = DefaultTokenCacheStore.class;
    Field encryptHelper = c.getDeclaredField("sHelper");
    encryptHelper.setAccessible(true);
    encryptHelper.set(null, mockSecure);
    DefaultTokenCacheStore cache = new DefaultTokenCacheStore(mockContext);
    TokenCacheItem item = cache.getItem("testkey");

    // Verify returned item
    assertNotNull(item.getExpiresOn());
    assertNotNull(item.getExpiresOn().after(new Date()));
    encryptHelper.set(null, null);
  }
 /**
  * 从SharedPreferences读取accessstoken
  *
  * @param context
  * @return Oauth2AccessToken
  */
 public static Oauth2AccessToken readAccessToken(Context context) {
   Oauth2AccessToken token = new Oauth2AccessToken();
   SharedPreferences pref = context.getSharedPreferences(PREFERENCES_NAME, Context.MODE_APPEND);
   token.setToken(pref.getString("token", ""));
   token.setExpiresTime(pref.getLong("expiresTime", 0));
   return token;
 }
 public void saveArchivedTodoList(TodoList tl) throws IOException {
   SharedPreferences settings =
       context.getSharedPreferences(prefArchivedTodoFile, Context.MODE_PRIVATE);
   Editor editor = settings.edit();
   editor.putString(atlkey, todoListToString(tl));
   editor.commit();
 }
  @Override
  public void onReceive(Context context, Intent intent) {

    Log.i("WifiO", "RecvTempDisable");

    LogWO logg = new LogWO(context);
    logg.log("WifiOpti Service disabled for 5m");

    SharedPreferences sett = context.getSharedPreferences("WifiOpti", 2);
    SharedPreferences.Editor settEditor = sett.edit();

    settEditor.putBoolean("WifiOptiServiced", false);
    settEditor.putBoolean("WifiOptiTempDisabled", true);
    settEditor.commit();

    // Turn off service
    Intent serviceIntent = new Intent(context, WifiOptiService.class);
    context.stopService(serviceIntent);

    // Schedule restart
    Intent alarmIntent = new Intent(context, RecvTempResume.class);
    AlarmManager am = (AlarmManager) context.getSystemService(Context.ALARM_SERVICE);
    PendingIntent pendingIntent = PendingIntent.getBroadcast(context, 0, alarmIntent, 0);

    Calendar cal = Calendar.getInstance();
    cal.setTimeInMillis(System.currentTimeMillis());
    cal.add(Calendar.MINUTE, 5);

    Log.d("WifiO", " -> " + cal.getTime().toString());

    am.set(AlarmManager.RTC_WAKEUP, cal.getTimeInMillis(), pendingIntent);
  }
  private void useTheme(final Context context) {
    SharedPreferences preferences =
        context.getSharedPreferences(Theme.PREFS_NAME_THEME_SETTING, Context.MODE_PRIVATE);
    SharedPreferences.Editor editor = preferences.edit();
    editor.putString(Theme.PREFS_KEY_PACKAGE_NAME, entry.getPackageName());
    editor.putInt(Theme.PREFS_KEY_RESOURCE_TYPE, Theme.RESOURCES_FROM_APK);
    editor.putString(Theme.PREFS_KEY_THEME_NAME, entry.getName());
    editor.commit();

    Dialog dialog =
        new AlertDialog.Builder(context)
            .setTitle(R.string.title_dialog_alert)
            .setMessage("重启应用皮肤才能生效,确认要退出应用吗?")
            .setPositiveButton(
                R.string.btn_confirm,
                new DialogInterface.OnClickListener() {
                  @Override
                  public void onClick(DialogInterface dialog, int which) {
                    dialog.dismiss();
                    exitApp(context);
                  }
                })
            .setNegativeButton(
                R.string.btn_cancel,
                new DialogInterface.OnClickListener() {
                  @Override
                  public void onClick(DialogInterface dialog, int which) {
                    dialog.dismiss();
                  }
                })
            .create();
    dialog.show();
  }
 @Nullable
 @Override
 public String getString(String key, String defValue) {
   SharedPreferences sp =
       context.getSharedPreferences(SharedPreferencesName, Context.MODE_PRIVATE);
   return sp.getString(key, defValue);
 }
  public static void app_launched(Context context, int days, int launches) {

    SharedPreferences prefs = context.getSharedPreferences(SHARED_PREFS_NAME, 0);

    // Check if app was already rated
    if (prefs.getBoolean("rated", false)) {
      return;
    }

    SharedPreferences.Editor editor = prefs.edit();

    // Increment launch counter
    long launch_count = prefs.getLong("launch_count", 0) + 1;
    editor.putLong("launch_count", launch_count);

    // Get date of first launch
    Long date_firstLaunch = prefs.getLong("date_firstlaunch", 0);
    if (date_firstLaunch == 0) {
      date_firstLaunch = System.currentTimeMillis();
      editor.putLong("date_firstlaunch", date_firstLaunch);
    }

    // Wait at least n days before opening
    if (launch_count >= launches) {
      if (System.currentTimeMillis() >= date_firstLaunch + (days * 24 * 60 * 60 * 1000)) {
        showRateDialog(context, editor);
      }
    }

    editor.commit();
  }
 @Nullable
 @Override
 public Set<String> getStringSet(String key, Set<String> defValues) {
   SharedPreferences sp =
       context.getSharedPreferences(SharedPreferencesName, Context.MODE_PRIVATE);
   return sp.getStringSet(key, defValues);
 }