Example usage for android.preference PreferenceManager setDefaultValues

List of usage examples for android.preference PreferenceManager setDefaultValues

Introduction

In this page you can find the example usage for android.preference PreferenceManager setDefaultValues.

Prototype

public static void setDefaultValues(Context context, @XmlRes int resId, boolean readAgain) 

Source Link

Document

Sets the default values from an XML preference file by reading the values defined by each Preference item's android:defaultValue attribute.

Usage

From source file:org.openhab.habdroid.ui.OpenHABMainActivity.java

@Override
protected void onCreate(Bundle savedInstanceState) {
    Log.d(TAG, "onCreate()");

    // Set default values, false means do it one time during the very first launch
    PreferenceManager.setDefaultValues(this, R.xml.preferences, false);

    SharedPreferences sharedPrefs = PreferenceManager.getDefaultSharedPreferences(this);
    // Set non-persistent HABDroid version preference to current version from application package
    try {//from  ww w . j a va 2 s .c om
        Log.d(TAG, "App version = " + getPackageManager().getPackageInfo(getPackageName(), 0).versionName);
        sharedPrefs.edit().putString(Constants.PREFERENCE_APPVERSION,
                getPackageManager().getPackageInfo(getPackageName(), 0).versionName).commit();
    } catch (PackageManager.NameNotFoundException e1) {
        Log.d(TAG, e1.getMessage());
    }

    checkDiscoveryPermissions();
    checkVoiceRecognition();

    // initialize loopj async http client
    mAsyncHttpClient = new MyAsyncHttpClient(this, sharedPrefs.getBoolean(Constants.PREFERENCE_SSLHOST, false),
            sharedPrefs.getBoolean(Constants.PREFERENCE_SSLCERT, false));

    // Set the theme to one from preferences
    mSettings = PreferenceManager.getDefaultSharedPreferences(this);

    // Disable screen timeout if set in preferences
    if (mSettings.getBoolean(Constants.PREFERENCE_SCREENTIMEROFF, false)) {
        getWindow().addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);
    }

    // Fetch openHAB service type name from strings.xml
    openHABServiceType = getString(R.string.openhab_service_type);

    // Get username/password from preferences
    openHABUsername = mSettings.getString(Constants.PREFERENCE_USERNAME, null);
    openHABPassword = mSettings.getString(Constants.PREFERENCE_PASSWORD, null);
    mAsyncHttpClient.setBasicAuth(openHABUsername, openHABPassword, true);
    mAsyncHttpClient.setTimeout(30000);

    if (!BuildConfig.IS_DEVELOPER) {
        Util.initCrittercism(getApplicationContext(), "5117659f59e1bd4ba9000004");
    }

    Util.setActivityTheme(this);
    super.onCreate(savedInstanceState);

    if (!BuildConfig.IS_DEVELOPER) {
        ((HABDroid) getApplication()).getTracker(HABDroid.TrackerName.APP_TRACKER);
    }

    setContentView(R.layout.activity_main);

    setupToolbar();
    setupDrawer();
    gcmRegisterBackground();
    setupPager();

    MemorizingTrustManager.setResponder(this);

    // Check if we have openHAB page url in saved instance state?
    if (savedInstanceState != null) {
        openHABBaseUrl = savedInstanceState.getString("openHABBaseUrl");
        sitemapRootUrl = savedInstanceState.getString("sitemapRootUrl");
        mStartedWithNetworkConnectivityInfo = savedInstanceState
                .getParcelable("startedWithNetworkConnectivityInfo");
        mOpenHABVersion = savedInstanceState.getInt("openHABVersion");
        mSitemapList = savedInstanceState.getParcelableArrayList("sitemapList");
        pagerAdapter.setOpenHABBaseUrl(openHABBaseUrl);
    }

    if (mSitemapList == null) {
        mSitemapList = new ArrayList<>();
    }

    if (getIntent() != null) {
        Log.d(TAG, "Intent != null");
        if (getIntent().getAction() != null) {
            Log.d(TAG, "Intent action = " + getIntent().getAction());
            if (getIntent().getAction().equals("android.nfc.action.NDEF_DISCOVERED")) {
                Log.d(TAG, "This is NFC action");
                if (getIntent().getDataString() != null) {
                    Log.d(TAG, "NFC data = " + getIntent().getDataString());
                    mNfcData = getIntent().getDataString();
                }
            } else if (getIntent().getAction().equals("org.openhab.notification.selected")) {
                onNotificationSelected(getIntent());
            } else if (getIntent().getAction().equals("android.intent.action.VIEW")) {
                Log.d(TAG, "This is URL Action");
                mNfcData = getIntent().getDataString();
            }
        }
    }

    if (isFullscreenEnabled()) {
        registerReceiver(dreamReceiver, new IntentFilter("android.intent.action.DREAMING_STARTED"));
        registerReceiver(dreamReceiver, new IntentFilter("android.intent.action.DREAMING_STOPPED"));
        checkFullscreen();
    }

    Api api = new Api(this);
    api.process();
}

