Example usage for android.widget Switch setOnCheckedChangeListener

List of usage examples for android.widget Switch setOnCheckedChangeListener

Introduction

In this page you can find the example usage for android.widget Switch setOnCheckedChangeListener.

Prototype

public void setOnCheckedChangeListener(@Nullable OnCheckedChangeListener listener) 

Source Link

Document

Register a callback to be invoked when the checked state of this button changes.

Usage

From source file:com.androguide.honamicontrol.kernel.cpucontrol.CPUActivity.java

private void handleGovernors() {
    String currentGovernor = "";
    if (Helpers.doesFileExist(GOVERNOR))
        currentGovernor = CPUHelper.readOneLineNotRoot(GOVERNOR);

    String currentGovernor2 = "";
    if (Helpers.doesFileExist(GOVERNOR2))
        currentGovernor2 = CPUHelper.readOneLineNotRoot(GOVERNOR2);
    else//from www.  j  av a 2 s  .com
        currentGovernor2 = bootPrefs.getString("CORE1_GOVERNOR", "NaN");

    String currentGovernor3 = "";
    if (Helpers.doesFileExist(GOVERNOR3))
        currentGovernor3 = CPUHelper.readOneLineNotRoot(GOVERNOR3);
    else
        currentGovernor3 = bootPrefs.getString("CORE2_GOVERNOR", "NaN");

    String currentGovernor4 = "";
    if (Helpers.doesFileExist(GOVERNOR4))
        currentGovernor4 = CPUHelper.readOneLineNotRoot(GOVERNOR4);
    else
        currentGovernor4 = bootPrefs.getString("CORE3_GOVERNOR", "NaN");

    /** CPU Governor for all cores */
    String[] availableGovernorsGeneral = CPUHelper.readOneLineNotRoot(GOVERNORS_LIST).split(" ");
    ArrayAdapter<CharSequence> governorAdapterGeneral = new ArrayAdapter<CharSequence>(this,
            R.layout.spinner_row);
    governorAdapterGeneral.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);

    for (String availableGovernor : availableGovernorsGeneral) {
        governorAdapterGeneral.add(availableGovernor);
    }

    mGeneralGovernor.setAdapter(governorAdapterGeneral);
    mGeneralGovernor.setSelection(Arrays.asList(availableGovernorsGeneral).indexOf(currentGovernor));
    mGeneralGovernor.setOnItemSelectedListener(new GeneralGovListener());

    /** CPU Governor for core 0 */
    String[] availableGovernors = CPUHelper.readOneLineNotRoot(GOVERNORS_LIST).split(" ");
    ArrayAdapter<CharSequence> governorAdapter = new ArrayAdapter<CharSequence>(this, R.layout.spinner_row);
    governorAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
    for (String availableGovernor : availableGovernors) {
        governorAdapter.add(availableGovernor);
    }
    mGovernor.setAdapter(governorAdapter);
    mGovernor.setSelection(Arrays.asList(availableGovernors).indexOf(currentGovernor));
    mGovernor.setOnItemSelectedListener(new GovListener());

    /** CPU Governor for core 1 */
    ArrayAdapter<CharSequence> governorAdapter2 = new ArrayAdapter<CharSequence>(this, R.layout.spinner_row);
    governorAdapter2.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
    for (String anAvailableGovernors2 : availableGovernors) {
        governorAdapter2.add(anAvailableGovernors2);
    }
    mGovernor2.setAdapter(governorAdapter2);
    mGovernor2.setSelection(Arrays.asList(availableGovernors).indexOf(currentGovernor2));
    mGovernor2.setOnItemSelectedListener(new GovListener2());

    /** CPU Governor for core 2 */
    ArrayAdapter<CharSequence> governorAdapter3 = new ArrayAdapter<CharSequence>(this, R.layout.spinner_row);
    governorAdapter3.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
    for (String anAvailableGovernors3 : availableGovernors) {
        governorAdapter3.add(anAvailableGovernors3);
    }
    mGovernor3.setAdapter(governorAdapter3);
    mGovernor3.setSelection(Arrays.asList(availableGovernors).indexOf(currentGovernor3));
    mGovernor3.setOnItemSelectedListener(new GovListener3());

    /** CPU Governor for core 3 */
    ArrayAdapter<CharSequence> governorAdapter4 = new ArrayAdapter<CharSequence>(this, R.layout.spinner_row);
    governorAdapter4.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
    for (String anAvailableGovernors4 : availableGovernors) {
        governorAdapter4.add(anAvailableGovernors4);
    }
    mGovernor4.setAdapter(governorAdapter4);
    mGovernor4.setSelection(Arrays.asList(availableGovernors).indexOf(currentGovernor4));
    mGovernor4.setOnItemSelectedListener(new GovListener4());

    /** CPU Boost */
    if (Helpers.doesFileExist(KRAIT_BOOST)) {
        Switch cpuBoostSwitch = (Switch) findViewById(R.id.krait_boost_switch);
        String cpuBoostState = CPUHelper.readOneLineNotRoot(KRAIT_BOOST);
        if (cpuBoostState.equals("Y"))
            cpuBoostSwitch.setChecked(true);
        else
            cpuBoostSwitch.setChecked(false);

        cpuBoostSwitch.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
                if (isChecked)
                    Helpers.CMDProcessorWrapper.runSuCommand("busybox echo Y > " + KRAIT_BOOST);
                else
                    Helpers.CMDProcessorWrapper.runSuCommand("busybox echo N > " + KRAIT_BOOST);
            }
        });

    } else {
        findViewById(R.id.card_krait_boost).setVisibility(View.GONE);
    }

    /** CPU Informations */
    String pvs = "NaN";
    String table = "NaN";
    TextView pvsBinning = (TextView) findViewById(R.id.pvs_bin);
    TextView pvsSpeed = (TextView) findViewById(R.id.pvs_speed);

    if (Helpers.doesFileExist(PVS_BINNING)) {
        String rawTableName = CPUHelper.readOneLineNotRoot(PVS_BINNING);
        rawTableName = rawTableName.replaceAll("[\\D]", "");
        table = rawTableName;
        String[] params = rawTableName.split("");
        if (rawTableName.length() == 3)
            pvs = params[2];
    }

    pvsBinning.setText(getString(R.string.pvs_binning) + " " + pvs);
    pvsSpeed.setText(getString(R.string.freq_table) + " " + table);
}

