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:me.spadival.podmode.PodModeService.java

@Override
public void onCreate() {

    IntentFilter usbFilter = new IntentFilter();
    usbFilter.addAction(UsbManager.ACTION_USB_DEVICE_DETACHED);
    usbFilter.addAction(UsbManager.ACTION_USB_ACCESSORY_DETACHED);
    registerReceiver(mUsbReceiver, usbFilter);
    // mProvider = RemoteMetadataProvider.getInstance(this);

    // mProvider.setOnMetadataChangeListener(mMetadataListner);
    // mProvider.acquireRemoteControls();
    LocalBroadcastManager bManager = LocalBroadcastManager.getInstance(this);
    IntentFilter notifyFilter = new IntentFilter();
    notifyFilter.addAction(NOTIFYACTION);
    bManager.registerReceiver(mNotifyReceiver, notifyFilter);

    mSerialHost = new FTDriver((UsbManager) getSystemService(Context.USB_SERVICE));

    mSerialDevice = new FT311UARTInterface(this, null);

    // Get the local Bluetooth adapter
    mBluetoothAdapter = BluetoothAdapter.getDefaultAdapter();

    // Get a set of currently paired devices
    Set<BluetoothDevice> pairedDevices = mBluetoothAdapter.getBondedDevices();

    mBluetoothDevice = null;/*from   w  w  w  .jav a 2s . c om*/

    /*   // If there are paired devices, add each one to the ArrayAdapter
       if (pairedDevices.size() > 0) {
          for (BluetoothDevice device : pairedDevices) {
    if (device.getName().equals("PodModeBT"))
       mBluetoothDevice = device;
          }
       }
            
       if (mBluetoothDevice != null) {
          mBTDevice = new BluetoothSerialService(this, mHandler);
          mBTDevice.connect(mBluetoothDevice);
       } */

    // Create the Wifi lock (this does not acquire the lock, this just
    // creates it)
    mWifiLock = ((WifiManager) getSystemService(Context.WIFI_SERVICE))
            .createWifiLock(WifiManager.WIFI_MODE_FULL, "mylock");

    mNotificationManager = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
    mAudioManager = (AudioManager) getSystemService(AUDIO_SERVICE);

    // Create the retriever and start an asynchronous task that will prepare
    // it.

    SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(this);

    mRetriever = new MusicRetriever(getContentResolver(), getApplicationContext(), true, prefs);

    // mRetriever.switchToMainPlaylist();

    prefs.registerOnSharedPreferenceChangeListener((OnSharedPreferenceChangeListener) this);

    mNowPlaying = prefs.getInt("nowplaying", 0);

    String mBaudrate = prefs.getString("baud_rate", "57600");

    if (mBaudrate.equals("57600"))
        mSerialBaudRate = FTDriver.BAUD57600;
    else if (mBaudrate.equals("38400"))
        mSerialBaudRate = FTDriver.BAUD38400;
    else if (mBaudrate.equals("19200"))
        mSerialBaudRate = FTDriver.BAUD19200;

    (new PrepareMusicRetrieverTask(mRetriever, this)).execute();

    // create the Audio Focus Helper, if the Audio Focus feature is
    // available (SDK 8 or above)
    if (android.os.Build.VERSION.SDK_INT >= 8)
        mAudioFocusHelper = new AudioFocusHelper(getApplicationContext(), this);
    else
        mAudioFocus = AudioFocus.Focused; // no focus feature, so we always
    // "have" audio focus

    boolean wakeLockPreferred = prefs.getBoolean("wakelock", false);

    if (podWakeLock == null && wakeLockPreferred) {
        PowerManager powerMgr = (PowerManager) getSystemService(Context.POWER_SERVICE);
        podWakeLock = powerMgr.newWakeLock(PowerManager.SCREEN_DIM_WAKE_LOCK, WAKETAG);
        podWakeLock.acquire();
    }

    PackageManager pxm = getPackageManager();
    Intent mediaIntent = new Intent(Intent.ACTION_MEDIA_BUTTON);

    List<ResolveInfo> mAppsInfo = pxm.queryBroadcastReceivers(mediaIntent, 0);

    mSimpleRemoteApp = prefs.getString("selectapp", null);
    mAdvancedRemoteApp = prefs.getString("selectadvancedapp", PACKAGENAME);

    // Make sure App preferences are still valid and Apps haven't been
    // uninstalled.

    if (mAppsInfo.size() > 0) {

        CharSequence[] entryValues = new CharSequence[mAppsInfo.size()];
        CharSequence[] advEntryValues = new CharSequence[mAppsInfo.size() + 1];

        advEntryValues[0] = PACKAGENAME;

        int i = 0;
        for (ResolveInfo info : mAppsInfo) {
            entryValues[i] = (String) info.activityInfo.packageName;
            advEntryValues[i + 1] = (String) info.activityInfo.packageName;

            i++;
        }

        boolean entryFound = false;

        if (mSimpleRemoteApp != null) {
            for (i = 0; i < entryValues.length; i++) {
                if (mSimpleRemoteApp.equals(entryValues[i])) {
                    entryFound = true;
                }
            }
        }

        if (!entryFound) {
            SharedPreferences.Editor editor = prefs.edit();
            editor.putString("selectapp", (String) entryValues[0]);
            editor.commit();
            mSimpleRemoteApp = (String) entryValues[0];
        }

        entryFound = false;

        if (mAdvancedRemoteApp != null) {
            for (i = 0; i < advEntryValues.length; i++) {
                if (mAdvancedRemoteApp.equals(advEntryValues[i])) {
                    entryFound = true;
                }
            }
        }

        if (!entryFound) {
            SharedPreferences.Editor editor = prefs.edit();
            editor.putString("selectadvancedapp", (String) advEntryValues[0]);
            editor.commit();
            mAdvancedRemoteApp = (String) advEntryValues[0];

        }
    } else {
        SharedPreferences.Editor editor = prefs.edit();
        editor.putString("selectadvancedapp", PACKAGENAME);
        editor.commit();
        mAdvancedRemoteApp = PACKAGENAME;
    }

    mAccessoryName = prefs.getString("accessoryName", null);
    mAccessoryMnf = prefs.getString("accessoryMnf", null);
    mAccessoryModel = prefs.getString("accessoryModel", null);

}