From source file:com.honglang.zxing.CaptureActivity.java

@Override
public void onCreate(Bundle icicle) {
    super.onCreate(icicle);

    Window window = getWindow();/*from  w  w w  .  j a va 2 s. c o  m*/
    window.addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);
    setContentView(R.layout.activity_capture);

    app = (HlApp) getApplication();
    title = (TextView) this.findViewById(R.id.title);
    back = (Button) this.findViewById(R.id.back);
    back.setOnClickListener(this);
    //      ok = (Button) this.findViewById(R.id.ok);
    //      ok.setText("");
    //      ok.setVisibility(View.VISIBLE);
    //      ok.setOnClickListener(this);

    linear = (LinearLayout) findViewById(R.id.out);
    jf = (LinearLayout) findViewById(R.id.jf);
    jf.setOnClickListener(this);
    pc = (LinearLayout) findViewById(R.id.pc);
    pc.setOnClickListener(this);

    qsno = (TextView) findViewById(R.id.qsno);
    jfCount = (TextView) findViewById(R.id.jfCount);
    jfRecords = (TextView) findViewById(R.id.jfRecords);
    jfCode = (TextView) findViewById(R.id.jfCode);
    pcno = (TextView) findViewById(R.id.pcno);
    pcCount = (TextView) findViewById(R.id.pcCount);
    pcRecords = (TextView) findViewById(R.id.pcRecords);
    pcCode = (TextView) findViewById(R.id.pcCode);
    count = (TextView) findViewById(R.id.count);
    record = (TextView) findViewById(R.id.record);
    sure = (Button) findViewById(R.id.sure);
    sure.setOnClickListener(this);

    soundPool = new SoundPool(4, AudioManager.STREAM_SYSTEM, 5);
    soundPool.load(this, R.raw.success, 1);
    soundPool.load(this, R.raw.done, 1);
    soundPool.load(this, R.raw.both, 1);
    soundPool.load(this, R.raw.failed, 1);

    TYPE = this.getIntent().getExtras().getInt("QRTYPE");
    switch (TYPE) {
    case 0:
        title.setText("???");
        break;
    case 1:
        title.setText("???");
        break;
    case 2:
        title.setText("????");
        break;
    case 3:
        title.setText("????");
        break;
    case 4:
        title.setText("??");
        break;
    case 5:
        title.setText("???");
        break;
    case 6:
        title.setText("");
        linear.setVisibility(View.VISIBLE);
        new NewTask().execute((Void) null);
        break;
    }

    hasSurface = false;
    historyManager = new HistoryManager(this);
    historyManager.trimHistory();
    inactivityTimer = new InactivityTimer(this);
    beepManager = new BeepManager(this);
    ambientLightManager = new AmbientLightManager(this);

    PreferenceManager.setDefaultValues(this, R.xml.preferences, false);
}

