Example usage for android.content SharedPreferences getInt

List of usage examples for android.content SharedPreferences getInt

Introduction

In this page you can find the example usage for android.content SharedPreferences getInt.

Prototype

int getInt(String key, int defValue);

Source Link

Document

Retrieve an int value from the preferences.

Usage

From source file:com.amaze.carbonfilemanager.utils.files.Futils.java

public void openFile(final File f, final MainActivity m) {
    boolean defaultHandler = isSelfDefault(f, m);
    SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(m);
    if (defaultHandler && f.getName().toLowerCase().endsWith(".zip")
            || f.getName().toLowerCase().endsWith(".jar") || f.getName().toLowerCase().endsWith(".rar")
            || f.getName().toLowerCase().endsWith(".tar") || f.getName().toLowerCase().endsWith(".tar.gz")) {
        GeneralDialogCreation.showArchiveDialog(f, m);
    } else if (f.getName().toLowerCase().endsWith(".apk")) {
        GeneralDialogCreation.showPackageDialog(f, m);
    } else if (defaultHandler && f.getName().toLowerCase().endsWith(".db")) {
        Intent intent = new Intent(m, DbViewer.class);
        intent.putExtra("path", f.getPath());
        m.startActivity(intent);/*from   w  ww  .  jav a 2s. co m*/
    } else if (Icons.isAudio(f.getPath())) {
        final int studio_count = sharedPreferences.getInt("studio", 0);
        Uri uri = Uri.fromFile(f);
        final Intent intent = new Intent();
        intent.setAction(Intent.ACTION_VIEW);
        intent.setDataAndType(uri, "audio/*");

        // Behold! It's the  legendary easter egg!
        if (studio_count != 0) {
            new CountDownTimer(studio_count, 1000) {
                @Override
                public void onTick(long millisUntilFinished) {
                    int sec = (int) millisUntilFinished / 1000;
                    if (studioCount != null)
                        studioCount.cancel();
                    studioCount = Toast.makeText(m, sec + "", Toast.LENGTH_LONG);
                    studioCount.show();
                }

                @Override
                public void onFinish() {
                    if (studioCount != null)
                        studioCount.cancel();
                    studioCount = Toast.makeText(m, m.getString(R.string.opening), Toast.LENGTH_LONG);
                    studioCount.show();
                    m.startActivity(intent);
                }
            }.start();
        } else
            m.startActivity(intent);
    } else {
        try {
            openunknown(f, m, false);
        } catch (Exception e) {
            Toast.makeText(m, m.getResources().getString(R.string.noappfound), Toast.LENGTH_LONG).show();
            openWith(f, m);
        }
    }
}

From source file:com.achep.acdisplay.Config.java

/**
 * Loads saved values from shared preferences.
 * This is called on {@link App app's} create.
 *///  www  .  j  a v a 2  s. c  o m