From source file:apps.junkuvo.alertapptowalksafely.MainActivity.java

public void setSwitchInLayout(View layout) {
    final RadioButton radioButtonTop = (RadioButton) layout.findViewById(R.id.radiobutton_top);
    final RadioButton radioButtonCenter = (RadioButton) layout.findViewById(R.id.radiobutton_center);
    final RadioButton radioButtonBottom = (RadioButton) layout.findViewById(R.id.radiobutton_bottom);
    Switch swh = (Switch) layout.findViewById(R.id.swhToastOnOff);
    swh.setChecked(mIsToastOn);//www.j a va  2s . c o  m
    swh.setOnCheckedChangeListener(new Switch.OnCheckedChangeListener() {
        public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
            mIsToastOn = isChecked;
            if (mAlertService != null && mAlertService.isBoundService()) {
                mAlertService.setIsToastOn(mIsToastOn);
            }
            radioButtonBottom.setEnabled(isChecked);
            radioButtonTop.setEnabled(isChecked);
            radioButtonCenter.setEnabled(isChecked);
        }
    });
    swh = (Switch) layout.findViewById(R.id.swhVibrationOnOff);
    swh.setChecked(mIsVibrationOn);
    swh.setOnCheckedChangeListener(new Switch.OnCheckedChangeListener() {
        public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
            mIsVibrationOn = isChecked;
            if (mAlertService != null && mAlertService.isBoundService()) {
                mAlertService.setIsVibrationOn(mIsVibrationOn);
            }
        }
    });
    swh = (Switch) layout.findViewById(R.id.swhPasscodeOnOff);
    swh.setChecked(mPasscodeOn);
    swh.setOnCheckedChangeListener(new Switch.OnCheckedChangeListener() {
        public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
            mPasscodeOn = isChecked;
        }
    });

    if (mAlertService != null) {
        swh.setEnabled(!mAlertService.IsRunningAlertService());
    } else {
        swh.setEnabled(true);
    }
}

From source file:fm.krui.kruifm.StreamFragment.java

@Override
public void onActivityCreated(Bundle savedInstanceState) {
    super.onActivityCreated(savedInstanceState);

    // Instantiate class members
    prefManager = new PreferenceManager(getActivity());
    favTrackManager = new FavoriteTrackManager(getActivity());

    // FIXME: Move these to PreferenceManager after expanding its scope for cleaner code
    trackPrefs = getActivity().getSharedPreferences(StreamService.PREFS_NAME, 0);

    // Instantiate broadcast receiver
    broadcastReceiver = new BroadcastReceiver() {
        @Override/*from  ww w  .j  av  a 2 s  . c om*/
        public void onReceive(Context context, Intent intent) {
            processBroadcastCommand(intent);
        }
    };

    // Determine the URL we need to use to stream based on the station tag and quality preferences
    streamUrl = getStreamUrl(stationTag);
    Log.v(TAG, "streamUrl is now set to: " + streamUrl);

    // Perform initial configuration of audio server
    changeUrl(stationTag);

    // Begin buffering the audio
    startAudio((ImageView) getActivity().findViewById(R.id.play_audio_imageview));

    // Build play button listener
    final ImageView playButton = (ImageView) getActivity().findViewById(R.id.play_audio_imageview);
    playButton.setOnClickListener(new View.OnClickListener() {

        @Override
        public void onClick(View v) {
            handleAudio(playButton);
        }
    });

    // Build volume seek bar listener
    // ** DISABLED FOR NOW -- This might be completely thrown out. **
    /*final SeekBar volumeSeekBar = (SeekBar)getActivity().findViewById(R.id.volume_seekbar);
    volumeSeekBar.setOnSeekBarChangeListener(new SeekBar.OnSeekBarChangeListener() {
            
    // When seek bar progress is changed, change the audio of the media player appropriately.
    @Override
    public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) {
        // Send new volume via intent? Will this be slow?
    }
            
    @Override
    public void onStartTrackingTouch(SeekBar seekBar) {
    }
            
    @Override
    public void onStopTrackingTouch(SeekBar seekBar) {
    }
    }); */

    // Build settings button listener and apply it to settings icon and submit button
    View.OnClickListener flipListener = new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            // Card flip animation which toggles between stream controls and settings views
            flipCard();
        }
    };

    final ImageView settingsButton = (ImageView) getActivity().findViewById(R.id.stream_settings_imageview);
    final Button saveSettingsButton = (Button) getActivity().findViewById(R.id.set_stream_settings_button);
    settingsButton.setOnClickListener(flipListener);
    saveSettingsButton.setOnClickListener(flipListener);

    // Build favorite button listener
    final ImageView favoriteButton = (ImageView) getActivity().findViewById(R.id.stream_favorite_imageview);
    favoriteButton.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            if (trackIsFavorite) {
                favoriteButton.setImageResource(R.drawable.star_unfilled_white);
                trackIsFavorite = false;
                removeTrackFromFavorites();
            } else {
                favoriteButton.setImageResource(R.drawable.star_filled_white);
                trackIsFavorite = true;
                addTrackToFavorites();
            }
        }
    });

    // Build settings switches
    final Switch streamQualitySwitch = (Switch) getActivity().findViewById(R.id.stream_quality_switch);
    final Switch albumArtSwitch = (Switch) getActivity().findViewById(R.id.stream_album_art_switch);

    // Set initial state of switches
    albumArtSwitch.setChecked(prefManager.getAlbumArtDownloadPreference());
    if (prefManager.getStreamQuality() == prefManager.HIGH_QUALITY) {
        streamQualitySwitch.setChecked(true);
    } else {
        streamQualitySwitch.setChecked(false);
    }

    // Assign listeners to switches
    streamQualitySwitch.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
        @Override
        public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
            if (isChecked) {
                prefManager.setStreamQuality(prefManager.HIGH_QUALITY);
                Log.v(TAG, "Stream quality setting is now: " + prefManager.getStreamQuality());
            } else {
                prefManager.setStreamQuality(prefManager.LOW_QUALITY);
                Log.v(TAG, "Stream quality setting is now: " + prefManager.getStreamQuality());
            }
            changeUrl(stationSpinnerPosition);
        }
    });

    albumArtSwitch.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
        @Override
        public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
            if (isChecked) {
                prefManager.setAlbumArtDownloadPreference(true);
                Log.v(TAG, "Album Art Download setting is now " + prefManager.getAlbumArtDownloadPreference());
            } else {
                prefManager.setAlbumArtDownloadPreference(false);
                Log.v(TAG, "Album Art Download setting is now " + prefManager.getAlbumArtDownloadPreference());
            }
        }
    });

}