From source file:ma.wanam.xtouchwiz.XTouchWizActivity.java

@Override
public void onRestoreDefaults() {

    MainApplication.getSharedPreferences().edit().clear().commit();
    PreferenceManager.setDefaultValues(this, R.xml.wanam_settings, false);

    Toast.makeText(this, R.string.defaults_restored, Toast.LENGTH_SHORT).show();

    MainApplication.getSharedPreferences().edit().putInt("notificationSize", MainApplication.getWindowsSize().x)
            .commit();//ww  w  .j av  a 2 s . c o  m

    XCscFeaturesManager.applyCscFeatures(MainApplication.getSharedPreferences());

    recreate();

    RebootNotification.notify(this, 999, false);
}

From source file:org.uoyabause.android.YabauseHandler.java

/** Called when the activity is first created. */
@Override/*from w w  w.java2  s .c  om*/
public void onCreate(Bundle savedInstanceState) {
    SharedPreferences sharedPref = PreferenceManager.getDefaultSharedPreferences(Yabause.this);
    boolean lock_landscape = sharedPref.getBoolean("pref_landscape", false);
    if (lock_landscape == true) {
        setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE);
    } else {
        setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_UNSPECIFIED);
    }

    super.onCreate(savedInstanceState);
    System.gc();

    YabauseApplication application = (YabauseApplication) getApplication();
    mTracker = application.getDefaultTracker();

    setContentView(R.layout.main);
    getWindow().setSustainedPerformanceMode(true);
    getWindow().addFlags(
            WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON | WindowManager.LayoutParams.FLAG_FULLSCREEN);
    mDrawerLayout = (DrawerLayout) findViewById(R.id.drawer_layout);
    mDrawerLayout.setSystemUiVisibility(
            View.SYSTEM_UI_FLAG_LAYOUT_STABLE | View.SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION
                    | View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN | View.SYSTEM_UI_FLAG_HIDE_NAVIGATION
                    | View.SYSTEM_UI_FLAG_FULLSCREEN | View.SYSTEM_UI_FLAG_IMMERSIVE_STICKY);
    mNavigationView = (NavigationView) findViewById(R.id.nav_view);
    mNavigationView.setNavigationItemSelectedListener(this);
    if (sharedPref.getBoolean("pref_analog_pad", false) == true) {
        mNavigationView.setCheckedItem(R.id.pad_mode);
    }

    DrawerLayout.DrawerListener drawerListener = new DrawerLayout.DrawerListener() {
        @Override
        public void onDrawerSlide(View view, float v) {

        }

        @Override
        public void onDrawerOpened(View view) {
            if (menu_showing == false) {
                menu_showing = true;
                YabauseRunnable.pause();
                audio.mute(audio.SYSTEM);
                String name = YabauseRunnable.getGameTitle();
                TextView tx = (TextView) findViewById(R.id.menu_title);
                if (tx != null) {
                    tx.setText(name);
                }

                if (adView != null) {
                    LinearLayout lp = (LinearLayout) findViewById(R.id.navilayer);
                    if (lp != null) {
                        final int mCount = lp.getChildCount();
                        boolean find = false;
                        for (int i = 0; i < mCount; ++i) {
                            final View mChild = lp.getChildAt(i);
                            if (mChild == adView) {
                                find = true;
                            }
                        }
                        if (find == false) {
                            lp.addView(adView);
                        }
                        AdRequest adRequest = new AdRequest.Builder()
                                .addTestDevice("303A789B146C169D4BDB5652D928FF8E").build();
                        adView.loadAd(adRequest);
                    }
                }

            }
        }

        @Override
        public void onDrawerClosed(View view) {

            if (waiting_reault == false && menu_showing == true) {
                menu_showing = false;
                YabauseRunnable.resume();
                audio.unmute(audio.SYSTEM);
            }

        }

        @Override
        public void onDrawerStateChanged(int i) {
        }
    };
    this.mDrawerLayout.setDrawerListener(drawerListener);

    audio = new YabauseAudio(this);

    Intent intent = getIntent();
    String game = intent.getStringExtra("org.uoyabause.android.FileName");
    if (game != null && game.length() > 0) {
        YabauseStorage storage = YabauseStorage.getStorage();
        gamepath = storage.getGamePath(game);
    } else
        gamepath = "";

    String exgame = intent.getStringExtra("org.uoyabause.android.FileNameEx");
    if (exgame != null) {
        gamepath = exgame;
    }

    PreferenceManager.setDefaultValues(this, R.xml.preferences, false);
    readPreferences();

    padm = PadManager.getPadManager();
    padm.loadSettings();
    waiting_reault = false;

    handler = new YabauseHandler(this);
    yabauseThread = new YabauseRunnable(this);

    UiModeManager uiModeManager = (UiModeManager) getSystemService(Context.UI_MODE_SERVICE);
    if (uiModeManager.getCurrentModeType() != Configuration.UI_MODE_TYPE_TELEVISION) {
        SharedPreferences prefs = getSharedPreferences("private", Context.MODE_PRIVATE);
        Boolean hasDonated = prefs.getBoolean("donated", false);
        if (hasDonated) {
            adView = null;
        } else {
            adView = new AdView(this);
            adView.setAdUnitId(getString(R.string.banner_ad_unit_id2));
            adView.setAdSize(AdSize.BANNER);
            AdRequest adRequest = new AdRequest.Builder().build();
            adView.loadAd(adRequest);
            adView.setAdListener(new AdListener() {
                @Override
                public void onAdOpened() {
                    // Save app state before going to the ad overlay.
                }
            });
        }
    } else {
        adView = null;
    }

}