void init(@NonNull Context context) {
    mListeners = new ArrayList<>(6);

    Resources res = context.getResources();
    SharedPreferences prefs = getSharedPreferences(context);
    mAcDisplayEnabled = prefs.getBoolean(KEY_ENABLED, res.getBoolean(R.bool.config_default_enabled));
    mKeyguardEnabled = prefs.getBoolean(KEY_KEYGUARD, res.getBoolean(R.bool.config_default_keyguard_enabled));
    mActiveMode = prefs.getBoolean(KEY_ACTIVE_MODE, res.getBoolean(R.bool.config_default_active_mode_enabled));
    mActiveModeWithoutNotifies = prefs.getBoolean(KEY_ACTIVE_MODE_WITHOUT_NOTIFICATIONS,
            res.getBoolean(R.bool.config_default_active_mode_without_notifies_enabled));

    // notifications
    mNotifyLowPriority = prefs.getBoolean(KEY_NOTIFY_LOW_PRIORITY,
            res.getBoolean(R.bool.config_default_notify_low_priority));
    mNotifyWakeUpOn = prefs.getBoolean(KEY_NOTIFY_WAKE_UP_ON,
            res.getBoolean(R.bool.config_default_notify_wake_up_on));

    // timeout
    mTimeoutNormal = prefs.getInt(KEY_TIMEOUT_NORMAL, res.getInteger(R.integer.config_default_timeout_normal));
    mTimeoutShort = prefs.getInt(KEY_TIMEOUT_SHORT, res.getInteger(R.integer.config_default_timeout_short));

    // inactive time
    mInactiveTimeFrom = prefs.getInt(KEY_INACTIVE_TIME_FROM,
            res.getInteger(R.integer.config_default_inactive_time_from));
    mInactiveTimeTo = prefs.getInt(KEY_INACTIVE_TIME_TO,
            res.getInteger(R.integer.config_default_inactive_time_to));
    mInactiveTimeEnabled = prefs.getBoolean(KEY_INACTIVE_TIME_ENABLED,
            res.getBoolean(R.bool.config_default_inactive_time_enabled));

    // interface
    mUiWallpaper = prefs.getBoolean(KEY_UI_WALLPAPER_SHOWN,
            res.getBoolean(R.bool.config_default_ui_show_wallpaper));
    mUiWallpaperShadow = prefs.getBoolean(KEY_UI_SHADOW_TOGGLE,
            res.getBoolean(R.bool.config_default_ui_show_shadow));
    mUiDynamicBackground = prefs.getInt(KEY_UI_DYNAMIC_BACKGROUND_MODE,
            res.getInteger(R.integer.config_default_ui_show_shadow_dynamic_bg));
    mUiMirroredTimeoutBar = prefs.getBoolean(KEY_UI_MIRRORED_TIMEOUT_BAR,
            res.getBoolean(R.bool.config_default_ui_mirrored_timeout_bar));
    mUiNotifyCircledIcon = prefs.getBoolean(KEY_UI_NOTIFY_CIRCLED_ICON,
            res.getBoolean(R.bool.config_default_ui_notify_circled_icon));
    mUiBatterySticky = prefs.getBoolean(KEY_UI_STATUS_BATTERY_STICKY,
            res.getBoolean(R.bool.config_default_ui_status_battery_sticky));
    mUiFullScreen = prefs.getBoolean(KEY_UI_FULLSCREEN, res.getBoolean(R.bool.config_default_ui_full_screen));
    mUiUnlockAnimation = prefs.getBoolean(KEY_UI_UNLOCK_ANIMATION,
            res.getBoolean(R.bool.config_default_ui_unlock_animation));
    mUiIconSize = prefs.getInt(KEY_UI_ICON_SIZE, res.getInteger(R.integer.config_default_ui_icon_size_dp));

    // development
    mDevSensorsDump = prefs.getBoolean(KEY_DEV_SENSORS_DUMP,
            res.getBoolean(R.bool.config_default_dev_sensors_dump));

    // other
    mEnabledOnlyWhileCharging = prefs.getBoolean(KEY_ONLY_WHILE_CHARGING,
            res.getBoolean(R.bool.config_default_enabled_only_while_charging));
    mScreenOffAfterLastNotify = prefs.getBoolean(KEY_FEEL_SCREEN_OFF_AFTER_LAST_NOTIFY,
            res.getBoolean(R.bool.config_default_feel_screen_off_after_last_notify));
    mFeelWidgetPinnable = prefs.getBoolean(KEY_FEEL_WIDGET_PINNABLE,
            res.getBoolean(R.bool.config_default_feel_widget_pinnable));
    mFeelWidgetReadable = prefs.getBoolean(KEY_FEEL_WIDGET_READABLE,
            res.getBoolean(R.bool.config_default_feel_widget_readable));

    // triggers
    mTrigHelpRead = prefs.getBoolean(KEY_TRIG_HELP_READ, false);
    mTrigTranslated = prefs.getBoolean(KEY_TRIG_TRANSLATED, false);
    mTrigPreviousVersion = prefs.getInt(KEY_TRIG_PREVIOUS_VERSION, 0);
}

From source file:mobi.omegacentauri.ptimer.PTimerEditActivity.java