From source file:fm.krui.kruifm.StreamActivity.java

@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.stream_layout);

    // Instantiate class members
    prefManager = new PreferenceManager(this);
    favTrackManager = new FavoriteTrackManager(this);

    stationTag = getIntent().getIntExtra(KEY_STATION_TAG, -1);

    // Set ActionBar Title
    ActionBar actionBar = getActionBar();
    actionBar.setTitle(getString(R.string.listen_sidebar));
    actionBar.setSubtitle(getActivitySubtitle(getIntent()));

    // FIXME: Move these to PreferenceManager after expanding its scope for cleaner code
    trackPrefs = this.getSharedPreferences(StreamService.PREFS_NAME, 0);

    // Instantiate broadcast receiver
    broadcastReceiver = new BroadcastReceiver() {
        @Override//from  www .j  a  v a 2s .c om
        public void onReceive(Context context, Intent intent) {
            processBroadcastCommand(intent);
        }
    };

    // Retrieve player state to determine how to build this activity
    boolean playerState = prefManager.getPlayerState();

    // If audio is playing in StreamService, we don't want to rebuffer, and we want to restore the UI state from the cache.
    if (playerState) {
        restoreUIState();
    }

    // If audio is NOT playing, buffer and treat this launch like a clean startup.
    else {
        // Determine the URL we need to use to stream based on the station tag and quality preferences
        streamUrl = getStreamUrl(stationTag);
        Log.v(TAG, "streamUrl is now set to: " + streamUrl);

        // Perform initial configuration of audio server
        changeUrl(stationTag);

        // Begin buffering the audio
        startAudio((ImageView) this.findViewById(R.id.play_audio_imageview));
    }

    // Build play button listener
    final ImageView playButton = (ImageView) this.findViewById(R.id.play_audio_imageview);
    playButton.setOnClickListener(new View.OnClickListener() {

        @Override
        public void onClick(View v) {
            handleAudio(playButton);
        }
    });

    // Build volume seek bar listener
    // ** DISABLED FOR NOW -- This might be completely thrown out. **
    /*final SeekBar volumeSeekBar = (SeekBar)this.findViewById(R.id.volume_seekbar);
    volumeSeekBar.setOnSeekBarChangeListener(new SeekBar.OnSeekBarChangeListener() {
            
    // When seek bar progress is changed, change the audio of the media player appropriately.
    @Override
    public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) {
        // Send new volume via intent? Will this be slow?
    }
            
    @Override
    public void onStartTrackingTouch(SeekBar seekBar) {
    }
            
    @Override
    public void onStopTrackingTouch(SeekBar seekBar) {
    }
    }); */

    // Build settings button listener and apply it to settings icon and submit button
    View.OnClickListener flipListener = new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            // Card flip animation which toggles between stream controls and settings views
            flipCard();
        }
    };

    final ImageView settingsButton = (ImageView) this.findViewById(R.id.stream_settings_imageview);
    final Button saveSettingsButton = (Button) this.findViewById(R.id.set_stream_settings_button);
    settingsButton.setOnClickListener(flipListener);
    saveSettingsButton.setOnClickListener(flipListener);

    // Build favorite button listener
    final ImageView favoriteButton = (ImageView) this.findViewById(R.id.stream_favorite_imageview);
    favoriteButton.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            if (trackIsFavorite) {
                favoriteButton.setImageResource(R.drawable.star_unfilled_white);
                trackIsFavorite = false;
                removeTrackFromFavorites();
            } else {
                favoriteButton.setImageResource(R.drawable.star_filled_white);
                trackIsFavorite = true;
                addTrackToFavorites();
            }
        }
    });

    // Build settings switches
    final Switch streamQualitySwitch = (Switch) this.findViewById(R.id.stream_quality_switch);
    final Switch albumArtSwitch = (Switch) this.findViewById(R.id.stream_album_art_switch);

    // Set initial state of switches
    albumArtSwitch.setChecked(prefManager.getAlbumArtDownloadPreference());
    if (prefManager.getStreamQuality() == prefManager.HIGH_QUALITY) {
        streamQualitySwitch.setChecked(true);
    } else {
        streamQualitySwitch.setChecked(false);
    }

    // Assign listeners to switches
    streamQualitySwitch.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
        @Override
        public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
            if (isChecked) {
                prefManager.setStreamQuality(prefManager.HIGH_QUALITY);
                Log.v(TAG, "Stream quality setting is now: " + prefManager.getStreamQuality());
            } else {
                prefManager.setStreamQuality(prefManager.LOW_QUALITY);
                Log.v(TAG, "Stream quality setting is now: " + prefManager.getStreamQuality());
            }
            changeUrl(stationSpinnerPosition);
        }
    });

    albumArtSwitch.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
        @Override
        public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
            if (isChecked) {
                prefManager.setAlbumArtDownloadPreference(true);
                Log.v(TAG, "Album Art Download setting is now " + prefManager.getAlbumArtDownloadPreference());
            } else {
                prefManager.setAlbumArtDownloadPreference(false);
                Log.v(TAG, "Album Art Download setting is now " + prefManager.getAlbumArtDownloadPreference());
            }
        }
    });

    // ***** Old onCreate function starts here!
    // Initialize screen lock/wake receiver
    IntentFilter filter = new IntentFilter(Intent.ACTION_SCREEN_ON);
    filter.addAction(Intent.ACTION_SCREEN_OFF);
    BroadcastReceiver screenReceiver = new ScreenReceiver();

    // Attach it to this activity
    this.getApplicationContext().registerReceiver(screenReceiver, filter);

}