From source file:org.schabi.newpipe.VideoItemListActivity.java

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_videoitem_list);
    StreamingService streamingService = null;

    View bg = findViewById(R.id.mainBG);
    bg.setVisibility(View.VISIBLE);

    try {/* w  ww  .jav  a2s .c  o m*/
        //------ todo: remove this line when multiservice support is implemented ------
        currentStreamingServiceId = ServiceList.getIdOfService("Youtube");
        streamingService = ServiceList.getService(currentStreamingServiceId);
    } catch (Exception e) {
        e.printStackTrace();
        ErrorActivity.reportError(VideoItemListActivity.this, e, null, findViewById(R.id.videoitem_list),
                ErrorActivity.ErrorInfo.make(ErrorActivity.SEARCHED,
                        ServiceList.getNameOfService(currentStreamingServiceId), "", R.string.general_error));
    }
    setVolumeControlStream(AudioManager.STREAM_MUSIC);
    listFragment = (VideoItemListFragment) getSupportFragmentManager().findFragmentById(R.id.videoitem_list);
    listFragment.setStreamingService(streamingService);

    if (savedInstanceState != null && mode != PRESENT_VIDEOS_MODE) {
        searchQuery = savedInstanceState.getString(QUERY);
        currentStreamingServiceId = savedInstanceState.getInt(STREAMING_SERVICE);
        if (!searchQuery.isEmpty()) {
            listFragment.search(searchQuery);
        }
    }

    if (findViewById(R.id.videoitem_detail_container) != null) {
        // The detail container view will be present only in the
        // large-screen layouts (res/values-large and
        // res/values-sw600dp). If this view is present, then the
        // activity should be in two-pane mode.
        mTwoPane = true;

        // In two-pane mode, list items should be given the
        // 'activated' state when touched.

        ((VideoItemListFragment) getSupportFragmentManager().findFragmentById(R.id.videoitem_list))
                .setActivateOnItemClick(true);

        SearchView searchView = (SearchView) findViewById(R.id.searchViewTablet);
        if (mode != PRESENT_VIDEOS_MODE) {
            // Somehow the seticonifiedbydefault property set by the layout xml is not working on
            // the support version on SearchView, so it needs to be set programmatically.
            searchView.setIconifiedByDefault(false);
            searchView.setIconified(false);
            if (!searchQuery.isEmpty()) {
                searchView.setQuery(searchQuery, false);
            }
            searchView.setOnQueryTextListener(new SearchVideoQueryListener());
            suggestionListAdapter = new SuggestionListAdapter(this);
            searchView.setSuggestionsAdapter(suggestionListAdapter);
            searchView.setOnSuggestionListener(new SearchSuggestionListener(searchView));
        } else {
            searchView.setVisibility(View.GONE);
        }
    }

    PreferenceManager.setDefaultValues(this, R.xml.settings, false);
}