private void handleFatalError(final CharSequence errorInternalName, final CharSequence errorString,
        final Exception exception) {
    Log.i("Ringdroid", "handleFatalError");

    SharedPreferences prefs = getPreferences(Context.MODE_PRIVATE);
    int failureCount = prefs.getInt(PREF_ERROR_COUNT, 0);
    final SharedPreferences.Editor prefsEditor = prefs.edit();
    prefsEditor.putInt(PREF_ERROR_COUNT, failureCount + 1);
    prefsEditor.commit();/*  w ww  .  java2 s. co m*/

    // Check if we already have a pref for whether or not we can
    // contact the server.
    int serverAllowed = prefs.getInt(PREF_ERR_SERVER_ALLOWED, SERVER_ALLOWED_UNKNOWN);

    if (serverAllowed == SERVER_ALLOWED_NO) {
        Log.i("Ringdroid", "ERR: SERVER_ALLOWED_NO");

        // Just show a simple "write error" message
        showFinalAlert(exception, errorString);
        return;
    }

    if (serverAllowed == SERVER_ALLOWED_YES) {
        Log.i("Ringdroid", "SERVER_ALLOWED_YES");

        new AlertDialog.Builder(PTimerEditActivity.this).setTitle(R.string.alert_title_failure)
                .setMessage(errorString)
                .setPositiveButton(R.string.alert_ok_button, new DialogInterface.OnClickListener() {
                    public void onClick(DialogInterface dialog, int whichButton) {
                        sendErrToServerAndFinish(errorInternalName, exception);
                        return;
                    }
                }).setCancelable(false).show();
        return;
    }

    // The number of times the user must have had a failure before
    // we'll ask them.  Defaults to 1, and each time they click "Later"
    // we double and add 1.
    final int allowServerCheckIndex = prefs.getInt(PREF_ERR_SERVER_CHECK, 1);
    if (failureCount < allowServerCheckIndex) {
        Log.i("Ringdroid", "failureCount " + failureCount + " is less than " + allowServerCheckIndex);
        // Just show a simple "write error" message
        showFinalAlert(exception, errorString);
        return;
    }

    final SpannableString message = new SpannableString(
            errorString + ". " + getResources().getText(R.string.error_server_prompt));
    Linkify.addLinks(message, Linkify.ALL);

    AlertDialog dialog = new AlertDialog.Builder(this).setTitle(R.string.alert_title_failure)
            .setMessage(message).setPositiveButton(R.string.server_yes, new DialogInterface.OnClickListener() {
                public void onClick(DialogInterface dialog, int whichButton) {
                    prefsEditor.putInt(PREF_ERR_SERVER_ALLOWED, SERVER_ALLOWED_YES);
                    prefsEditor.commit();
                    sendErrToServerAndFinish(errorInternalName, exception);
                }
            }).setNeutralButton(R.string.server_later, new DialogInterface.OnClickListener() {
                public void onClick(DialogInterface dialog, int whichButton) {
                    prefsEditor.putInt(PREF_ERR_SERVER_CHECK, 1 + allowServerCheckIndex * 2);
                    Log.i("Ringdroid",
                            "Won't check again until " + (1 + allowServerCheckIndex * 2) + " errors.");
                    prefsEditor.commit();
                    finish();
                }
            }).setNegativeButton(R.string.server_never, new DialogInterface.OnClickListener() {
                public void onClick(DialogInterface dialog, int whichButton) {
                    prefsEditor.putInt(PREF_ERR_SERVER_ALLOWED, SERVER_ALLOWED_NO);
                    prefsEditor.commit();
                    finish();
                }
            }).setCancelable(false).show();

    // Make links clicky
    ((TextView) dialog.findViewById(android.R.id.message)).setMovementMethod(LinkMovementMethod.getInstance());
}

From source file:com.SpeechEd.SpeechEdEditActivity.java