From source file:com.adamas.client.android.MainActivity.java

@Override
public boolean onCreateOptionsMenu(Menu menu) {
    getMenuInflater().inflate(R.menu.menu_main, menu);

    _menuItemStartStop = menu.findItem(R.id.action_start_stop_vpn);
    final Switch mySwitch = (Switch) _menuItemStartStop.getActionView()
            .findViewById(R.id.switchForStartStopConnector);
    if (_checked != null) {
        mySwitch.setChecked(_checked.booleanValue());
        _checked = null;//from   w w w.java2 s .c o m
    } else {
        mySwitch.setChecked(_connected);
    }
    if (_connecting.get() || _disconnecting.get()) {
        _menuItemStartStop.getActionView().findViewById(R.id.switchForStartStopConnector)
                .setVisibility(View.GONE);
        _menuItemStartStop.getActionView().findViewById(R.id.progressBarConnecting).setVisibility(View.VISIBLE);
    }
    //attach a listener to check for changes in state
    mySwitch.setOnCheckedChangeListener(new Switch.OnCheckedChangeListener() {
        @Override
        public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
            if (_runProcessConnectDisconnectKey) {
                if (isChecked) {
                    processConnectDisconnectKey();
                } else {
                    processConnectDisconnectKey();
                }
            } else {
                _runProcessConnectDisconnectKey = true;
            }
        }
    });

    return true;
}

From source file:it.iziozi.iziozi.gui.IOBoardActivity.java

public void tapOnSpeakableButton(final IOSpeakableImageButton spkBtn, final Integer level) {
    if (IOGlobalConfiguration.isEditing) {

        AlertDialog.Builder builder = new AlertDialog.Builder(this);
        LayoutInflater inflater = getLayoutInflater();

        View layoutView = inflater.inflate(R.layout.editmode_alertview, null);

        builder.setTitle(getString(R.string.choose));

        builder.setView(layoutView);//from  w  ww . jav  a2 s .com

        final AlertDialog dialog = builder.create();

        final Switch matrioskaSwitch = (Switch) layoutView.findViewById(R.id.editModeAlertToggleBoard);
        Button editPictoButton = (Button) layoutView.findViewById(R.id.editModeAlertActionPicture);
        final Button editBoardButton = (Button) layoutView.findViewById(R.id.editModeAlertActionBoard);

        matrioskaSwitch.setChecked(spkBtn.getIsMatrioska());
        editBoardButton.setEnabled(spkBtn.getIsMatrioska());

        matrioskaSwitch.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
                spkBtn.setIsMatrioska(isChecked);
                editBoardButton.setEnabled(isChecked);
            }
        });

        editPictoButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                //spkBtn.showInsertDialog();
                Intent cIntent = new Intent(getApplicationContext(), IOCreateButtonActivity.class);
                cIntent.putExtra(BUTTON_INDEX,
                        mActualLevel.getBoardAtIndex(mActualIndex).getButtons().indexOf(spkBtn));

                cIntent.putExtra(BUTTON_TEXT, spkBtn.getSentence());
                cIntent.putExtra(BUTTON_TITLE, spkBtn.getmTitle());
                cIntent.putExtra(BUTTON_IMAGE_FILE, spkBtn.getmImageFile());
                cIntent.putExtra(BUTTON_AUDIO_FILE, spkBtn.getAudioFile());

                startActivityForResult(cIntent, CREATE_BUTTON_CODE);

                matrioskaSwitch.setOnCheckedChangeListener(null);

                dialog.dismiss();
            }
        });

        editBoardButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {

                IOLevel nestedBoard = spkBtn.getLevel();

                pushLevel(nestedBoard);

                matrioskaSwitch.setOnCheckedChangeListener(null);

                dialog.dismiss();
            }
        });

        dialog.show();

    } else {

        if (IOGlobalConfiguration.isScanMode) {
            IOSpeakableImageButton scannedButton = mActualLevel.getBoardAtIndex(mActualIndex).getButtons()
                    .get(mActualScanIndex);
            if (scannedButton.getAudioFile() != null && scannedButton.getAudioFile().length() > 0) {

                final MediaPlayer mPlayer = new MediaPlayer();
                try {
                    mPlayer.setDataSource(scannedButton.getAudioFile());
                    mPlayer.prepare();

                    mPlayer.setOnCompletionListener(new MediaPlayer.OnCompletionListener() {
                        @Override
                        public void onCompletion(MediaPlayer mp) {
                            mPlayer.release();

                        }
                    });

                    mPlayer.start();

                } catch (IOException e) {
                    Log.e("playback_debug", "prepare() failed");
                }
            } else if (mCanSpeak) {
                Log.d("speakable_debug", "should say: " + scannedButton.getSentence());
                if (scannedButton.getSentence() == "")
                    tts.speak(getResources().getString(R.string.tts_nosentence), TextToSpeech.QUEUE_FLUSH,
                            null);
                else
                    tts.speak(scannedButton.getSentence(), TextToSpeech.QUEUE_FLUSH, null);
            } else {
                Toast.makeText(this, getResources().getString(R.string.tts_notinitialized), Toast.LENGTH_LONG)
                        .show();
            }

            if (scannedButton.getIsMatrioska() && null != scannedButton.getLevel()) {
                pushLevel(scannedButton.getLevel());
            }
        } else {

            if (spkBtn.getAudioFile() != null && spkBtn.getAudioFile().length() > 0) {

                final MediaPlayer mPlayer = new MediaPlayer();
                try {
                    mPlayer.setDataSource(spkBtn.getAudioFile());
                    mPlayer.prepare();

                    mPlayer.setOnCompletionListener(new MediaPlayer.OnCompletionListener() {
                        @Override
                        public void onCompletion(MediaPlayer mp) {
                            mPlayer.release();

                        }
                    });

                    mPlayer.start();

                } catch (IOException e) {
                    Log.e("playback_debug", "prepare() failed");
                }
            } else if (mCanSpeak) {
                Log.d("speakable_debug", "should say: " + spkBtn.getSentence());
                if (spkBtn.getSentence() == "")
                    tts.speak(getResources().getString(R.string.tts_nosentence), TextToSpeech.QUEUE_FLUSH,
                            null);
                else
                    tts.speak(spkBtn.getSentence(), TextToSpeech.QUEUE_FLUSH, null);
            } else {
                Toast.makeText(this, getResources().getString(R.string.tts_notinitialized), Toast.LENGTH_LONG)
                        .show();
            }

            if (spkBtn.getIsMatrioska() && null != spkBtn.getLevel()) {
                pushLevel(spkBtn.getLevel());
            }
        }
    }
}