From source file:com.nuvolect.securesuite.main.ContactListActivity.java

/**
 * Start the GUI, method assumes that a master account is already set
 */// w ww. j av  a2  s. c  o  m
private void startGui() {

    SqlCipher.getInstance(m_ctx);
    /**
     * Detect app upgrade and provide a placeholder for managing upgrades, database changes, etc.
     */
    boolean appUpgraded = LicenseUtil.appUpgraded(m_act);

    if (appUpgraded) {

        Toast.makeText(getApplicationContext(), "Application upgraded", Toast.LENGTH_LONG).show();

        // Execute upgrade methods
    }

    // Set default settings
    PreferenceManager.setDefaultValues(this, R.xml.settings, false);

    // Set the progress bar to off, otherwise some devices will default to on
    setProgressBarIndeterminateVisibility(false);

    // Load group data into memory, used for group titles and people counts
    MyGroups.loadGroupMemory();

    boolean isFirstTime = Persist.isStartingUp(m_ctx);
    if (isFirstTime) {

        String account = LicensePersist.getLicenseAccount(m_ctx);
        Cryp.setCurrentAccount(account);
        MyGroups.addBaseGroupsToNewAccount(m_ctx, account);
        Cryp.setCurrentGroup(MyGroups.getDefaultGroup(account));

        try {
            // Import a default contact when starting first time
            InputStream vcf = getResources().getAssets().open(CConst.APP_VCF);
            ImportVcard.importVcf(m_ctx, vcf, Cryp.getCurrentGroup());

        } catch (IOException e) {
            LogUtil.logException(ContactListActivity.class, e);
        }

        // First time, request phone management access
        PermissionUtil.requestFirstTimePermissions(m_act);
    }

    // Support for action bar pull down menu
    adapter = ArrayAdapter.createFromResource(this, R.array.action_bar_spinner_menu,
            android.R.layout.simple_spinner_dropdown_item);

    // Action bar spinner menu callback
    navigationListener = new OnNavigationListener() {

        // List items from resource
        String[] navItems = getResources().getStringArray(R.array.action_bar_spinner_menu);

        @Override
        public boolean onNavigationItemSelected(int position, long id) {

            if (DEBUG)
                LogUtil.log("ContactListActivity NavigationItemSelected: " + navItems[position]);

            // Do stuff when navigation item is selected
            switch (CConst.NavMenu.values()[position]) {

            case contacts: {

                // Persist the navigation selection for fragments to pick up
                Persist.setNavChoice(m_act, position, navItems[position]);

                break;
            }

            case groups: {

                // Persist the navigation selection for fragments to pick up
                Persist.setNavChoice(m_act, position, navItems[position]);

                // Dispatch to the main group list activity
                Intent intent = new Intent(m_act, GroupListActivity.class);
                startActivity(intent);

                // Remove this activity from the stack
                // Group list is the only activity on the stack
                m_act.finish();

                break;
            }
            case passwords: {

                actionBar.setSelectedNavigationItem(Persist.getNavChoice(m_act));
                PasswordFragment f = PasswordFragment.newInstance(m_act);
                f.start();
                break;
            }
            case calendar: {

                Intent intent = new Intent(m_act, CalendarActivity.class);
                startActivity(intent);
                break;
            }
            case finder: {

                Intent intent = new Intent(m_act, FinderActivity.class);
                startActivity(intent);
                break;
            }
            case server: {

                /**
                 * Restore the spinner such that the Password is never persisted
                 * and never shows.
                 */
                actionBar.setSelectedNavigationItem(Persist.getNavChoice(m_act));
                ServerFragment f = ServerFragment.newInstance(m_act);
                f.start();
                break;
            }
            default:
            }
            return true;
        }
    };

    actionBar = getActionBar();
    ActionBarUtil.setNavigationMode(actionBar, ActionBar.NAVIGATION_MODE_LIST);
    ActionBarUtil.setDisplayShowTitleEnabled(actionBar, false);
    ActionBarUtil.setListNavigationCallbacks(actionBar, adapter, navigationListener);
    AppTheme.applyActionBarTheme(m_act, actionBar);

    // Start with the previous contact or reset to a valid contact
    m_contact_id = Persist.getCurrentContactId(m_act);
    if (m_contact_id <= 0 || !SqlCipher.validContactId(m_contact_id)) {
        m_contact_id = SqlCipher.getFirstContactID();
        Persist.setCurrentContactId(m_act, m_contact_id);
    }

    // savedInstanceState is non-null when there is fragment state
    // saved from previous configurations of this activity
    // (e.g. when rotating the screen from portrait to landscape).
    // In this case, the fragment will automatically be re-added
    // to its container so we don't need to manually add it.
    // For more information, see the Fragments API guide at:
    //
    // http://developer.android.com/guide/components/fragments.html
    //
    if (isFirstTime || m_savedInstanceState == null) {

        if (findViewById(R.id.contact_detail_container) != null) {
            // Setup for single or dual fragments depending on display size
            // The detail container view will be present only in the large-screen layouts
            // (res/values-large and res/values-sw600dp). If this view is present, then the
            // activity should be in two-pane mode.
            mTwoPane = true;

            m_clf_fragment = startContactListFragment();

            // In two-pane mode, list items should be given the 'activated' state when touched.
            m_clf_fragment.setActivateOnItemClick(true);

            // In two-pane mode, show the detail view in this activity by
            // adding or replacing the detail fragment using a fragment transaction.
            startContactDetailFragment();

        } else {
            mTwoPane = false;
            m_clf_fragment = startContactListFragment();
        }
    }
}