private void handleFatalError(final CharSequence errorInternalName, final CharSequence errorString,
        final Exception exception) {
    Log.i("Speech-Ed", "handleFatalError");

    SharedPreferences prefs = getPreferences(Context.MODE_PRIVATE);
    int failureCount = prefs.getInt(PREF_ERROR_COUNT, 0);
    final SharedPreferences.Editor prefsEditor = prefs.edit();
    prefsEditor.putInt(PREF_ERROR_COUNT, failureCount + 1);
    prefsEditor.commit();//from   w w  w .jav  a  2  s . c o  m

    // Check if we already have a pref for whether or not we can
    // contact the server.
    int serverAllowed = prefs.getInt(PREF_ERR_SERVER_ALLOWED, SERVER_ALLOWED_UNKNOWN);

    if (serverAllowed == SERVER_ALLOWED_NO) {
        Log.i("Speech-Ed", "ERR: SERVER_ALLOWED_NO");

        // Just show a simple "write error" message
        showFinalAlert(exception, errorString);
        return;
    }

    if (serverAllowed == SERVER_ALLOWED_YES) {
        Log.i("Speech-Ed", "SERVER_ALLOWED_YES");

        new AlertDialog.Builder(SpeechEdEditActivity.this).setTitle(R.string.alert_title_failure)
                .setMessage(errorString)
                .setPositiveButton(R.string.alert_ok_button, new DialogInterface.OnClickListener() {
                    public void onClick(DialogInterface dialog, int whichButton) {
                        sendErrToServerAndFinish(errorInternalName, exception);
                        return;
                    }
                }).setCancelable(false).show();
        return;
    }

    // The number of times the user must have had a failure before
    // we'll ask them.  Defaults to 1, and each time they click "Later"
    // we double and add 1.
    final int allowServerCheckIndex = prefs.getInt(PREF_ERR_SERVER_CHECK, 1);
    if (failureCount < allowServerCheckIndex) {
        Log.i("Speech-Ed", "failureCount " + failureCount + " is less than " + allowServerCheckIndex);
        // Just show a simple "write error" message
        showFinalAlert(exception, errorString);
        return;
    }

    final SpannableString message = new SpannableString(
            errorString + ". " + getResources().getText(R.string.error_server_prompt));
    Linkify.addLinks(message, Linkify.ALL);

    AlertDialog dialog = new AlertDialog.Builder(this).setTitle(R.string.alert_title_failure)
            .setMessage(message).setPositiveButton(R.string.server_yes, new DialogInterface.OnClickListener() {
                public void onClick(DialogInterface dialog, int whichButton) {
                    prefsEditor.putInt(PREF_ERR_SERVER_ALLOWED, SERVER_ALLOWED_YES);
                    prefsEditor.commit();
                    sendErrToServerAndFinish(errorInternalName, exception);
                }
            }).setNeutralButton(R.string.server_later, new DialogInterface.OnClickListener() {
                public void onClick(DialogInterface dialog, int whichButton) {
                    prefsEditor.putInt(PREF_ERR_SERVER_CHECK, 1 + allowServerCheckIndex * 2);
                    Log.i("Speech-Ed",
                            "Won't check again until " + (1 + allowServerCheckIndex * 2) + " errors.");
                    prefsEditor.commit();
                    finish();
                }
            }).setNegativeButton(R.string.server_never, new DialogInterface.OnClickListener() {
                public void onClick(DialogInterface dialog, int whichButton) {
                    prefsEditor.putInt(PREF_ERR_SERVER_ALLOWED, SERVER_ALLOWED_NO);
                    prefsEditor.commit();
                    finish();
                }
            }).setCancelable(false).show();

    // Make links clicky
    ((TextView) dialog.findViewById(android.R.id.message)).setMovementMethod(LinkMovementMethod.getInstance());
}

From source file:com.appdupe.flamer.LoginUsingFacebook.java

@SuppressLint("NewApi")
private String getRegistrationId(Context context) {
    final SharedPreferences prefs = getGCMPreferences(context);
    String registrationId = prefs.getString(PROPERTY_REG_ID, "");
    if (registrationId.isEmpty()) {
        // logDebug("getRegistrationId   Registration not found.");

        return "";
    }//from   w w w.  ja v  a  2s  .c o m
    // Check if app was updated; if so, it must clear the registration ID
    // since the existing regID is not guaranteed to work with the new
    // app version.
    int registeredVersion = prefs.getInt(PROPERTY_APP_VERSION, Integer.MIN_VALUE);
    int currentVersion = getAppVersion(context);
    if (registeredVersion != currentVersion) {
        // Log.i(TAG, "App version changed.");
        // logDebug("getRegistrationId   App version changed.");
        return "";
    }
    return registrationId;
}

From source file:mobi.omegacentauri.ptimer.PTimerEditActivity.java