From source file:mp.teardrop.PlaybackService.java

@Override
public void onCreate() {
    HandlerThread thread = new HandlerThread("PlaybackService", Process.THREAD_PRIORITY_DEFAULT);
    thread.start();//  www . j a v a  2s .c om

    mTimeline = new SongTimeline(this);
    mTimeline.setCallback(this);
    int state = loadState();

    mPlayCounts = new PlayCountsHelper(this);

    mMediaPlayer = getNewMediaPlayer();
    mBastpUtil = new BastpUtil();
    mReadahead = new ReadaheadThread();
    mReadahead.start();

    mNotificationManager = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
    mAudioManager = (AudioManager) getSystemService(AUDIO_SERVICE);

    SharedPreferences settings = getSettings(this);
    settings.registerOnSharedPreferenceChangeListener(this);
    mNotificationMode = Integer.parseInt(settings.getString(PrefKeys.NOTIFICATION_MODE, "1"));
    mScrobble = settings.getBoolean(PrefKeys.SCROBBLE, false);
    mIdleTimeout = settings.getBoolean(PrefKeys.USE_IDLE_TIMEOUT, false)
            ? settings.getInt(PrefKeys.IDLE_TIMEOUT, 3600)
            : 0;

    Song.mCoverLoadMode = settings.getBoolean(PrefKeys.COVERLOADER_ANDROID, true)
            ? Song.mCoverLoadMode | Song.COVER_MODE_ANDROID
            : Song.mCoverLoadMode & ~(Song.COVER_MODE_ANDROID);
    Song.mCoverLoadMode = settings.getBoolean(PrefKeys.COVERLOADER_VANILLA, true)
            ? Song.mCoverLoadMode | Song.COVER_MODE_VANILLA
            : Song.mCoverLoadMode & ~(Song.COVER_MODE_VANILLA);
    Song.mCoverLoadMode = settings.getBoolean(PrefKeys.COVERLOADER_SHADOW, true)
            ? Song.mCoverLoadMode | Song.COVER_MODE_SHADOW
            : Song.mCoverLoadMode & ~(Song.COVER_MODE_SHADOW);

    mHeadsetOnly = settings.getBoolean(PrefKeys.HEADSET_ONLY, false);
    mStockBroadcast = settings.getBoolean(PrefKeys.STOCK_BROADCAST, false);
    mInvertNotification = settings.getBoolean(PrefKeys.NOTIFICATION_INVERTED_COLOR, false);
    mNotificationAction = createNotificationAction(settings);
    mHeadsetPause = getSettings(this).getBoolean(PrefKeys.HEADSET_PAUSE, true);
    mShakeAction = settings.getBoolean(PrefKeys.ENABLE_SHAKE, false)
            ? Action.getAction(settings, PrefKeys.SHAKE_ACTION, Action.NextSong)
            : Action.Nothing;
    mShakeThreshold = settings.getInt(PrefKeys.SHAKE_THRESHOLD, 80) / 10.0f;

    mReplayGainTrackEnabled = settings.getBoolean(PrefKeys.ENABLE_TRACK_REPLAYGAIN, false);
    mReplayGainAlbumEnabled = settings.getBoolean(PrefKeys.ENABLE_ALBUM_REPLAYGAIN, false);
    mReplayGainBump = settings.getInt(PrefKeys.REPLAYGAIN_BUMP, 75); /* seek bar is 150 -> 75 == middle == 0 */
    mReplayGainUntaggedDeBump = settings.getInt(PrefKeys.REPLAYGAIN_UNTAGGED_DEBUMP,
            150); /* seek bar is 150 -> == 0 */

    mReadaheadEnabled = settings.getBoolean(PrefKeys.ENABLE_READAHEAD, false);

    PowerManager powerManager = (PowerManager) getSystemService(POWER_SERVICE);
    mWakeLock = powerManager.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, "TeardropMusicLock");

    mReceiver = new Receiver();
    IntentFilter filter = new IntentFilter();
    filter.addAction(AudioManager.ACTION_AUDIO_BECOMING_NOISY);
    filter.addAction(Intent.ACTION_SCREEN_ON);
    registerReceiver(mReceiver, filter);

    getContentResolver().registerContentObserver(MediaStore.Audio.Media.EXTERNAL_CONTENT_URI, true, mObserver);

    CompatIcs.registerRemote(this, mAudioManager);

    mLooper = thread.getLooper();
    mHandler = new Handler(mLooper, this);

    initWidgets();

    updateState(state);
    setCurrentSong(0, false);

    sInstance = this;
    synchronized (sWait) {
        sWait.notifyAll();
    }

    mAccelFiltered = 0.0f;
    mAccelLast = SensorManager.GRAVITY_EARTH;
    setupSensor();
}