From source file:fiskinfoo.no.sintef.fiskinfoo.MapFragment.java

private void createProximityAlertSetupDialog() {
    final Dialog dialog = dialogInterface.getDialog(getActivity(), R.layout.dialog_proximity_alert_create,
            R.string.create_proximity_alert);

    Button setProximityAlertWatcherButton = (Button) dialog
            .findViewById(R.id.create_proximity_alert_create_alert_watcher_button);
    Button stopCurrentProximityAlertWatcherButton = (Button) dialog
            .findViewById(R.id.create_proximity_alert_stop_existing_alert_button);
    Button cancelButton = (Button) dialog.findViewById(R.id.create_proximity_alert_cancel_button);
    SeekBar seekbar = (SeekBar) dialog.findViewById(R.id.create_proximity_alert_seekBar);
    final EditText radiusEditText = (EditText) dialog.findViewById(R.id.create_proximity_alert_range_edit_text);
    final Switch formatSwitch = (Switch) dialog.findViewById(R.id.create_proximity_alert_format_switch);

    final double seekBarStepSize = (double) (getResources()
            .getInteger(R.integer.proximity_alert_maximum_warning_range_meters)
            - getResources().getInteger(R.integer.proximity_alert_minimum_warning_range_meters)) / 100;

    radiusEditText.setText(//from w  ww  . java 2 s.c  o  m
            String.valueOf(getResources().getInteger(R.integer.proximity_alert_minimum_warning_range_meters)));

    formatSwitch.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
        @Override
        public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
            if (isChecked) {
                buttonView.setText(getString(R.string.range_format_nautical_miles));
            } else {
                buttonView.setText(getString(R.string.range_format_meters));
            }
        }
    });

    seekbar.setOnSeekBarChangeListener(new SeekBar.OnSeekBarChangeListener() {
        @Override
        public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) {
            if (fromUser) {
                String range = String.valueOf(
                        (int) (getResources().getInteger(R.integer.proximity_alert_minimum_warning_range_meters)
                                + (seekBarStepSize * progress)));
                radiusEditText.setText(range);
            }
        }

        @Override
        public void onStartTrackingTouch(SeekBar seekBar) {

        }

        @Override
        public void onStopTrackingTouch(SeekBar seekBar) {

        }
    });

    setProximityAlertWatcherButton.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            String toastText;

            if (proximityAlertWatcher == null) {
                toastText = getString(R.string.proximity_alert_set);
            } else {

                toastText = getString(R.string.proximity_alert_replace);
            }

            if (proximityAlertWatcher != null) {
                proximityAlertWatcher.cancel(true);
            }

            mGpsLocationTracker = new GpsLocationTracker(getActivity());
            double latitude, longitude;

            if (mGpsLocationTracker.canGetLocation()) {
                latitude = mGpsLocationTracker.getLatitude();
                cachedLat = latitude;
                longitude = mGpsLocationTracker.getLongitude();
                cachedLon = longitude;
            } else {
                mGpsLocationTracker.showSettingsAlert();
                return;
            }

            if (formatSwitch.isChecked()) {
                cachedDistance = Double.valueOf(radiusEditText.getText().toString())
                        * getResources().getInteger(R.integer.meters_per_nautical_mile);
            } else {
                cachedDistance = Double.valueOf(radiusEditText.getText().toString());
            }

            dialog.dismiss();

            Response response;

            try {
                String apiName = "fishingfacility";
                String format = "OLEX";
                String filePath;
                String fileName = "collisionCheckToolsFile";

                response = barentswatchApi.getApi().geoDataDownload(apiName, format);

                if (response == null) {
                    Log.d(TAG, "RESPONSE == NULL");
                    throw new InternalError();
                }

                if (fiskInfoUtility.isExternalStorageWritable()) {
                    String directoryPath = Environment
                            .getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS).toString();
                    String directoryName = "FiskInfo";
                    filePath = directoryPath + "/" + directoryName + "/";
                    InputStream zippedInputStream = null;

                    try {
                        TypedInput responseInput = response.getBody();
                        zippedInputStream = responseInput.in();
                        zippedInputStream = new GZIPInputStream(zippedInputStream);

                        InputSource inputSource = new InputSource(zippedInputStream);
                        InputStream input = new BufferedInputStream(inputSource.getByteStream());
                        byte data[];
                        data = FiskInfoUtility.toByteArray(input);

                        InputStream inputStream = new ByteArrayInputStream(data);
                        BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream));
                        FiskInfoPolygon2D serializablePolygon2D = new FiskInfoPolygon2D();

                        String line;
                        boolean startSet = false;
                        String[] convertedLine;
                        List<Point> shape = new ArrayList<>();
                        while ((line = reader.readLine()) != null) {
                            Point currPoint = new Point();
                            if (line.length() == 0 || line.equals("")) {
                                continue;
                            }
                            if (Character.isLetter(line.charAt(0))) {
                                continue;
                            }

                            convertedLine = line.split("\\s+");

                            if (line.length() > 150) {
                                Log.d(TAG, "line " + line);
                            }

                            if (convertedLine[0].startsWith("3sl")) {
                                continue;
                            }

                            if (convertedLine[3].equalsIgnoreCase("Garnstart") && startSet) {
                                if (shape.size() == 1) {
                                    // Point

                                    serializablePolygon2D.addPoint(shape.get(0));
                                    shape = new ArrayList<>();
                                } else if (shape.size() == 2) {

                                    // line
                                    serializablePolygon2D.addLine(new Line(shape.get(0), shape.get(1)));
                                    shape = new ArrayList<>();
                                } else {

                                    serializablePolygon2D.addPolygon(new Polygon(shape));
                                    shape = new ArrayList<>();
                                }
                                startSet = false;
                            }

                            if (convertedLine[3].equalsIgnoreCase("Garnstart") && !startSet) {
                                double lat = Double.parseDouble(convertedLine[0]) / 60;
                                double lon = Double.parseDouble(convertedLine[1]) / 60;
                                currPoint.setNewPointValues(lat, lon);
                                shape.add(currPoint);
                                startSet = true;
                            } else if (convertedLine[3].equalsIgnoreCase("Brunsirkel")) {
                                double lat = Double.parseDouble(convertedLine[0]) / 60;
                                double lon = Double.parseDouble(convertedLine[1]) / 60;
                                currPoint.setNewPointValues(lat, lon);
                                shape.add(currPoint);
                            }
                        }

                        reader.close();
                        new FiskInfoUtility().serializeFiskInfoPolygon2D(filePath + fileName + "." + format,
                                serializablePolygon2D);

                        tools = serializablePolygon2D;

                    } catch (IOException e) {
                        e.printStackTrace();
                    } catch (ArrayIndexOutOfBoundsException e) {
                        Log.e(TAG, "Error when trying to serialize file.");
                        Toast error = Toast.makeText(getActivity(), "Ingen redskaper i omrdet du definerte",
                                Toast.LENGTH_LONG);
                        e.printStackTrace();
                        error.show();
                        return;
                    } finally {
                        try {
                            if (zippedInputStream != null) {
                                zippedInputStream.close();
                            }
                        } catch (IOException e) {
                            e.printStackTrace();
                        }
                    }
                } else {
                    Toast.makeText(v.getContext(), R.string.download_failed, Toast.LENGTH_LONG).show();
                    dialog.dismiss();
                    return;
                }

            } catch (Exception e) {
                Log.d(TAG, "Could not download tools file");
                Toast.makeText(getActivity(), R.string.download_failed, Toast.LENGTH_LONG).show();
            }

            runScheduledAlarm(getResources().getInteger(R.integer.zero),
                    getResources().getInteger(R.integer.proximity_alert_interval_time_seconds));

            Toast.makeText(getActivity(), toastText, Toast.LENGTH_LONG).show();
        }
    });

    if (proximityAlertWatcher != null) {
        TypedValue outValue = new TypedValue();
        stopCurrentProximityAlertWatcherButton.setVisibility(View.VISIBLE);

        getResources().getValue(R.dimen.proximity_alert_dialog_button_text_size_small, outValue, true);
        float textSize = outValue.getFloat();

        setProximityAlertWatcherButton.setTextSize(textSize);
        stopCurrentProximityAlertWatcherButton.setTextSize(textSize);
        cancelButton.setTextSize(textSize);

        stopCurrentProximityAlertWatcherButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                proximityAlertWatcher.cancel(true);
                proximityAlertWatcher = null;
                dialog.dismiss();
            }
        });
    }

    cancelButton.setOnClickListener(onClickListenerInterface.getDismissDialogListener(dialog));

    dialog.show();
}