private void afterSavingRingtone(CharSequence title, String outPath, File outFile, int duration) {
    long length = outFile.length();
    if (length <= 512) {
        outFile.delete();/*from  w  w w. j a v a2s. c o  m*/
        new AlertDialog.Builder(this).setTitle(R.string.alert_title_failure)
                .setMessage(R.string.too_small_error).setPositiveButton(R.string.alert_ok_button, null)
                .setCancelable(false).show();
        return;
    }

    // Create the database record, pointing to the existing file path

    long fileSize = outFile.length();
    String mimeType = "audio/mpeg";

    String artist = "" + getResources().getText(R.string.artist_name);

    ContentValues values = new ContentValues();
    values.put(MediaStore.MediaColumns.DATA, outPath);
    values.put(MediaStore.MediaColumns.TITLE, title.toString());
    values.put(MediaStore.MediaColumns.SIZE, fileSize);
    values.put(MediaStore.MediaColumns.MIME_TYPE, mimeType);

    values.put(MediaStore.Audio.Media.ARTIST, artist);
    values.put(MediaStore.Audio.Media.DURATION, duration);

    values.put(MediaStore.Audio.Media.IS_RINGTONE, mNewFileKind == FileSaveDialog.FILE_KIND_RINGTONE);
    values.put(MediaStore.Audio.Media.IS_NOTIFICATION, mNewFileKind == FileSaveDialog.FILE_KIND_NOTIFICATION);
    values.put(MediaStore.Audio.Media.IS_ALARM, mNewFileKind == FileSaveDialog.FILE_KIND_ALARM);
    values.put(MediaStore.Audio.Media.IS_MUSIC, mNewFileKind == FileSaveDialog.FILE_KIND_MUSIC);

    // Insert it into the database
    Uri uri = MediaStore.Audio.Media.getContentUriForPath(outPath);
    final Uri newUri = getContentResolver().insert(uri, values);
    setResult(RESULT_OK, new Intent().setData(newUri));

    // Update a preference that counts how many times we've
    // successfully saved a ringtone or other audio
    SharedPreferences prefs = getPreferences(Context.MODE_PRIVATE);
    int successCount = prefs.getInt(PREF_SUCCESS_COUNT, 0);
    SharedPreferences.Editor prefsEditor = prefs.edit();
    prefsEditor.putInt(PREF_SUCCESS_COUNT, successCount + 1);
    prefsEditor.commit();

    // If Ringdroid was launched to get content, just return
    if (mWasGetContentIntent) {
        sendStatsToServerIfAllowedAndFinish();
        return;
    }

    // There's nothing more to do with music or an alarm.  Show a
    // success message and then quit.
    if (mNewFileKind == FileSaveDialog.FILE_KIND_MUSIC || mNewFileKind == FileSaveDialog.FILE_KIND_ALARM) {
        Toast.makeText(this, R.string.save_success_message, Toast.LENGTH_SHORT).show();
        sendStatsToServerIfAllowedAndFinish();
        return;
    }

    // If it's a notification, give the user the option of making
    // this their default notification.  If they say no, we're finished.
    if (mNewFileKind == FileSaveDialog.FILE_KIND_NOTIFICATION) {
        new AlertDialog.Builder(PTimerEditActivity.this).setTitle(R.string.alert_title_success)
                .setMessage(R.string.set_default_notification)
                .setPositiveButton(R.string.alert_yes_button, new DialogInterface.OnClickListener() {
                    public void onClick(DialogInterface dialog, int whichButton) {
                        RingtoneManager.setActualDefaultRingtoneUri(PTimerEditActivity.this,
                                RingtoneManager.TYPE_NOTIFICATION, newUri);
                        sendStatsToServerIfAllowedAndFinish();
                    }
                }).setNegativeButton(R.string.alert_no_button, new DialogInterface.OnClickListener() {
                    public void onClick(DialogInterface dialog, int whichButton) {
                        sendStatsToServerIfAllowedAndFinish();
                    }
                }).setCancelable(false).show();
        return;
    }

    // If we get here, that means the type is a ringtone.  There are
    // three choices: make this your default ringtone, assign it to a
    // contact, or do nothing.

    final Handler handler = new Handler() {
        public void handleMessage(Message response) {
            int actionId = response.arg1;
            switch (actionId) {
            case R.id.button_make_default:
                RingtoneManager.setActualDefaultRingtoneUri(PTimerEditActivity.this,
                        RingtoneManager.TYPE_RINGTONE, newUri);
                Toast.makeText(PTimerEditActivity.this, R.string.default_ringtone_success_message,
                        Toast.LENGTH_SHORT).show();
                sendStatsToServerIfAllowedAndFinish();
                break;
            case R.id.button_choose_contact:
                chooseContactForRingtone(newUri);
                break;
            default:
            case R.id.button_do_nothing:
                sendStatsToServerIfAllowedAndFinish();
                break;
            }
        }
    };
    Message message = Message.obtain(handler);
    AfterSaveActionDialog dlog = new AfterSaveActionDialog(this, message);
    dlog.show();
}