From source file:com.almalence.plugins.capture.video.VideoCapturePlugin.java

public void onResume() {
    SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(ApplicationScreen.getMainContext());
    preferenceVideoMuteMode = prefs.getBoolean("preferenceVideoMuteMode", false);

    preferenceFocusMode = prefs.getInt(CameraController.isFrontCamera() ? ApplicationScreen.sRearFocusModePref
            : ApplicationScreen.sFrontFocusModePref, CameraParameters.AF_MODE_AUTO);

    PreferenceManager.getDefaultSharedPreferences(ApplicationScreen.getMainContext()).edit()
            .putBoolean("ContinuousCapturing", true).commit();

    shutterOff = false;/*w  w w.  j  av  a  2  s .c o  m*/
    showRecording = false;

    swChecked = false;
    interval = 0;
    measurementVal = 0;

    if (this.shouldPreviewToGPU()) {
        ApplicationScreen.getMessageHandler().sendEmptyMessage(ApplicationInterface.MSG_OPENGL_LAYER_SHOW_V2);
        ApplicationScreen.getMessageHandler()
                .sendEmptyMessage(ApplicationInterface.MSG_OPENGL_LAYER_RENDERMODE_WHEN_DIRTY);
    }

    showLandscapeNotification = prefs.getBoolean("showLandscapeNotification", true);

    frameCnt = 0;

    if (CameraController.isRemoteCamera()) {
        if (timeLapseButton != null) {
            timeLapseButton.setVisibility(View.GONE);
        }
        if (takePictureButton != null) {
            takePictureButton.setVisibility(View.GONE);
        }
        if (modeSwitcher != null) {
            modeSwitcher.setVisibility(View.GONE);
        }
    }
}