From source file:com.npi.muzeiflickr.ui.activities.SettingsActivity.java

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    CalligraphyConfig.initDefault("");

    setContentView(R.layout.settings_activity);

    final SharedPreferences settings = getSharedPreferences(PREFS_NAME, 0);
    final SharedPreferences.Editor editor = settings.edit();

    //Find views//from w  w w.  j av  a2 s.c o m

    Switch wifiOnly = (Switch) findViewById(R.id.wifi_only);
    mRefreshRate = (TextView) findViewById(R.id.refresh_rate);
    ImageView aboutShortcut = (ImageView) findViewById(R.id.about);
    mRequestList = (DragSortListView) findViewById(R.id.content_list);
    mUndoContainer = (RelativeLayout) findViewById(R.id.undo_container);
    mLastDeletedItemText = (TextView) findViewById(R.id.last_deleted_item);
    TextView mLastDeletedUndo = (TextView) findViewById(R.id.last_deleted_undo);

    List<RequestData> items = new ArrayList<RequestData>();
    items.addAll(Search.listAll(Search.class));
    items.addAll(User.listAll(User.class));
    items.addAll(Tag.listAll(Tag.class));
    items.addAll(FGroup.listAll(FGroup.class));

    mRequestAdapter = new RequestAdapter(this, items);

    final View footerView = getLayoutInflater().inflate(R.layout.list_footer, null);
    mRequestList.addFooterView(footerView);

    mRequestList.setAdapter(mRequestAdapter);

    mRequestList.setRemoveListener(onRemove);

    populateFooter(footerView);

    //Wifi status and setting
    wifiOnly.setChecked(settings.getBoolean(PreferenceKeys.WIFI_ONLY, false));

    wifiOnly.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
        @Override
        public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
            editor.putBoolean(PreferenceKeys.WIFI_ONLY, isChecked);
            editor.commit();
        }
    });

    //Other settings population
    int refreshRate = settings.getInt(PreferenceKeys.REFRESH_TIME, FlickrSource.DEFAULT_REFRESH_TIME);

    mRefreshRate.setText(Utils.convertDurationtoString(refreshRate));
    mRefreshRate.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            HHmsPickerBuilder hpb = new HHmsPickerBuilder().setFragmentManager(getSupportFragmentManager())
                    .setStyleResId(R.style.MyCustomBetterPickerTheme);
            hpb.show();
        }
    });

    aboutShortcut.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            AboutActivity.launchActivity(SettingsActivity.this);
        }
    });

    mLastDeletedUndo.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            if (mLastDeletedItem instanceof User) {
                User user = ((User) mLastDeletedItem);
                user.setId(null);
                user.save();
            } else if (mLastDeletedItem instanceof Search) {
                Search search = ((Search) mLastDeletedItem);
                search.setId(null);
                search.save();
            }
            mRequestAdapter.add(mLastDeletedItem);
            mRequestAdapter.notifyDataSetChanged();
            mUndoContainer.setVisibility(View.GONE);
        }
    });

}