From source file:com.SpeechEd.SpeechEdEditActivity.java

private void afterSavingRingtone(CharSequence title, String outPath, File outFile, int duration) {
    long length = outFile.length();
    if (length <= 512) {
        outFile.delete();//w  ww  .  j  a  v a  2s  . co m
        new AlertDialog.Builder(this).setTitle(R.string.alert_title_failure)
                .setMessage(R.string.too_small_error).setPositiveButton(R.string.alert_ok_button, null)
                .setCancelable(false).show();
        return;
    }

    // Create the database record, pointing to the existing file path

    long fileSize = outFile.length();
    String mimeType = "audio/mpeg";

    String artist = "" + getResources().getText(R.string.artist_name);

    ContentValues values = new ContentValues();
    values.put(MediaStore.MediaColumns.DATA, outPath);
    values.put(MediaStore.MediaColumns.TITLE, title.toString());
    values.put(MediaStore.MediaColumns.SIZE, fileSize);
    values.put(MediaStore.MediaColumns.MIME_TYPE, mimeType);

    values.put(MediaStore.Audio.Media.ARTIST, artist);
    values.put(MediaStore.Audio.Media.DURATION, duration);

    values.put(MediaStore.Audio.Media.IS_RINGTONE, mNewFileKind == FileSaveDialog.FILE_KIND_RINGTONE);
    values.put(MediaStore.Audio.Media.IS_NOTIFICATION, mNewFileKind == FileSaveDialog.FILE_KIND_NOTIFICATION);
    values.put(MediaStore.Audio.Media.IS_ALARM, mNewFileKind == FileSaveDialog.FILE_KIND_ALARM);
    values.put(MediaStore.Audio.Media.IS_MUSIC, mNewFileKind == FileSaveDialog.FILE_KIND_MUSIC);

    // Insert it into the database
    Uri uri = MediaStore.Audio.Media.getContentUriForPath(outPath);
    final Uri newUri = getContentResolver().insert(uri, values);
    setResult(RESULT_OK, new Intent().setData(newUri));

    // Update a preference that counts how many times we've
    // successfully saved a ringtone or other audio
    SharedPreferences prefs = getPreferences(Context.MODE_PRIVATE);
    int successCount = prefs.getInt(PREF_SUCCESS_COUNT, 0);
    SharedPreferences.Editor prefsEditor = prefs.edit();
    prefsEditor.putInt(PREF_SUCCESS_COUNT, successCount + 1);
    prefsEditor.commit();

    // If SpeechEd was launched to get content, just return
    if (mWasGetContentIntent) {
        sendStatsToServerIfAllowedAndFinish();
        return;
    }

    // There's nothing more to do with music or an alarm.  Show a
    // success message and then quit.
    if (mNewFileKind == FileSaveDialog.FILE_KIND_MUSIC || mNewFileKind == FileSaveDialog.FILE_KIND_ALARM) {
        Toast.makeText(this, R.string.save_success_message, Toast.LENGTH_SHORT).show();
        sendStatsToServerIfAllowedAndFinish();
        return;
    }

    // If it's a notification, give the user the option of making
    // this their default notification.  If they say no, we're finished.
    if (mNewFileKind == FileSaveDialog.FILE_KIND_NOTIFICATION) {
        new AlertDialog.Builder(SpeechEdEditActivity.this).setTitle(R.string.alert_title_success)
                .setMessage(R.string.set_default_notification)
                .setPositiveButton(R.string.alert_yes_button, new DialogInterface.OnClickListener() {
                    public void onClick(DialogInterface dialog, int whichButton) {
                        RingtoneManager.setActualDefaultRingtoneUri(SpeechEdEditActivity.this,
                                RingtoneManager.TYPE_NOTIFICATION, newUri);
                        sendStatsToServerIfAllowedAndFinish();
                    }
                }).setNegativeButton(R.string.alert_no_button, new DialogInterface.OnClickListener() {
                    public void onClick(DialogInterface dialog, int whichButton) {
                        sendStatsToServerIfAllowedAndFinish();
                    }
                }).setCancelable(false).show();
        return;
    }

    // If we get here, that means the type is a ringtone.  There are
    // three choices: make this your default ringtone, assign it to a
    // contact, or do nothing.

    final Handler handler = new Handler() {
        public void handleMessage(Message response) {
            int actionId = response.arg1;
            switch (actionId) {
            case R.id.button_make_default:
                RingtoneManager.setActualDefaultRingtoneUri(SpeechEdEditActivity.this,
                        RingtoneManager.TYPE_RINGTONE, newUri);
                Toast.makeText(SpeechEdEditActivity.this, R.string.default_ringtone_success_message,
                        Toast.LENGTH_SHORT).show();
                sendStatsToServerIfAllowedAndFinish();
                break;
            case R.id.button_choose_contact:
                chooseContactForRingtone(newUri);
                break;
            default:
            case R.id.button_do_nothing:
                sendStatsToServerIfAllowedAndFinish();
                break;
            }
        }
    };
    Message message = Message.obtain(handler);
    AfterSaveActionDialog dlog = new AfterSaveActionDialog(this, message);
    dlog.show();
}