From source file:com.zen.androidhtmleditor.AHEActivity.java

public void deleteFile(View v) {
    View rl = v;//w w  w. jav a  2s  .  co m
    TextView typeId = (TextView) rl.findViewById(R.id.typeId);
    TextView fileFolderName = (TextView) rl.findViewById(R.id.fileFolderName);
    String name = fileFolderName.getText().toString();
    String type = typeId.getText().toString();
    int i = 0;
    int pos = 0;
    String file = "";
    for (String[] s : alrts) {
        if (s[0].equals(name) && s[1].equals(type)) {
            Log.i("List", "Removing " + s[0] + "=" + name + "," + s[1] + "=" + type);
            file = s[0];
            pos = i;

            break;
            //alrts.remove(i);
        }
        i++;

    }
    //Log.i("remove file",folderPath+file);

    SharedPreferences settings = getSharedPreferences(PREFS_NAME, Context.MODE_PRIVATE);
    String currentServers = settings.getString("Accounts", "");
    int connectedTo = settings.getInt("connectedTo", -1);
    if (connectedTo != -1) {
        if (currentServers.equals("")) {
        } else {
            Gson gson = new Gson();
            SearchResponse response = gson.fromJson(currentServers, SearchResponse.class);
            List<Result> results = response.data;
            Result s = results.get(connectedTo);

            if (s.serverName != "" && s.userName != "" && s.port.trim() != "") {

                new DeleteFileFolderTask(s.serverName, s.userName, s.passWord, type, file, s.sftp, s.port, pos)
                        .execute();

            }
        }
    }

    //arrayAdapter.notifyDataSetChanged();

}

From source file:com.zen.androidhtmleditor.AHEActivity.java

@Override
public boolean onOptionsItemSelected(MenuItem item) {
    // Handle item selection

    if (mDrawerToggle.onOptionsItemSelected(item)) {
        return true;
    }//from   ww  w . ja  v  a 2  s . c o m

    switch (item.getItemId()) {
    case R.id.newfile:
        //newGame();

        newFileFolder(0);

        //save(l);
        return true;
    case R.id.newfolder:

        newFileFolder(1);

        //saveAs(l);
        return true;

    case R.id.uploadfile:

        uploadFile();

        return true;

    case R.id.terminal:

        SharedPreferences settings = getSharedPreferences(PREFS_NAME, Context.MODE_PRIVATE);
        String currentServers = settings.getString("Accounts", "");
        int ct = settings.getInt("connectedTo", -1);
        Log.i("connectedTo", String.valueOf(ct));
        if (ct > -1) {

            if (currentServers.equals("")) {
            } else {
                Gson gson = new Gson();
                SearchResponse response = gson.fromJson(currentServers, SearchResponse.class);
                List<Result> results = response.data;
                Result l = results.get(connectedTo);
                if (l.sftp.equals("3")) {
                    Intent TerminalIntent = new Intent(AHEActivity.this, Terminal.class);
                    startActivity(TerminalIntent);
                } else {
                    Toast.makeText(AHEActivity.this, "Not Connected with SFTP", Toast.LENGTH_SHORT).show();
                }
            }
        } else {
            Toast.makeText(AHEActivity.this, "Not Connected To Server", Toast.LENGTH_SHORT).show();

        }
        return true;

    default:
        return super.onOptionsItemSelected(item);
    }
}

From source file:com.zen.androidhtmleditor.AHEActivity.java

