List of usage examples for android.content SharedPreferences contains
boolean contains(String key);
From source file:com.yahala.android.NotificationsController.java
private void showOrUpdateNotification(boolean notifyAboutLast) { if (!UserConfig.isClientActivated() || pushMessages.isEmpty()) { dismissNotification();// w w w .j a va 2 s . c o m return; } try { XMPPManager.getInstance().maybeStartReconnect(); MessageObject lastMessageObject = pushMessages.get(0); String dialog_id = lastMessageObject.getDialogId(); // String chat_id = lastMessageObject.messageOwner.to_id.chat_id; String user_jid = lastMessageObject.messageOwner.getJid(); /*if (user_jid == 0) { user_jid = lastMessageObject.messageOwner.from_id; } else if (usjer_id == UserConfig.getClientUserId()) { user_jid = lastMessageObject.messageOwner.from_id; }*/ TLRPC.User user = ContactsController.getInstance().friendsDict.get(user_jid); TLRPC.Chat chat = null; /*if (chat_id != 0) { chat = MessagesController.getInstance().chats.get(chat_id); }*/ TLRPC.FileLocation photoPath = null; boolean notifyDisabled = false; boolean needVibrate = false; String choosenSoundPath = null; int ledColor = 0xff00ff00; boolean inAppSounds = false; boolean inAppVibrate = false; boolean inAppPreview = false; int vibrate_override = 0; SharedPreferences preferences = ApplicationLoader.applicationContext .getSharedPreferences("Notifications", Context.MODE_PRIVATE); int notify_override = preferences.getInt("notify2_" + dialog_id, 0); /* if (!notifyAboutLast || notify_override == 2 || (!preferences.getBoolean("EnableAll", true) || chat_id != 0 && !preferences.getBoolean("EnableGroup", true)) && notify_override == 0) { notifyDisabled = true; }*/ String defaultPath = Settings.System.DEFAULT_NOTIFICATION_URI.getPath(); if (!notifyDisabled) { inAppSounds = preferences.getBoolean("EnableInAppSounds", true); inAppVibrate = preferences.getBoolean("EnableInAppVibrate", true); inAppPreview = preferences.getBoolean("EnableInAppPreview", true); vibrate_override = preferences.getInt("vibrate_" + dialog_id, 0); choosenSoundPath = preferences.getString("sound_path_" + dialog_id, null); /* if (chat_id != 0) { if (choosenSoundPath != null && choosenSoundPath.equals(defaultPath)) { choosenSoundPath = null; } else if (choosenSoundPath == null) { choosenSoundPath = preferences.getString("GroupSoundPath", defaultPath); } needVibrate = preferences.getBoolean("EnableVibrateGroup", true); ledColor = preferences.getInt("GroupLed", 0xff00ff00); } else*/ if (user_jid.equals("0")) { if (choosenSoundPath != null && choosenSoundPath.equals(defaultPath)) { choosenSoundPath = null; } else if (choosenSoundPath == null) { choosenSoundPath = preferences.getString("GlobalSoundPath", defaultPath); } needVibrate = preferences.getBoolean("EnableVibrateAll", true); ledColor = preferences.getInt("MessagesLed", 0xff00ff00); } if (preferences.contains("color_" + dialog_id)) { ledColor = preferences.getInt("color_" + dialog_id, 0); } if (!needVibrate && vibrate_override == 1) { needVibrate = true; } else if (needVibrate && vibrate_override == 2) { needVibrate = false; } if (!ApplicationLoader.mainInterfacePaused) { if (!inAppSounds) { choosenSoundPath = null; } if (!inAppVibrate) { needVibrate = false; } } } Intent intent = new Intent(ApplicationLoader.applicationContext, LaunchActivity.class); intent.setAction("com.tmessages.openchat" + Math.random() + Integer.MAX_VALUE); intent.setFlags(32768); if (dialog_id != "0") { // if (chat_id != 0) { // intent.putExtra("chatId", chat_id); // } else if (user_id != 0) { intent.putExtra("user_jid", user_jid); // } if (pushDialogs.size() == 1) { if (chat != null) { if (chat.photo != null && chat.photo.photo_small != null && chat.photo.photo_small.volume_id != 0 && chat.photo.photo_small.local_id != 0) { photoPath = chat.photo.photo_small; } } else { if (user.photo != null && user.photo.photo_small != null && user.photo.photo_small.volume_id != 0 && user.photo.photo_small.local_id != 0) { photoPath = user.photo.photo_small; } } } } PendingIntent contentIntent = PendingIntent.getActivity(ApplicationLoader.applicationContext, 0, intent, PendingIntent.FLAG_ONE_SHOT); String name = null; boolean replace = true; if (dialog_id == "0" || pushDialogs.size() > 1) { name = LocaleController.getString("AppName", R.string.AppName); replace = false; } else { if (chat != null) { name = chat.title; } else { name = Utilities.formatName(user.first_name, user.last_name); } } String detailText = null; if (pushDialogs.size() == 1) { detailText = LocaleController.formatPluralString("NewMessages", total_unread_count); } else { detailText = String.format("%s %s", LocaleController.formatPluralString("NewMessages", total_unread_count), LocaleController.formatPluralString("FromContacts", pushDialogs.size())); } NotificationCompat.Builder mBuilder = new NotificationCompat.Builder( ApplicationLoader.applicationContext).setContentTitle(name) .setSmallIcon(R.drawable.notification).setAutoCancel(true).setContentText(detailText) .setContentIntent(contentIntent); String lastMessage = null; if (pushMessages.size() == 1) { String message = lastMessage = getStringForMessage(pushMessages.get(0)); if (message == null) { return; } if (replace) { if (chat != null) { message = message.replace(" @ " + name, ""); } else { message = message.replace(name + ": ", "").replace(name + " ", ""); } } mBuilder.setStyle(new NotificationCompat.BigTextStyle().bigText(message)); } else { NotificationCompat.InboxStyle inboxStyle = new NotificationCompat.InboxStyle(); inboxStyle.setBigContentTitle(name); int count = Math.min(10, pushMessages.size()); for (int i = 0; i < count; i++) { String message = getStringForMessage(pushMessages.get(i)); if (message == null) { continue; } if (i == 0) { lastMessage = message; } if (pushDialogs.size() == 1) { if (replace) { if (chat != null) { message = message.replace(" @ " + name, ""); } else { message = message.replace(name + ": ", "").replace(name + " ", ""); } } } inboxStyle.addLine(message); } inboxStyle.setSummaryText(detailText); mBuilder.setStyle(inboxStyle); } if (photoPath != null) { Bitmap img = FileLoader.getInstance().getImageFromMemory(photoPath, null, null, "50_50", false); if (img != null) { mBuilder.setLargeIcon(img); } } if (!notifyDisabled) { if (ApplicationLoader.mainInterfacePaused || inAppPreview) { mBuilder.setTicker(lastMessage); } if (choosenSoundPath != null && !choosenSoundPath.equals("NoSound")) { if (choosenSoundPath.equals(defaultPath)) { mBuilder.setSound(Settings.System.DEFAULT_NOTIFICATION_URI, AudioManager.STREAM_NOTIFICATION); } else { mBuilder.setSound(Uri.parse(choosenSoundPath), AudioManager.STREAM_NOTIFICATION); } } if (ledColor != 0) { mBuilder.setLights(ledColor, 1000, 1000); } if (needVibrate) { mBuilder.setVibrate(new long[] { 0, 100, 0, 100 }); } } else { mBuilder.setVibrate(new long[] { 0, 0 }); } notificationManager.notify(1, mBuilder.build()); if (preferences.getBoolean("EnablePebbleNotifications", false)) { sendAlertToPebble(lastMessage); } } catch (Exception e) { FileLog.e("tmessages", e); } }
From source file:com.hichinaschool.flashcards.async.DeckTask.java
private TaskData doInBackgroundOpenCollection(TaskData... params) { // Log.i(AnkiDroidApp.TAG, "doInBackgroundOpenCollection"); long time = Utils.intNow(1000); Resources res = AnkiDroidApp.getInstance().getBaseContext().getResources(); String collectionFile = params[0].getString(); SharedPreferences prefs = AnkiDroidApp.getSharedPrefs(AnkiDroidApp.getInstance().getBaseContext()); // see, if a collection is still opened Collection oldCol = AnkiDroidApp.getCol(); Collection col = null;/*from w ww. ja v a2s .co m*/ publishProgress(new TaskData(res.getString(R.string.open_collection))); if (!(AnkiDroidApp.colIsOpen() && oldCol.getPath().equals(collectionFile))) { // do a safety backup if last backup is too old --> addresses // android's delete db bug if (BackupManager.safetyBackupNeeded(collectionFile)) { publishProgress(new TaskData(res.getString(R.string.backup_collection))); BackupManager.performBackup(collectionFile); } publishProgress(new TaskData(res.getString(R.string.open_collection))); // load collection try { col = AnkiDroidApp.openCollection(collectionFile); } catch (RuntimeException e) { BackupManager.restoreCollectionIfMissing(collectionFile); Log.e(AnkiDroidApp.TAG, "doInBackgroundOpenCollection - RuntimeException on opening collection: " + e); AnkiDroidApp.saveExceptionReportFile(e, "doInBackgroundOpenCollection"); return new TaskData(false); } // create tutorial deck if needed if (prefs.contains("createTutorial") && prefs.getBoolean("createTutorial", false)) { prefs.edit().remove("createTutorial").commit(); publishProgress(new TaskData(res.getString(R.string.tutorial_load))); doInBackgroundLoadTutorial(new TaskData(col)); } } else { // Log.i(AnkiDroidApp.TAG, "doInBackgroundOpenCollection: collection still open - reusing it"); col = oldCol; } Object[] counts = null; DeckTask.TaskData result = doInBackgroundLoadDeckCounts(new TaskData(col)); if (result != null) { counts = result.getObjArray(); } if (prefs.getBoolean("splashScreen", false)) { long millies = Utils.intNow(1000) - time; if (millies < 1000) { try { Thread.sleep(2200 - millies); } catch (InterruptedException e) { } } } return new TaskData(col, counts); }
From source file:com.nit.async.DeckTask.java
private TaskData doInBackgroundOpenCollection(TaskData... params) { // Log.i(AnkiDroidApp.TAG, "doInBackgroundOpenCollection"); long time = Utils.intNow(1000); Resources res = AnkiDroidApp.getInstance().getBaseContext().getResources(); String collectionFile = params[0].getString(); SharedPreferences prefs = AnkiDroidApp.getSharedPrefs(AnkiDroidApp.getInstance().getBaseContext()); // see, if a collection is still opened Collection oldCol = AnkiDroidApp.getCol(); Collection col = null;//ww w. j a v a2 s .c o m publishProgress(new TaskData(res.getString(R.string.open_collection))); if (!(AnkiDroidApp.colIsOpen() && oldCol.getPath().equals(collectionFile))) { // do a safety backup if last backup is too old --> addresses // android's delete db bug if (BackupManager.safetyBackupNeeded(collectionFile)) { publishProgress(new TaskData(res.getString(R.string.backup_collection))); BackupManager.performBackup(collectionFile); } publishProgress(new TaskData(res.getString(R.string.open_collection))); // load collection try { col = AnkiDroidApp.openCollection(collectionFile); } catch (RuntimeException e) { BackupManager.restoreCollectionIfMissing(collectionFile); Log.e(AnkiDroidApp.TAG, "doInBackgroundOpenCollection - RuntimeException on opening collection: " + e); AnkiDroidApp.saveExceptionReportFile(e, "doInBackgroundOpenCollection"); return new TaskData(false); } // create tutorial deck if needed if (prefs.contains("createTutorial") && prefs.getBoolean("createTutorial", false)) { prefs.edit().remove("createTutorial").commit(); publishProgress(new TaskData(res.getString(R.string.tutorial_load))); doInBackgroundLoadTutorial(new TaskData(col)); } } else { // Log.i(AnkiDroidApp.TAG, "doInBackgroundOpenCollection: collection still open - reusing it"); col = oldCol; } Object[] counts = null; DeckTask.TaskData result = doInBackgroundLoadDeckCounts(new TaskData(col)); if (result != null) { counts = result.getObjArray(); } if (prefs.getBoolean("splashScreen", false)) { long millies = Utils.intNow(1000) - time; if (millies < 1000) { try { Thread.sleep(1200 - millies); } catch (InterruptedException e) { } } } return new TaskData(col, counts); }
From source file:com.ichi2.anki.DeckPicker.java
private void upgradePreferences(int previousVersionCode) { SharedPreferences preferences = AnkiDroidApp.getSharedPrefs(getBaseContext()); // clear all prefs if super old version to prevent any errors if (previousVersionCode < 20300130) { preferences.edit().clear().commit(); }/*from w w w . j a va 2 s. com*/ // when upgrading from before 2.5alpha35 if (previousVersionCode < 20500135) { // Card zooming behaviour was changed the preferences renamed int oldCardZoom = preferences.getInt("relativeDisplayFontSize", 100); int oldImageZoom = preferences.getInt("relativeImageSize", 100); preferences.edit().putInt("cardZoom", oldCardZoom).commit(); preferences.edit().putInt("imageZoom", oldImageZoom).commit(); if (!preferences.getBoolean("useBackup", true)) { preferences.edit().putInt("backupMax", 0).commit(); } preferences.edit().remove("useBackup").commit(); preferences.edit().remove("intentAdditionInstantAdd").commit(); } if (preferences.contains("fullscreenReview")) { // clear fullscreen flag as we use a integer try { boolean old = preferences.getBoolean("fullscreenReview", false); preferences.edit().putString("fullscreenMode", old ? "1" : "0").commit(); } catch (ClassCastException e) { // TODO: can remove this catch as it was only here to fix an error in the betas preferences.edit().remove("fullscreenMode").commit(); } preferences.edit().remove("fullscreenReview").commit(); } }
From source file:com.piusvelte.sonet.SonetService.java
@Override public void onCreate() { super.onCreate(); // handle version changes int currVer = 0; try {/* ww w.j a v a2 s . c o m*/ currVer = getPackageManager().getPackageInfo(getPackageName(), 0).versionCode; } catch (NameNotFoundException e) { e.printStackTrace(); } SharedPreferences sp = PreferenceManager.getDefaultSharedPreferences(getApplicationContext()); if (!sp.contains(getString(R.string.key_version)) || (currVer > sp.getInt(getString(R.string.key_version), 0))) { sp.edit().putInt(getString(R.string.key_version), currVer).commit(); Eidos.requestBackup(this); } mAlarmManager = (AlarmManager) getSystemService(Context.ALARM_SERVICE); mConnectivityManager = (ConnectivityManager) getSystemService(CONNECTIVITY_SERVICE); mSonetCrypto = SonetCrypto.getInstance(getApplicationContext()); // check the instant upload settings startService(Sonet.getPackageIntent(getApplicationContext(), SonetUploader.class)); }
From source file:com.piusvelte.sonet.core.SonetService.java
@Override public void onCreate() { super.onCreate(); // handle version changes int currVer = 0; try {/*from w ww .j ava 2s . c o m*/ currVer = getPackageManager().getPackageInfo(getPackageName(), 0).versionCode; } catch (NameNotFoundException e) { e.printStackTrace(); } SharedPreferences sp = PreferenceManager.getDefaultSharedPreferences(getApplicationContext()); if (!sp.contains(getString(R.string.key_version)) || (currVer > sp.getInt(getString(R.string.key_version), 0))) { sp.edit().putInt(getString(R.string.key_version), currVer).commit(); try { BackupManager.dataChanged(this); } catch (Throwable t) { Log.d(TAG, "backupagent not supported"); } } mAlarmManager = (AlarmManager) getSystemService(Context.ALARM_SERVICE); mConnectivityManager = (ConnectivityManager) getSystemService(CONNECTIVITY_SERVICE); mSonetCrypto = SonetCrypto.getInstance(getApplicationContext()); // check the instant upload settings startService(Sonet.getPackageIntent(getApplicationContext(), SonetUploader.class)); }
From source file:org.mareatlantica.android.NotificationsController.java
private void showOrUpdateNotification(boolean notifyAboutLast) { if (!UserConfig.isClientActivated() || pushMessages.isEmpty()) { dismissNotification();//from w w w. java2 s.co m return; } try { ConnectionsManager.getInstance().resumeNetworkMaybe(); MessageObject lastMessageObject = pushMessages.get(0); long dialog_id = lastMessageObject.getDialogId(); int chat_id = lastMessageObject.messageOwner.to_id.chat_id; int user_id = lastMessageObject.messageOwner.to_id.user_id; if (user_id == 0) { user_id = lastMessageObject.messageOwner.from_id; } else if (user_id == UserConfig.getClientUserId()) { user_id = lastMessageObject.messageOwner.from_id; } TLRPC.User user = MessagesController.getInstance().users.get(user_id); TLRPC.Chat chat = null; if (chat_id != 0) { chat = MessagesController.getInstance().chats.get(chat_id); } TLRPC.FileLocation photoPath = null; boolean notifyDisabled = false; boolean needVibrate = false; String choosenSoundPath = null; int ledColor = 0xff00ff00; boolean inAppSounds = false; boolean inAppVibrate = false; boolean inAppPreview = false; int vibrate_override = 0; SharedPreferences preferences = ApplicationLoader.applicationContext .getSharedPreferences("Notifications", Context.MODE_PRIVATE); int notify_override = preferences.getInt("notify2_" + dialog_id, 0); if (!notifyAboutLast || notify_override == 2 || (!preferences.getBoolean("EnableAll", true) || chat_id != 0 && !preferences.getBoolean("EnableGroup", true)) && notify_override == 0) { notifyDisabled = true; } String defaultPath = Settings.System.DEFAULT_NOTIFICATION_URI.getPath(); if (!notifyDisabled) { inAppSounds = preferences.getBoolean("EnableInAppSounds", true); inAppVibrate = preferences.getBoolean("EnableInAppVibrate", true); inAppPreview = preferences.getBoolean("EnableInAppPreview", true); vibrate_override = preferences.getInt("vibrate_" + dialog_id, 0); choosenSoundPath = preferences.getString("sound_path_" + dialog_id, null); if (chat_id != 0) { if (choosenSoundPath != null && choosenSoundPath.equals(defaultPath)) { choosenSoundPath = null; } else if (choosenSoundPath == null) { choosenSoundPath = preferences.getString("GroupSoundPath", defaultPath); } needVibrate = preferences.getBoolean("EnableVibrateGroup", true); ledColor = preferences.getInt("GroupLed", 0xff00ff00); } else if (user_id != 0) { if (choosenSoundPath != null && choosenSoundPath.equals(defaultPath)) { choosenSoundPath = null; } else if (choosenSoundPath == null) { choosenSoundPath = preferences.getString("GlobalSoundPath", defaultPath); } needVibrate = preferences.getBoolean("EnableVibrateAll", true); ledColor = preferences.getInt("MessagesLed", 0xff00ff00); } if (preferences.contains("color_" + dialog_id)) { ledColor = preferences.getInt("color_" + dialog_id, 0); } if (!needVibrate && vibrate_override == 1) { needVibrate = true; } else if (needVibrate && vibrate_override == 2) { needVibrate = false; } if (!ApplicationLoader.mainInterfacePaused) { if (!inAppSounds) { choosenSoundPath = null; } if (!inAppVibrate) { needVibrate = false; } } } Intent intent = new Intent(ApplicationLoader.applicationContext, LaunchActivity.class); intent.setAction("com.tmessages.openchat" + Math.random() + Integer.MAX_VALUE); intent.setFlags(32768); if ((int) dialog_id != 0) { if (pushDialogs.size() == 1) { if (chat_id != 0) { intent.putExtra("chatId", chat_id); } else if (user_id != 0) { intent.putExtra("userId", user_id); } } if (pushDialogs.size() == 1) { if (chat != null) { if (chat.photo != null && chat.photo.photo_small != null && chat.photo.photo_small.volume_id != 0 && chat.photo.photo_small.local_id != 0) { photoPath = chat.photo.photo_small; } } else { if (user.photo != null && user.photo.photo_small != null && user.photo.photo_small.volume_id != 0 && user.photo.photo_small.local_id != 0) { photoPath = user.photo.photo_small; } } } } else { if (pushDialogs.size() == 1) { intent.putExtra("encId", (int) (dialog_id >> 32)); } } PendingIntent contentIntent = PendingIntent.getActivity(ApplicationLoader.applicationContext, 0, intent, PendingIntent.FLAG_ONE_SHOT); String name = null; boolean replace = true; if ((int) dialog_id == 0 || pushDialogs.size() > 1) { name = LocaleController.getString("AppName", R.string.AppName); replace = false; } else { if (chat != null) { name = chat.title; } else { name = Utilities.formatName(user.first_name, user.last_name); } } String detailText = null; if (pushDialogs.size() == 1) { detailText = LocaleController.formatPluralString("NewMessages", total_unread_count); } else { detailText = String.format("%s %s", LocaleController.formatPluralString("NewMessages", total_unread_count), LocaleController.formatPluralString("FromContacts", pushDialogs.size())); } NotificationCompat.Builder mBuilder = new NotificationCompat.Builder( ApplicationLoader.applicationContext).setContentTitle(name) .setSmallIcon(R.drawable.notification).setAutoCancel(true) .setContentIntent(contentIntent); String lastMessage = null; if (pushMessages.size() == 1) { String message = lastMessage = getStringForMessage(pushMessages.get(0)); if (message == null) { return; } if (replace) { if (chat != null) { message = message.replace(" @ " + name, ""); } else { message = message.replace(name + ": ", "").replace(name + " ", ""); } } mBuilder.setContentText(message); mBuilder.setStyle(new NotificationCompat.BigTextStyle().bigText(message)); } else { mBuilder.setContentText(detailText); NotificationCompat.InboxStyle inboxStyle = new NotificationCompat.InboxStyle(); inboxStyle.setBigContentTitle(name); int count = Math.min(10, pushMessages.size()); for (int i = 0; i < count; i++) { String message = getStringForMessage(pushMessages.get(i)); if (message == null) { continue; } if (i == 0) { lastMessage = message; } if (pushDialogs.size() == 1) { if (replace) { if (chat != null) { message = message.replace(" @ " + name, ""); } else { message = message.replace(name + ": ", "").replace(name + " ", ""); } } } inboxStyle.addLine(message); } inboxStyle.setSummaryText(detailText); mBuilder.setStyle(inboxStyle); } if (photoPath != null) { Bitmap img = FileLoader.getInstance().getImageFromMemory(photoPath, null, null, "50_50"); if (img != null) { mBuilder.setLargeIcon(img); } } if (!notifyDisabled) { if (ApplicationLoader.mainInterfacePaused || inAppPreview) { mBuilder.setTicker(lastMessage); } if (choosenSoundPath != null && !choosenSoundPath.equals("NoSound")) { if (choosenSoundPath.equals(defaultPath)) { mBuilder.setSound(Settings.System.DEFAULT_NOTIFICATION_URI, AudioManager.STREAM_NOTIFICATION); } else { mBuilder.setSound(Uri.parse(choosenSoundPath), AudioManager.STREAM_NOTIFICATION); } } if (ledColor != 0) { mBuilder.setLights(ledColor, 1000, 1000); } if (needVibrate) { mBuilder.setVibrate(new long[] { 0, 100, 0, 100 }); } else { mBuilder.setVibrate(new long[] { 0, 0 }); } } else { mBuilder.setVibrate(new long[] { 0, 0 }); } notificationManager.notify(1, mBuilder.build()); if (preferences.getBoolean("EnablePebbleNotifications", false)) { sendAlertToPebble(lastMessage); } } catch (Exception e) { FileLog.e("tmessages", e); } }
From source file:com.shafiq.myfeedle.core.MyfeedleService.java
@Override public void onCreate() { super.onCreate(); // handle version changes int currVer = 0; try {//from ww w .jav a2 s.c o m currVer = getPackageManager().getPackageInfo(getPackageName(), 0).versionCode; } catch (NameNotFoundException e) { e.printStackTrace(); } SharedPreferences sp = PreferenceManager.getDefaultSharedPreferences(getApplicationContext()); if (!sp.contains(getString(R.string.key_version)) || (currVer > sp.getInt(getString(R.string.key_version), 0))) { sp.edit().putInt(getString(R.string.key_version), currVer).commit(); try { BackupManager.dataChanged(this); } catch (Throwable t) { Log.d(TAG, "backupagent not supported"); } } mAlarmManager = (AlarmManager) getSystemService(Context.ALARM_SERVICE); mConnectivityManager = (ConnectivityManager) getSystemService(CONNECTIVITY_SERVICE); mMyfeedleCrypto = MyfeedleCrypto.getInstance(getApplicationContext()); // check the instant upload settings startService(Myfeedle.getPackageIntent(getApplicationContext(), MyfeedleUploader.class)); }
From source file:com.zion.htf.receiver.AlarmReceiver.java
@Override public void onReceive(Context context, Intent intent) { // Get preferences Resources res = context.getResources(); SharedPreferences pref = PreferenceManager.getDefaultSharedPreferences(context); int setId, alarmId; try {//from w w w .j av a2 s . co m if (0 == (setId = intent.getIntExtra("set_id", 0))) throw new MissingArgumentException("set_id", "int"); if (0 == (alarmId = intent.getIntExtra("alarm_id", 0))) throw new MissingArgumentException("alarm_id", "int"); } catch (MissingArgumentException e) { throw new RuntimeException(e.getMessage()); } // Fetch info about the set try { // VIBRATE will be added if user did NOT disable notification vibration // SOUND won't as it is set even if it is to the default value int flags = Notification.DEFAULT_LIGHTS; MusicSet set = MusicSet.getById(setId); Artist artist = set.getArtist(); SimpleDateFormat dateFormat; if ("fr".equals(Locale.getDefault().getLanguage())) { dateFormat = new SimpleDateFormat("HH:mm", Locale.FRANCE); } else { dateFormat = new SimpleDateFormat("h:mm aa", Locale.ENGLISH); } // Creates an explicit intent for an Activity in your app Intent resultIntent = new Intent(context, ArtistDetailsActivity.class); resultIntent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP | Intent.FLAG_ACTIVITY_SINGLE_TOP);// Do not start a new activity but reuse the existing one (if any) resultIntent.putExtra(ArtistDetailsActivity.EXTRA_SET_ID, setId); // Manipulate the TaskStack in order to get a good back button behaviour. See http://developer.android.com/guide/topics/ui/notifiers/notifications.html TaskStackBuilder stackBuilder = TaskStackBuilder.create(context); stackBuilder.addParentStack(ArtistDetailsActivity.class); stackBuilder.addNextIntent(resultIntent); PendingIntent resultPendingIntent = stackBuilder.getPendingIntent(0, PendingIntent.FLAG_UPDATE_CURRENT); // Extract a bitmap from a file to use a large icon Bitmap largeIconBitmap = BitmapFactory.decodeResource(context.getResources(), artist.getPictureResourceId()); // Builds the notification NotificationCompat.Builder notificationBuilder = new NotificationCompat.Builder(context) .setPriority(NotificationCompat.PRIORITY_MAX).setSmallIcon(R.drawable.ic_stat_notify_app_icon) .setLargeIcon(largeIconBitmap).setAutoCancel(true).setContentIntent(resultPendingIntent) .setContentTitle(artist.getName()) .setContentText(String.format(context.getString(R.string.alarm_notification), artist.getName(), set.getStage(), dateFormat.format(set.getBeginDate()))); // Vibrate settings Boolean defaultVibrate = true; if (!pref.contains(res.getString(R.string.pref_key_notifications_alarms_vibrate))) { // Get the system default for the vibrate setting AudioManager audioManager = (AudioManager) context.getSystemService(Context.AUDIO_SERVICE); if (null != audioManager) { switch (audioManager.getRingerMode()) { case AudioManager.RINGER_MODE_SILENT: defaultVibrate = false; break; case AudioManager.RINGER_MODE_NORMAL: case AudioManager.RINGER_MODE_VIBRATE: default: defaultVibrate = true; } } } Boolean vibrate = pref.getBoolean(res.getString(R.string.pref_key_notifications_alarms_vibrate), defaultVibrate); // Ringtone settings String ringtone = pref.getString(res.getString(R.string.pref_key_notifications_alarms_ringtone), Settings.System.DEFAULT_NOTIFICATION_URI.toString()); // Apply notification settings if (!vibrate) { notificationBuilder.setVibrate(new long[] { 0l }); } else { flags |= Notification.DEFAULT_VIBRATE; } notificationBuilder.setSound(Uri.parse(ringtone)); // Get the stage GPS coordinates try { Stage stage = Stage.getByName(set.getStage()); // Add the expandable notification buttons PendingIntent directionsButtonPendingIntent = PendingIntent .getActivity(context, 1, new Intent(Intent.ACTION_VIEW, Uri.parse(String.format(Locale.ENGLISH, "http://maps.google.com/maps?f=d&daddr=%f,%f", stage.getLatitude(), stage.getLongitude()))), Intent.FLAG_ACTIVITY_NEW_TASK); notificationBuilder.addAction(R.drawable.ic_menu_directions, context.getString(R.string.action_directions), directionsButtonPendingIntent); } catch (InconsistentDatabaseException e) { // Although this is a serious error, its impact on functionality is minimal. // Report this through piwik if (BuildConfig.DEBUG) e.printStackTrace(); } // Finalize the notification notificationBuilder.setDefaults(flags); Notification notification = notificationBuilder.build(); NotificationManager notificationManager = (NotificationManager) context .getSystemService(Context.NOTIFICATION_SERVICE); notificationManager.notify(set.getStage(), 0, notification); SavedAlarm.delete(alarmId); } catch (SetNotFoundException e) { throw new RuntimeException(e.getMessage()); // TODO: Notify that an alarm was planned but some error prevented to display it properly. Open AlarmManagerActivity on click // Report this through piwik } }
From source file:im.neon.activity.VectorRoomActivity.java
/** * Display an e2e alert for the first opened room. *//*w ww. j a va 2 s .c om*/ private void displayE2eRoomAlert() { SharedPreferences preferences = PreferenceManager.getDefaultSharedPreferences(this); if (!preferences.contains(E2E_WARNINGS_PREFERENCES) && (null != mRoom) && mRoom.isEncrypted()) { SharedPreferences.Editor editor = preferences.edit(); editor.putBoolean(E2E_WARNINGS_PREFERENCES, false); editor.commit(); android.support.v7.app.AlertDialog.Builder builder = new android.support.v7.app.AlertDialog.Builder( this); builder.setTitle(R.string.room_e2e_alert_title); builder.setMessage(R.string.room_e2e_alert_message); builder.setPositiveButton(R.string.ok, new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { // NOP } }); builder.create().show(); } }