From source file:com.SpeechEd.SpeechEdEditActivity.java

private void sendStatsToServerIfAllowedAndFinish() {
    Log.i("Speech-Ed", "sendStatsToServerIfAllowedAndFinish");

    final SharedPreferences prefs = getPreferences(Context.MODE_PRIVATE);

    // Check if we already have a pref for whether or not we can
    // contact the server.
    int serverAllowed = prefs.getInt(PREF_STATS_SERVER_ALLOWED, SERVER_ALLOWED_UNKNOWN);
    if (serverAllowed == SERVER_ALLOWED_NO) {
        Log.i("Speech-Ed", "SERVER_ALLOWED_NO");
        finish();//from   w  w  w .  ja va2  s . c  om
        return;
    }

    if (serverAllowed == SERVER_ALLOWED_YES) {
        Log.i("Speech-Ed", "SERVER_ALLOWED_YES");
        sendStatsToServerAndFinish();
        return;
    }

    // Number of times the user has successfully saved a sound.
    int successCount = prefs.getInt(PREF_SUCCESS_COUNT, 0);

    // The number of times the user must have successfully saved
    // a sound before we'll ask them.  Defaults to 2, and doubles
    // each time they click "Later".
    final int allowServerCheckIndex = prefs.getInt(PREF_STATS_SERVER_CHECK, 2);
    if (successCount < allowServerCheckIndex) {
        Log.i("Speech-Ed", "successCount " + successCount + " is less than " + allowServerCheckIndex);
        finish();
        return;
    }

    showServerPrompt(false);
}

From source file:com.SpeechEd.SpeechEdEditActivity.java

/**
 * If the exception is not null, will send the stack trace.
 *//*from  w w  w  .  j a  v  a2 s . c om*/