public void newFileFolder(int type) {

    final int fileType = type;

    ndialog = new Dialog(AHEActivity.this);
    ndialog.requestWindowFeature(Window.FEATURE_NO_TITLE);
    ndialog.setContentView(R.layout.newfilediag);

    ndialog.setCancelable(true);//from   w  w  w.  ja va2  s  . co m

    Button closeServer = (Button) ndialog.findViewById(R.id.closeServer);
    closeServer.setOnClickListener(new OnClickListener() {
        public void onClick(View v) {

            ndialog.cancel();
        }
    });

    Button saveServer = (Button) ndialog.findViewById(R.id.saveServer);
    saveServer.setOnClickListener(new OnClickListener() {
        public void onClick(View v) {
            SharedPreferences settings = getSharedPreferences(PREFS_NAME, Context.MODE_PRIVATE);
            String currentServers = settings.getString("Accounts", "");
            int connectedTo = settings.getInt("connectedTo", -1);

            if (connectedTo != -1) {
                if (currentServers.equals("")) {
                } else {
                    Gson gson = new Gson();
                    SearchResponse response = gson.fromJson(currentServers, SearchResponse.class);
                    List<Result> results = response.data;
                    Result s = results.get(connectedTo);
                    if (s.serverName != "" && s.userName != "") {
                        new NewFileFolderTask(s.serverName, s.userName, s.passWord, fileType, folderPath,
                                s.sftp, s.port).execute();

                    }
                }
            }

        }
    });
    ndialog.show();
}

From source file:github.madmarty.madsonic.service.RESTMusicService.java

private HttpResponse executeWithRetry(Context context, String url, String originalUrl, HttpParams requestParams,
        List<String> parameterNames, List<Object> parameterValues, List<Header> headers,
        ProgressListener progressListener, CancellableTask task) throws IOException {
    Log.i(TAG, "Using URL " + url);

    SharedPreferences prefs = Util.getPreferences(context);
    int networkTimeout = Integer.parseInt(prefs.getString(Constants.PREFERENCES_KEY_NETWORK_TIMEOUT, "15000"));
    HttpParams newParams = httpClient.getParams();
    HttpConnectionParams.setSoTimeout(newParams, networkTimeout);
    httpClient.setParams(newParams);//  w ww  .  j a va  2s. co m

    final AtomicReference<Boolean> cancelled = new AtomicReference<Boolean>(false);
    int attempts = 0;
    while (true) {
        attempts++;
        HttpContext httpContext = new BasicHttpContext();
        final HttpPost request = new HttpPost(url);

        if (task != null) {
            // Attempt to abort the HTTP request if the task is cancelled.
            task.setOnCancelListener(new CancellableTask.OnCancelListener() {
                @Override
                public void onCancel() {
                    cancelled.set(true);
                    request.abort();
                }
            });
        }

        if (parameterNames != null) {
            List<NameValuePair> params = new ArrayList<NameValuePair>();
            for (int i = 0; i < parameterNames.size(); i++) {
                params.add(
                        new BasicNameValuePair(parameterNames.get(i), String.valueOf(parameterValues.get(i))));
            }
            request.setEntity(new UrlEncodedFormEntity(params, Constants.UTF_8));
        }

        if (requestParams != null) {
            request.setParams(requestParams);
            Log.d(TAG, "Socket read timeout: " + HttpConnectionParams.getSoTimeout(requestParams) + " ms.");
        }

        if (headers != null) {
            for (Header header : headers) {
                request.addHeader(header);
            }
        }

        // Set credentials to get through apache proxies that require authentication.
        int instance = prefs.getInt(Constants.PREFERENCES_KEY_SERVER_INSTANCE, 1);
        String username = prefs.getString(Constants.PREFERENCES_KEY_USERNAME + instance, null);
        String password = prefs.getString(Constants.PREFERENCES_KEY_PASSWORD + instance, null);
        httpClient.getCredentialsProvider().setCredentials(
                new AuthScope(AuthScope.ANY_HOST, AuthScope.ANY_PORT),
                new UsernamePasswordCredentials(username, password));

        try {
            HttpResponse response = httpClient.execute(request, httpContext);
            detectRedirect(originalUrl, context, httpContext);
            return response;
        } catch (IOException x) {
            request.abort();
            if (attempts >= HTTP_REQUEST_MAX_ATTEMPTS || cancelled.get()) {
                throw x;
            }
            if (progressListener != null) {
                String msg = context.getResources().getString(R.string.music_service_retry, attempts,
                        HTTP_REQUEST_MAX_ATTEMPTS - 1);
                progressListener.updateProgress(msg);
            }
            Log.w(TAG, "Got IOException (" + attempts + "), will retry", x);
            increaseTimeouts(requestParams);
            Util.sleepQuietly(2000L);
        }
    }
}