From source file:com.xgf.inspection.qrcode.google.zxing.client.CaptureActivity.java

@Override
public void onCreate(Bundle icicle) {
    super.onCreate(icicle);

    Window window = getWindow();//  w w  w  .  j ava  2s .  c o m
    window.addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);
    setContentView(R.layout.capture);
    mContext = CaptureActivity.this;

    hasSurface = false;
    historyManager = new HistoryManager(this);
    historyManager.trimHistory();
    inactivityTimer = new InactivityTimer(this);
    beepManager = new BeepManager(this);

    mBackIv = (ImageView) findViewById(R.id.qr_back_iv);
    mBackIv.setOnClickListener(new OnClickListener() {

        @Override
        public void onClick(View v) {
            CaptureActivity.this.finish();
        }
    });

    // TODO
    // add
    mQrUploadTv = (TextView) findViewById(R.id.qr_upload_tv);

    mQrUploadTv.setOnClickListener(new OnClickListener() {
        @Override
        public void onClick(View v) {
            if (mIsHasUpload) {
                uploadData();
            }
            // Intent intent = new Intent(getApplicationContext(),
            // UploadService.class);
            // getApplicationContext().startService(intent);
        }
    });
    isHasUpload();

    PreferenceManager.setDefaultValues(this, R.xml.preferences, false);

    mNowAction = getIntent().getAction();
    // showHelpOnFirstLaunch();
}

From source file:org.billthefarmer.tuner.MainActivity.java