void sendToServer(String serverUrl, CharSequence errType, Exception exception) {
    if (mTitle == null)
        return;

    Log.i("Speech-Ed", "sendStatsToServer");

    boolean isSuccess = (exception == null);

    StringBuilder postMessage = new StringBuilder();
    String SpeechEdVersion = "unknown";
    try {
        SpeechEdVersion = getPackageManager().getPackageInfo(getPackageName(), -1).versionName;
    } catch (android.content.pm.PackageManager.NameNotFoundException e) {
    }
    postMessage.append("speech-ed_version=");
    postMessage.append(URLEncoder.encode(SpeechEdVersion));

    postMessage.append("&android_version=");
    postMessage.append(URLEncoder.encode(Build.VERSION.RELEASE));

    postMessage.append("&unique_id=");
    postMessage.append(getUniqueId());

    postMessage.append("&accurate_seek=");
    postMessage.append(mCanSeekAccurately);

    if (isSuccess) {
        postMessage.append("&title=");
        postMessage.append(URLEncoder.encode(mTitle));
        if (mArtist != null) {
            postMessage.append("&artist=");
            postMessage.append(URLEncoder.encode(mArtist));
        }
        if (mAlbum != null) {
            postMessage.append("&album=");
            postMessage.append(URLEncoder.encode(mAlbum));
        }
        if (mGenre != null) {
            postMessage.append("&genre=");
            postMessage.append(URLEncoder.encode(mGenre));
        }
        postMessage.append("&year=");
        postMessage.append(mYear);

        postMessage.append("&filename=");
        postMessage.append(URLEncoder.encode(mFilename));

        // The user's real location is not actually sent, this is just
        // vestigial code from an old experiment.
        double latitude = 0.0;
        double longitude = 0.0;
        postMessage.append("&user_lat=");
        postMessage.append(URLEncoder.encode("" + latitude));
        postMessage.append("&user_lon=");
        postMessage.append(URLEncoder.encode("" + longitude));

        SharedPreferences prefs = getPreferences(Context.MODE_PRIVATE);
        int successCount = prefs.getInt(PREF_SUCCESS_COUNT, 0);
        postMessage.append("&success_count=");
        postMessage.append(URLEncoder.encode("" + successCount));

        postMessage.append("&bitrate=");
        postMessage.append(URLEncoder.encode("" + mSoundFile.getAvgBitrateKbps()));

        postMessage.append("&channels=");
        postMessage.append(URLEncoder.encode("" + mSoundFile.getChannels()));

        String md5;
        try {
            md5 = mSoundFile.computeMd5OfFirst10Frames();
        } catch (Exception e) {
            md5 = "";
        }
        postMessage.append("&md5=");
        postMessage.append(URLEncoder.encode(md5));

    } else {
        // Error case

        postMessage.append("&err_type=");
        postMessage.append(errType);
        postMessage.append("&err_str=");
        postMessage.append(URLEncoder.encode(getStackTrace(exception)));

        postMessage.append("&src_filename=");
        postMessage.append(URLEncoder.encode(mFilename));

        if (mDstFilename != null) {
            postMessage.append("&dst_filename=");
            postMessage.append(URLEncoder.encode(mDstFilename));
        }
    }

    if (mSoundFile != null) {
        double framesToSecs = 0.0;
        double sampleRate = mSoundFile.getSampleRate();
        if (sampleRate > 0.0) {
            framesToSecs = mSoundFile.getSamplesPerFrame() * 1.0 / sampleRate;
        }

        double songLen = framesToSecs * mSoundFile.getNumFrames();
        postMessage.append("&songlen=");
        postMessage.append(URLEncoder.encode("" + songLen));

        postMessage.append("&sound_type=");
        postMessage.append(URLEncoder.encode(mSoundFile.getFiletype()));

        double clipStart = mStartPos * framesToSecs;
        double clipLen = (mEndPos - mStartPos) * framesToSecs;
        postMessage.append("&clip_start=");
        postMessage.append(URLEncoder.encode("" + clipStart));
        postMessage.append("&clip_len=");
        postMessage.append(URLEncoder.encode("" + clipLen));
    }

    String fileKindName = FileSaveDialog.KindToName(mNewFileKind);
    postMessage.append("&clip_kind=");
    postMessage.append(URLEncoder.encode(fileKindName));

    Log.i("Speech-Ed", postMessage.toString());

    try {
        int TIMEOUT_MILLISEC = 10000; // = 10 seconds
        HttpParams httpParams = new BasicHttpParams();
        HttpConnectionParams.setConnectionTimeout(httpParams, TIMEOUT_MILLISEC);
        HttpConnectionParams.setSoTimeout(httpParams, TIMEOUT_MILLISEC);
        HttpClient client = new DefaultHttpClient(httpParams);

        HttpPost request = new HttpPost(serverUrl);
        request.setEntity(new ByteArrayEntity(postMessage.toString().getBytes("UTF8")));

        Log.i("Speech-Ed", "Executing request");
        HttpResponse response = client.execute(request);

        Log.i("Speech-Ed", "Response: " + response.toString());

    } catch (Exception e) {
        e.printStackTrace();
    }
}