From source file:com.zen.androidhtmleditor.AHEActivity.java

public void uploadFile() {

    ndialog = new Dialog(AHEActivity.this);
    ndialog.requestWindowFeature(Window.FEATURE_NO_TITLE);
    ndialog.setContentView(R.layout.uploadfilediag);
    ndialog.setCancelable(true);/*from  www.ja v a 2s .  c  o  m*/

    Button lb = (Button) ndialog.findViewById(R.id.localBackButton);

    lstLocal = (ListView) ndialog.findViewById(R.id.list);
    // lstTest.setDividerHeight(10);
    lstLocal.setPadding(0, 5, 0, 5);

    File sdCardRoot = Environment.getExternalStorageDirectory();
    File yourDir = new File(sdCardRoot, localPath);
    localalrts = new ArrayList<String[]>();

    for (File f : yourDir.listFiles()) {
        if (f.isDirectory()) {
            String values[] = { f.getName(), "folder" };
            localalrts.add(values);
            //Log.i("localDirectory",f.getName());
        }

    }

    for (File f : yourDir.listFiles()) {
        if (f.isFile()) {
            //Log.i("localFile",f.getName());
            String values[] = { f.getName(), "file" };
            localalrts.add(values);
        }

    }

    //localPath = localPath+"/"+fn+"/";
    lb.setOnClickListener(new View.OnClickListener() {
        public void onClick(View v) {
            String[] localPathBits = localPath.split("/");
            localPath = "";
            for (int i = 0; i < localPathBits.length - 1; i++) {
                localPath += localPathBits[i] + "/";
            }
            TextView lp = (TextView) ndialog.findViewById(R.id.localPath);
            lp.setText(localPath);
            uploadFileList();
        }
    });

    arrayLocalAdapter = new FetchAdapter(AHEActivity.this, R.layout.listitems, localalrts);
    lstLocal.setAdapter(arrayLocalAdapter);

    lstLocal.setOnItemClickListener(new AdapterView.OnItemClickListener() {
        public void onItemClick(AdapterView<?> av, View v, int pos, long id) {
            TextView type = (TextView) v.findViewById(R.id.typeId);
            String t = type.getText().toString();

            TextView fileFolder = (TextView) v.findViewById(R.id.fileFolderName);
            String fn = fileFolder.getText().toString();

            if (t.equals("folder")) {

                localPath = localPath + fn + "/";
                TextView lp = (TextView) ndialog.findViewById(R.id.localPath);
                lp.setText(localPath);
                Button lb = (Button) ndialog.findViewById(R.id.localBackButton);

                if (localPath.equals("/")) {
                    lb.setVisibility(View.GONE);
                } else {
                    lb.setVisibility(View.VISIBLE);

                }
                uploadFileList();
            }
            if (t.equals("file")) {

                SharedPreferences settings = getSharedPreferences(PREFS_NAME, Context.MODE_PRIVATE);
                String currentServers = settings.getString("Accounts", "");
                int connectedTo = settings.getInt("connectedTo", -1);

                if (connectedTo != -1) {
                    if (currentServers.equals("")) {
                    } else {
                        Gson gson = new Gson();
                        SearchResponse response = gson.fromJson(currentServers, SearchResponse.class);
                        List<Result> results = response.data;
                        Result s = results.get(connectedTo);
                        if (s.serverName != "" && s.userName != "") {
                            String local = localPath + fn;
                            String remote = folderPath + fn;
                            new LocalUploadTask(s.serverName, s.userName, s.passWord, local, remote, s.sftp,
                                    s.port, 0).execute();
                            ndialog.dismiss();

                        }
                    }
                }

            }
            //loadFileFolder(v);

        }
    });

    ndialog.show();

}

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