From source file:com.moonpi.tapunlock.MainActivity.java

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);

    // Get lobster_two asset and create typeface
    // Set action bar title to lobster_two typeface
    lobsterTwo = Typeface.createFromAsset(getAssets(), "lobster_two.otf");

    int actionBarTitle = Resources.getSystem().getIdentifier("action_bar_title", "id", "android");
    actionBarTitleView = (TextView) getWindow().findViewById(actionBarTitle);

    if (actionBarTitleView != null) {
        actionBarTitleView.setTypeface(lobsterTwo);
        actionBarTitleView.setTextSize(TypedValue.COMPLEX_UNIT_SP, 28f);
        actionBarTitleView.setTextColor(getResources().getColor(R.color.blue));
    }// w w w  .j  ava2  s. c  o m

    setContentView(R.layout.activity_main);

    // Hide keyboard on app launch
    this.getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_ALWAYS_HIDDEN);
    imm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);

    // Get NFC service and adapter
    NfcManager nfcManager = (NfcManager) this.getSystemService(Context.NFC_SERVICE);
    nfcAdapter = nfcManager.getDefaultAdapter();

    // Create PendingIntent for enableForegroundDispatch for NFC tag discovery
    pIntent = PendingIntent.getActivity(this, 0,
            new Intent(this, getClass()).addFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP), 0);

    readFromJSON();
    writeToJSON();
    readFromJSON();

    // If Android 4.2 or bigger
    if (Build.VERSION.SDK_INT > 16) {
        // Check if TapUnlock folder exists, if not, create directory
        File folder = new File(Environment.getExternalStorageDirectory() + "/TapUnlock");
        boolean folderSuccess = true;

        if (!folder.exists()) {
            folderSuccess = folder.mkdir();
        }

        try {
            // If blur var bigger than 0
            if (settings.getInt("blur") > 0) {
                // If folder exists or successfully created
                if (folderSuccess) {
                    // If blurred wallpaper file doesn't exist
                    if (!ImageUtils.doesBlurredWallpaperExist()) {
                        // Get default wallpaper
                        WallpaperManager wallpaperManager = WallpaperManager.getInstance(this);
                        final Drawable wallpaperDrawable = wallpaperManager.peekFastDrawable();

                        if (wallpaperDrawable != null) {
                            // Default wallpaper to bitmap - fastBlur the bitmap - store bitmap
                            new Thread(new Runnable() {
                                @Override
                                public void run() {
                                    Bitmap bitmapToBlur = ImageUtils.drawableToBitmap(wallpaperDrawable);

                                    Bitmap blurredWallpaper = null;
                                    if (bitmapToBlur != null)
                                        blurredWallpaper = ImageUtils.fastBlur(MainActivity.this, bitmapToBlur,
                                                blur);

                                    if (blurredWallpaper != null) {
                                        ImageUtils.storeImage(blurredWallpaper);
                                    }
                                }
                            }).start();
                        }
                    }
                }
            }

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

    // Initialize layout items
    pinEdit = (EditText) findViewById(R.id.pinEdit);
    pinEdit.setImeOptions(EditorInfo.IME_ACTION_DONE);
    Button setPin = (Button) findViewById(R.id.setPin);
    ImageButton newTag = (ImageButton) findViewById(R.id.newTag);
    enabled_disabled = (TextView) findViewById(R.id.enabled_disabled);
    Switch toggle = (Switch) findViewById(R.id.toggle);
    seekBar = (SeekBar) findViewById(R.id.seekBar);
    progressBar = (ProgressBar) findViewById(R.id.progressBar);
    Button refreshWallpaper = (Button) findViewById(R.id.refreshWallpaper);
    listView = (ListView) findViewById(R.id.listView);
    backgroundBlurValue = (TextView) findViewById(R.id.backgroundBlurValue);
    noTags = (TextView) findViewById(R.id.noTags);

    // Initialize TagAdapter
    adapter = new TagAdapter(this, tags);

    registerForContextMenu(listView);

    // Set listView adapter to TapAdapter object
    listView.setAdapter(adapter);

    // Set click, check and seekBar listeners
    setPin.setOnClickListener(this);
    newTag.setOnClickListener(this);
    refreshWallpaper.setOnClickListener(this);
    toggle.setOnCheckedChangeListener(this);
    seekBar.setOnSeekBarChangeListener(this);

    // Set seekBar progress to blur var
    try {
        seekBar.setProgress(settings.getInt("blur"));

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

    // Refresh the listView height
    updateListViewHeight(listView);

    // If no tags, show 'Press + to add Tags' textView
    if (tags.length() == 0)
        noTags.setVisibility(View.VISIBLE);

    else
        noTags.setVisibility(View.INVISIBLE);

    // Scroll up
    scrollView = (ScrollView) findViewById(R.id.scrollView);

    scrollView.post(new Runnable() {
        public void run() {
            scrollView.scrollTo(0, scrollView.getTop());
            scrollView.fullScroll(View.FOCUS_UP);
        }
    });

    // If lockscreen enabled, initialize switch, text and start service
    try {
        if (settings.getBoolean("lockscreen")) {
            onStart = true;
            enabled_disabled.setText(R.string.lockscreen_enabled);
            enabled_disabled.setTextColor(getResources().getColor(R.color.green));

            toggle.setChecked(true);
        }

    } catch (JSONException e1) {
        e1.printStackTrace();
    }
}

From source file:com.abhijitvalluri.android.fitnotifications.AppSettingsActivity.java

@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_app_settings);

    Switch discardEmptySwitch;
    Switch allDaySwitch;//from   w  w w.j  av a  2s.co  m

    mFilterText = (EditText) findViewById(R.id.filter_text);
    mStartTimeButton = (Button) findViewById(R.id.start_time);
    mStopTimeButton = (Button) findViewById(R.id.stop_time);
    mNextDay = (TextView) findViewById(R.id.next_day);
    discardEmptySwitch = (Switch) findViewById(R.id.discard_empty);
    allDaySwitch = (Switch) findViewById(R.id.all_day);

    mFilterText.setHorizontallyScrolling(false);
    mFilterText.setMaxLines(5);

    if (savedInstanceState == null) {
        mAppSelection = getIntent().getParcelableExtra(APP_SELECTION_EXTRA);
        mStartTimeHour = mAppSelection.getStartTimeHour();
        mStartTimeMinute = mAppSelection.getStartTimeMinute();
        mStopTimeHour = mAppSelection.getStopTimeHour();
        mStopTimeMinute = mAppSelection.getStopTimeMinute();
        mDiscardEmptyNotifications = mAppSelection.isDiscardEmptyNotifications();
        mAllDaySchedule = mAppSelection.isAllDaySchedule();
    } else {
        mAppSelection = savedInstanceState.getParcelable(STATE_APP_SELECTION);
        mStartTimeHour = savedInstanceState.getInt(STATE_START_TIME_HOUR);
        mStartTimeMinute = savedInstanceState.getInt(STATE_START_TIME_MINUTE);
        mStopTimeHour = savedInstanceState.getInt(STATE_STOP_TIME_HOUR);
        mStopTimeMinute = savedInstanceState.getInt(STATE_STOP_TIME_MINUTE);
        mDiscardEmptyNotifications = savedInstanceState.getBoolean(STATE_DISCARD_EMPTY_NOTIFICATIONS);
        mAllDaySchedule = savedInstanceState.getBoolean(STATE_ALL_DAY_SCHEDULE);
    }

    discardEmptySwitch.setChecked(mDiscardEmptyNotifications);
    setTitle(mAppSelection.getAppName());
    mFilterText.setText(mAppSelection.getFilterText());

    allDaySwitch.setChecked(mAllDaySchedule);
    setupScheduleSettings();

    discardEmptySwitch.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
        @Override
        public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
            mDiscardEmptyNotifications = isChecked;
        }
    });

    mStartTimeButton.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            FragmentManager manager = getSupportFragmentManager();
            TimePickerFragment dialog = TimePickerFragment.newInstance(mStartTimeHour, mStartTimeMinute,
                    mStopTimeHour, mStopTimeMinute, START_TIME_REQUEST);
            dialog.show(manager, DIALOG_TIME);
        }
    });

    mStopTimeButton.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            FragmentManager manager = getSupportFragmentManager();
            TimePickerFragment dialog = TimePickerFragment.newInstance(mStopTimeHour, mStopTimeMinute,
                    mStartTimeHour, mStartTimeMinute, STOP_TIME_REQUEST);
            dialog.show(manager, DIALOG_TIME);
        }
    });

    allDaySwitch.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
        @Override
        public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
            mAllDaySchedule = isChecked;
            setupScheduleSettings();
        }
    });
}