void getPreferences() {
    // Load preferences

    PreferenceManager.setDefaultValues(this, R.xml.preferences, false);

    SharedPreferences preferences = PreferenceManager.getDefaultSharedPreferences(this);

    // Set preferences
    if (audio != null) {
        audio.input = Integer.parseInt(preferences.getString(PREF_INPUT, "0"));
        audio.reference = preferences.getInt(PREF_REFERENCE, 440);
        audio.transpose = Integer.parseInt(preferences.getString(PREF_TRANSPOSE, "0"));

        audio.filter = preferences.getBoolean(PREF_FILTER, false);
        audio.downsample = preferences.getBoolean(PREF_DOWNSAMPLE, false);
        audio.multiple = preferences.getBoolean(PREF_MULTIPLE, false);
        audio.screen = preferences.getBoolean(PREF_SCREEN, false);
        audio.strobe = preferences.getBoolean(PREF_STROBE, false);
        audio.zoom = preferences.getBoolean(PREF_ZOOM, true);

        // Check screen
        if (audio.screen) {
            Window window = getWindow();
            window.addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);
        }//w  ww  .  j a v  a 2s  . c o m

        else {
            Window window = getWindow();
            window.clearFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);
        }

        // Check for strobe before setting colours
        if (strobe != null) {
            strobe.colour = Integer.valueOf(preferences.getString(PREF_COLOUR, "0"));

            if (strobe.colour == 3) {
                JSONArray custom;

                try {
                    custom = new JSONArray(preferences.getString(PREF_CUSTOM, null));

                    strobe.foreground = custom.getInt(0);
                    strobe.background = custom.getInt(1);
                }

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

            // Ensure the view dimensions have been set
            if (strobe.width > 0 && strobe.height > 0)
                strobe.createShaders();
        }
    }
}