void showServerPrompt(final boolean userInitiated) {
    final SharedPreferences prefs = getPreferences(Context.MODE_PRIVATE);

    final SpannableString message = new SpannableString(getResources().getText(R.string.server_prompt));
    Linkify.addLinks(message, Linkify.ALL);

    final AlertDialog dialog = new AlertDialog.Builder(PTimerEditActivity.this).setTitle(R.string.server_title)
            .setMessage(message).setPositiveButton(R.string.server_yes, new DialogInterface.OnClickListener() {
                public void onClick(DialogInterface dialog, int whichButton) {
                    SharedPreferences.Editor prefsEditor = prefs.edit();
                    prefsEditor.putInt(PREF_STATS_SERVER_ALLOWED, SERVER_ALLOWED_YES);
                    prefsEditor.commit();
                    if (userInitiated) {
                        finish();//from   w  ww.ja v a  2 s  . c  om
                    } else {
                        sendStatsToServerAndFinish();
                    }
                }
            }).setNeutralButton(R.string.server_later, new DialogInterface.OnClickListener() {
                public void onClick(DialogInterface dialog, int whichButton) {
                    int allowServerCheckIndex = prefs.getInt(PREF_STATS_SERVER_CHECK, 2);
                    int successCount = prefs.getInt(PREF_SUCCESS_COUNT, 0);
                    SharedPreferences.Editor prefsEditor = prefs.edit();
                    if (userInitiated) {
                        prefsEditor.putInt(PREF_STATS_SERVER_CHECK, successCount + 2);

                    } else {
                        prefsEditor.putInt(PREF_STATS_SERVER_CHECK, allowServerCheckIndex * 2);
                    }
                    prefsEditor.commit();
                    finish();
                }
            }).setNegativeButton(R.string.server_never, new DialogInterface.OnClickListener() {
                public void onClick(DialogInterface dialog, int whichButton) {
                    SharedPreferences.Editor prefsEditor = prefs.edit();
                    prefsEditor.putInt(PREF_STATS_SERVER_ALLOWED, SERVER_ALLOWED_NO);
                    if (userInitiated) {
                        // If the user initiated, err on the safe side and disable
                        // sending crash reports too. There's no way to turn them
                        // back on now aside from clearing data from this app, but
                        // it doesn't matter, we don't need error reports from every
                        // user ever.
                        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

void showServerPrompt(final boolean userInitiated) {
    final SharedPreferences prefs = getPreferences(Context.MODE_PRIVATE);

    final SpannableString message = new SpannableString(getResources().getText(R.string.server_prompt));
    Linkify.addLinks(message, Linkify.ALL);

    final AlertDialog dialog = new AlertDialog.Builder(SpeechEdEditActivity.this)
            .setTitle(R.string.server_title).setMessage(message)
            .setPositiveButton(R.string.server_yes, new DialogInterface.OnClickListener() {
                public void onClick(DialogInterface dialog, int whichButton) {
                    SharedPreferences.Editor prefsEditor = prefs.edit();
                    prefsEditor.putInt(PREF_STATS_SERVER_ALLOWED, SERVER_ALLOWED_YES);
                    prefsEditor.commit();
                    if (userInitiated) {
                        finish();//  w ww . j  ava  2 s.  com
                    } else {
                        sendStatsToServerAndFinish();
                    }
                }
            }).setNeutralButton(R.string.server_later, new DialogInterface.OnClickListener() {
                public void onClick(DialogInterface dialog, int whichButton) {
                    int allowServerCheckIndex = prefs.getInt(PREF_STATS_SERVER_CHECK, 2);
                    int successCount = prefs.getInt(PREF_SUCCESS_COUNT, 0);
                    SharedPreferences.Editor prefsEditor = prefs.edit();
                    if (userInitiated) {
                        prefsEditor.putInt(PREF_STATS_SERVER_CHECK, successCount + 2);

                    } else {
                        prefsEditor.putInt(PREF_STATS_SERVER_CHECK, allowServerCheckIndex * 2);
                    }
                    prefsEditor.commit();
                    finish();
                }
            }).setNegativeButton(R.string.server_never, new DialogInterface.OnClickListener() {
                public void onClick(DialogInterface dialog, int whichButton) {
                    SharedPreferences.Editor prefsEditor = prefs.edit();
                    prefsEditor.putInt(PREF_STATS_SERVER_ALLOWED, SERVER_ALLOWED_NO);
                    if (userInitiated) {
                        // If the user initiated, err on the safe side and disable
                        // sending crash reports too. There's no way to turn them
                        // back on now aside from clearing data from this app, but
                        // it doesn't matter, we don't need error reports from every
                        // user ever.
                        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());
}