From source file:com.softanalle.scma.MainActivity.java

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setTheme(android.R.style.Theme_Black_NoTitleBar_Fullscreen);
    setContentView(R.layout.activity_main);

    PropertyConfigurator.getConfigurator(this).configure();

    logger.debug("onCreate()");

    pictureButton_ = (Button) findViewById(R.id.pictureButton);
    toggleButton_ = (ToggleButton) findViewById(R.id.powerButton);
    ledIndicator_ = (LedIndicator) findViewById(R.id.ledIndicator1);
    focusButton_ = (Button) findViewById(R.id.focusButton);

    toggleButton_.setEnabled(false);//from  ww  w.jav  a  2  s .c o m
    toggleButton_.setChecked(false);

    // camera stuff

    if (checkCameraHardware(getApplicationContext())) {
        // ok, we have camera
        Log.i(TAG, "Device has camera");
    } else {
        logger.error("Unable to find camera");
        Toast.makeText(getApplicationContext(), "Camera is missing!", Toast.LENGTH_LONG).show();
    }

    FrameLayout tmp = (FrameLayout) findViewById(R.id.camera_preview);

    mPreview = new Preview(this);

    logger.debug("Created Preview -object");
    //Log.d(TAG, "Preview created");

    mPreview.startPreview();
    logger.debug("Preview object started");

    if (tmp == null) {
        logger.debug(TAG + ": Layout IS NULL");
        Toast.makeText(getApplicationContext(), "Layout is NULL: ", Toast.LENGTH_LONG).show();
        //} else {

        //Log.d(TAG, "Layout found");
    }

    if (mPreview != null) {
        logger.debug("Will add preview");
        try {
            tmp.addView(mPreview);
            //tmp.addView(mPreview);
        } catch (Exception e) {
            logger.error("onCreate(): got exception: " + e.toString());
            Toast.makeText(getApplicationContext(), "Got exception: " + e.toString(), Toast.LENGTH_LONG).show();

        }

    } else {
        logger.error("onCreate(): Preview creation FAILED");
    }

    logger.debug("onCreate(): Added preview");

    ledIndicator_.bringToFront();
    toggleButton_.bringToFront();
    pictureButton_.bringToFront();
    focusButton_.bringToFront();

    mPulseWidth = new int[mLedCount];
    mLedState = new boolean[mLedCount];
    mDefaultPulseWidth = new int[mLedCount];
    synchronized (lock_) {
        for (int index = 0; index < mLedCount; index++) {
            mLedState[index] = false;

            mDefaultPulseWidth[index] = defaultPulseWidth;
            //mPulseWidth[index] = mDefaultPulseWidth[index];
        }
    }

    pictureButton_.setOnClickListener(new OnClickListener() {

        @Override
        public void onClick(View v) {
            logger.debug("pictureButton.onClick()");
            if (powerState_) {
                // disable buttons -> no error clicks
                pictureButton_.setEnabled(false);
                toggleButton_.setEnabled(false);
                focusButton_.setEnabled(false);
                Runnable runnable = new Runnable() {
                    @Override
                    public void run() {
                        // run the picture sequence
                        takeColorSeries();
                    }
                };

                new Thread(runnable).start();
            }
        }
    });

    toggleButton_.setOnClickListener(new OnClickListener() {

        @Override
        public void onClick(View v) {
            logger.debug("toggleButton.onClick(" + ((ToggleButton) v).isChecked() + ")");
            // mPreview.camera.takePicture(shutterCallback, rawCallback, jpegCallback);
            if (((ToggleButton) v).isChecked()) {
                powerState_ = true;
                pictureButton_.setEnabled(true);
                mLedState[mFocusLedIndex] = true;
                mPulseWidth[mFocusLedIndex] = defaultFocusPulseWidth;
                mCurrentLedIndex = mFocusLedIndex;

                // make sure we don't go to screenlock while working
                /*
                PowerManager pm = (PowerManager) getApplicationContext().getSystemService( Context.POWER_SERVICE );
                wl = pm.newWakeLock(
                      PowerManager.SCREEN_DIM_WAKE_LOCK
                      | PowerManager.ON_AFTER_RELEASE,
                      TAG);               
                wl.acquire();
                */
            } else {
                powerState_ = false;
                pictureButton_.setEnabled(false);
                mShutdown = true;
                mLedState[mFocusLedIndex] = false;

                // release screen un-locker
                //wl.release();

            }
        }
    });

    focusButton_.setOnClickListener(new OnClickListener() {
        @Override
        public void onClick(View v) {
            logger.debug("focusButton.onClick()");
            try {
                ledIndicator_.setLedState(LED_INDEX_FOCUS, true);
                Thread.sleep(10);
                focusCamera();
                Thread.sleep(10);
                ledIndicator_.setLedState(LED_INDEX_FOCUS, false);
            } catch (Exception e) {

            }
        }
    });

    pictureButton_.setEnabled(false);

    logger.debug("onCreate(): controls initialized");

    Log.d(TAG, "onCreate'd");
    mDPM = (DevicePolicyManager) getSystemService(Context.DEVICE_POLICY_SERVICE);
    Log.d(TAG, "  getCameraDisabled(): " + mDPM.getCameraDisabled(null));

    // Display the fragment as the main content.
    /*
      getFragmentManager().beginTransaction()
        .replace(android.R.id.content, new SettingsFragment())
        .commit();
    */
    PreferenceManager.setDefaultValues(this, R.xml.preferences, false);

    getSettings();

    /*
    List<Integer> modes = mPreview.getSupportedPictureFormats();
    String lista = "";
    if ( modes != null && modes.size() > 0) {
       for (Integer i : modes) {
    lista += Integer.toString(i) + " ";
       }
    } else {
       lista = "List query failed";
    }
    Toast.makeText(getApplicationContext(), "Supported Picture formats: " + lista, Toast.LENGTH_LONG).show();
    */
    enableUi(false);
    Log.d(TAG, "onCreate - done");
    /*
           cl = new ChangeLog(this);
           if (cl.firstRun())
               cl.getLogDialog().show();
       */
    // set windows flags to keep full screen
    this.getWindow().addFlags(
            WindowManager.LayoutParams.FLAG_FULLSCREEN | WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);
}