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:de.baumann.browser.Browser_right.java

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

    getWindow().addFlags(WindowManager.LayoutParams.FLAG_DRAWS_SYSTEM_BAR_BACKGROUNDS);
    getWindow().setStatusBarColor(ContextCompat.getColor(Browser_right.this, R.color.colorTwoDark));

    WebView.enableSlowWholeDocumentDraw();
    setContentView(R.layout.activity_browser);
    helper_main.onStart(Browser_right.this);

    PreferenceManager.setDefaultValues(this, R.xml.user_settings, false);
    PreferenceManager.setDefaultValues(this, R.xml.user_settings_search, false);
    sharedPref = PreferenceManager.getDefaultSharedPreferences(this);
    sharedPref.edit()//from  w ww .  j  a  v  a  2s .  c om
            .putString("openURL", sharedPref.getString("startURL", "https://github.com/scoute-dich/browser/"))
            .apply();
    sharedPref.edit().putInt("keyboard", 0).apply();
    sharedPref.getInt("keyboard", 0);

    Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
    toolbar.setBackgroundColor(ContextCompat.getColor(Browser_right.this, R.color.colorTwo));
    setSupportActionBar(toolbar);

    actionBar = getSupportActionBar();

    customViewContainer = (FrameLayout) findViewById(R.id.customViewContainer);
    progressBar = (ProgressBar) findViewById(R.id.progressBar);

    editText = (EditText) findViewById(R.id.editText);
    editText.setVisibility(View.GONE);
    editText.setHint(R.string.app_search_hint);
    editText.clearFocus();

    urlBar = (TextView) findViewById(R.id.urlBar);

    imageButton = (ImageButton) findViewById(R.id.imageButton);
    imageButton.setVisibility(View.INVISIBLE);
    imageButton.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            mWebView.scrollTo(0, 0);
            imageButton.setVisibility(View.INVISIBLE);
            if (!actionBar.isShowing()) {
                urlBar.setText(mWebView.getTitle());
                actionBar.show();
            }
            helper_browser.setNavArrows(mWebView, imageButton_left, imageButton_right);
        }
    });

    SwipeRefreshLayout swipeView = (SwipeRefreshLayout) findViewById(R.id.swipe);
    assert swipeView != null;
    swipeView.setColorSchemeResources(R.color.colorTwo, R.color.colorAccent);
    swipeView.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() {
        @Override
        public void onRefresh() {
            mWebView.reload();
        }
    });

    mWebView = (ObservableWebView) findViewById(R.id.webView);
    if (sharedPref.getString("fullscreen", "2").equals("2")
            || sharedPref.getString("fullscreen", "2").equals("3")) {
        mWebView.setScrollViewCallbacks(this);
    }

    mWebChromeClient = new myWebChromeClient();
    mWebView.setWebChromeClient(mWebChromeClient);

    imageButton_left = (ImageButton) findViewById(R.id.imageButton_left);
    imageButton_right = (ImageButton) findViewById(R.id.imageButton_right);

    if (sharedPref.getBoolean("arrow", false)) {
        imageButton_left.setVisibility(View.VISIBLE);
        imageButton_right.setVisibility(View.VISIBLE);
    } else {
        imageButton_left.setVisibility(View.INVISIBLE);
        imageButton_right.setVisibility(View.INVISIBLE);
    }

    helper_webView.webView_Settings(Browser_right.this, mWebView);
    helper_webView.webView_WebViewClient(Browser_right.this, swipeView, mWebView, urlBar);

    mWebView.getSettings().setCacheMode(WebSettings.LOAD_DEFAULT);

    if (isNetworkUnAvailable()) {
        if (sharedPref.getBoolean("offline", false)) {
            if (isNetworkUnAvailable()) { // loading offline
                mWebView.getSettings().setCacheMode(WebSettings.LOAD_CACHE_ELSE_NETWORK);
                Snackbar.make(mWebView, R.string.toast_cache, Snackbar.LENGTH_SHORT).show();
            }
        } else {
            Snackbar.make(mWebView, R.string.toast_noInternet, Snackbar.LENGTH_SHORT).show();
        }
    }

    mWebView.setDownloadListener(new DownloadListener() {

        public void onDownloadStart(final String url, String userAgent, final String contentDisposition,
                final String mimetype, long contentLength) {

            registerReceiver(onComplete, new IntentFilter(DownloadManager.ACTION_DOWNLOAD_COMPLETE));

            final String filename = URLUtil.guessFileName(url, contentDisposition, mimetype);
            Snackbar snackbar = Snackbar
                    .make(mWebView, getString(R.string.toast_download_1) + " " + filename, Snackbar.LENGTH_LONG)
                    .setAction(getString(R.string.toast_yes), new View.OnClickListener() {
                        @Override
                        public void onClick(View view) {
                            DownloadManager.Request request = new DownloadManager.Request(Uri.parse(url));
                            request.addRequestHeader("Cookie", CookieManager.getInstance().getCookie(url));
                            request.allowScanningByMediaScanner();
                            request.setNotificationVisibility(
                                    DownloadManager.Request.VISIBILITY_VISIBLE_NOTIFY_COMPLETED); //Notify client once download is completed!
                            request.setDestinationInExternalPublicDir(Environment.DIRECTORY_DOWNLOADS,
                                    filename);
                            DownloadManager dm = (DownloadManager) getSystemService(DOWNLOAD_SERVICE);
                            dm.enqueue(request);

                            Snackbar.make(mWebView, getString(R.string.toast_download) + " " + filename,
                                    Snackbar.LENGTH_SHORT).show();
                        }
                    });
            snackbar.show();
        }
    });

    helper_browser.toolbar(Browser_right.this, Browser_left.class, mWebView, toolbar);
    helper_editText.editText_EditorAction(editText, Browser_right.this, mWebView, urlBar);
    helper_editText.editText_FocusChange(editText, Browser_right.this);
    helper_main.grantPermissionsStorage(Browser_right.this);

    onNewIntent(getIntent());
}

From source file:com.mpower.mintel.android.application.MIntel.java

@Override
public void onCreate() {
    singleton = this;
    MIntel.context = getApplicationContext();
    PreferenceManager.setDefaultValues(this, R.xml.preferences, false);
    super.onCreate();
    // PushService.actionStart(getAppContext());
}

From source file:esolz.connexstudent.apprtc.ConnectActivity.java

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

    //=============Power locker

    threadmanager = new Handler();

    callRejectionThred = new Runnable() {
        @Override//w ww. java  2 s .  co  m
        public void run() {

            //======Missed Call and no answer

            SimpleDateFormat frmatr = new SimpleDateFormat("dd MMM,yyyy-HH:mm");

            cDB.insertInLogTable(getIntent().getStringExtra("PHONE"),
                    cDB.getUserNameFromPhone(getIntent().getStringExtra("PHONE")),
                    cDB.getUserImage(getIntent().getStringExtra("PHONE")), "missed",
                    frmatr.format(new Date(Calendar.getInstance().getTimeInMillis())));

            fireMissedCall(cDB.getUserNameFromPhone(getIntent().getStringExtra("PHONE")));
            //==================================

            Intent i = new Intent(getApplicationContext(), RingToneService.class);
            i.setAction(RingToneService.ACTION_KILL);
            startService(i);
            finish();
        }
    };

    powerManager = (PowerManager) getSystemService(POWER_SERVICE);
    wakeLock = powerManager.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, "RingToneServiceLockerActivity");
    wakeLock.acquire();

    cDB = new ConnexDB(getApplicationContext());
    // Get setting keys.
    PreferenceManager.setDefaultValues(this, R.xml.preferences, false);
    sharedPref = PreferenceManager.getDefaultSharedPreferences(this);
    keyprefVideoCallEnabled = getString(R.string.pref_videocall_key);
    keyprefResolution = getString(R.string.pref_resolution_key);
    keyprefFps = getString(R.string.pref_fps_key);
    keyprefCaptureQualitySlider = getString(R.string.pref_capturequalityslider_key);
    keyprefVideoBitrateType = getString(R.string.pref_startvideobitrate_key);
    keyprefVideoBitrateValue = getString(R.string.pref_startvideobitratevalue_key);
    keyprefVideoCodec = getString(R.string.pref_videocodec_key);
    keyprefHwCodecAcceleration = getString(R.string.pref_hwcodec_key);
    keyprefCaptureToTexture = getString(R.string.pref_capturetotexture_key);
    keyprefAudioBitrateType = getString(R.string.pref_startaudiobitrate_key);
    keyprefAudioBitrateValue = getString(R.string.pref_startaudiobitratevalue_key);
    keyprefAudioCodec = getString(R.string.pref_audiocodec_key);
    keyprefNoAudioProcessingPipeline = getString(R.string.pref_noaudioprocessing_key);
    keyprefAecDump = getString(R.string.pref_aecdump_key);
    keyprefOpenSLES = getString(R.string.pref_opensles_key);
    keyprefDisplayHud = getString(R.string.pref_displayhud_key);
    keyprefTracing = getString(R.string.pref_tracing_key);
    keyprefRoomServerUrl = getString(R.string.pref_room_server_url_key);
    keyprefRoom = getString(R.string.pref_room_key);
    keyprefRoomList = getString(R.string.pref_room_list_key);

    setContentView(R.layout.activity_connect);

    getWindow().setFlags(WindowManager.LayoutParams.FLAG_TURN_SCREEN_ON,
            WindowManager.LayoutParams.FLAG_TURN_SCREEN_ON);
    getWindow().setFlags(WindowManager.LayoutParams.FLAG_SHOW_WHEN_LOCKED,
            WindowManager.LayoutParams.FLAG_SHOW_WHEN_LOCKED);
    getWindow().setFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON,
            WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);

    //=============permission management
    findViewById(R.id.notifoicatio).setVisibility(View.GONE);

    permissionChk();

    findViewById(R.id.rcv_call).setOnClickListener(new View.OnClickListener() {

        @Override
        public void onClick(View v) {

            //======Missed Call and no answer

            threadmanager.removeCallbacks(callRejectionThred);

            SimpleDateFormat frmatr = new SimpleDateFormat("dd MMM,yyyy-HH:mm");

            cDB.insertInLogTable(getIntent().getStringExtra("PHONE"),
                    cDB.getUserNameFromPhone(getIntent().getStringExtra("PHONE")),
                    cDB.getUserImage(getIntent().getStringExtra("PHONE")), "received",
                    frmatr.format(new Date(Calendar.getInstance().getTimeInMillis())));

            //==================================

            Intent i = new Intent(getApplicationContext(), RingToneService.class);
            i.setAction(RingToneService.ACTION_KILL_WITH_NOTHING);
            startService(i);

            ROOM_NAME = getIntent().getStringExtra("ROOM_NAME");

            pushHelperDhoperUrlAcceptence();

        }
    });

    findViewById(R.id.end_call).setOnClickListener(new View.OnClickListener() {

        @Override
        public void onClick(View v) {

            if (getIntent().getAction().equals(ACTION_APP)) {
                try {
                    if (mPlayer.isPlaying()) {
                        mPlayer.stop();
                        mPlayer.release();
                    }
                    finish();
                } catch (Exception e) {
                    e.printStackTrace();
                }

                dialoerRejection(ConnexConstante.DOMAIN_URL + "push_send?roomId=000000&sender_id="
                        + ConnexApplication.getInstance().getUserID() + "&receiver_id=" + RECEIVER_ID
                        + "&mod=callEnded&pem_mod=prod");

            } else {

                //======Missed Call and Rejected by You

                //======Missed Call and no answer

                threadmanager.removeCallbacks(callRejectionThred);

                SimpleDateFormat frmatr = new SimpleDateFormat("dd MMM,yyyy-HH:mm");

                cDB.insertInLogTable(getIntent().getStringExtra("PHONE"),
                        cDB.getUserNameFromPhone(getIntent().getStringExtra("PHONE")),
                        cDB.getUserImage(getIntent().getStringExtra("PHONE")), "missed",
                        frmatr.format(new Date(Calendar.getInstance().getTimeInMillis())));

                fireMissedCall(cDB.getUserNameFromPhone(getIntent().getStringExtra("PHONE")));
                //==================================

                //==================================

                Intent i = new Intent(getApplicationContext(), RingToneService.class);
                i.setAction(RingToneService.ACTION_KILL);
                startService(i);
            }

            finish();
        }
    });

    if (mPlayer == null) {
        mPlayer = MediaPlayer.create(ConnectActivity.this, R.raw.dialing);
    }

}

From source file:de.baumann.browser.Browser.java

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

    WebView.enableSlowWholeDocumentDraw();
    setContentView(R.layout.activity_browser);
    helper_main.onStart(Browser.this);

    Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
    setSupportActionBar(toolbar);/*  ww w . j ava  2s  .  c  o m*/

    PreferenceManager.setDefaultValues(this, R.xml.user_settings, false);
    PreferenceManager.setDefaultValues(this, R.xml.user_settings_search, false);
    sharedPref = PreferenceManager.getDefaultSharedPreferences(this);
    sharedPref.edit().putInt("keyboard", 0).apply();
    sharedPref.getInt("keyboard", 0);

    customViewContainer = (FrameLayout) findViewById(R.id.customViewContainer);
    progressBar = (ProgressBar) findViewById(R.id.progressBar);

    editText = (EditText) findViewById(R.id.editText);
    editText.setHint(R.string.app_search_hint);
    editText.clearFocus();

    imageButton = (ImageButton) findViewById(R.id.imageButton);
    imageButton.setVisibility(View.INVISIBLE);
    imageButton.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            mWebView.scrollTo(0, 0);
            imageButton.setVisibility(View.INVISIBLE);
            actionBar = getSupportActionBar();
            assert actionBar != null;
            if (!actionBar.isShowing()) {
                editText.setText(mWebView.getTitle());
                actionBar.show();
            }
            setNavArrows();
        }
    });

    SwipeRefreshLayout swipeView = (SwipeRefreshLayout) findViewById(R.id.swipe);
    assert swipeView != null;
    swipeView.setColorSchemeResources(R.color.colorPrimary, R.color.colorAccent);
    swipeView.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() {
        @Override
        public void onRefresh() {
            mWebView.reload();
        }
    });

    mWebView = (ObservableWebView) findViewById(R.id.webView);
    if (sharedPref.getString("fullscreen", "2").equals("2")
            || sharedPref.getString("fullscreen", "2").equals("3")) {
        mWebView.setScrollViewCallbacks(this);
    }

    mWebChromeClient = new myWebChromeClient();
    mWebView.setWebChromeClient(mWebChromeClient);

    imageButton_left = (ImageButton) findViewById(R.id.imageButton_left);
    imageButton_right = (ImageButton) findViewById(R.id.imageButton_right);

    if (sharedPref.getBoolean("arrow", false)) {
        imageButton_left.setVisibility(View.VISIBLE);
        imageButton_right.setVisibility(View.VISIBLE);
    } else {
        imageButton_left.setVisibility(View.INVISIBLE);
        imageButton_right.setVisibility(View.INVISIBLE);
    }

    helper_webView.webView_Settings(Browser.this, mWebView);
    helper_webView.webView_WebViewClient(Browser.this, swipeView, mWebView, editText);

    mWebView.getSettings().setCacheMode(WebSettings.LOAD_DEFAULT);

    if (isNetworkUnAvailable()) {
        if (sharedPref.getBoolean("offline", false)) {
            if (isNetworkUnAvailable()) { // loading offline
                mWebView.getSettings().setCacheMode(WebSettings.LOAD_CACHE_ELSE_NETWORK);
                Snackbar.make(mWebView, R.string.toast_cache, Snackbar.LENGTH_SHORT).show();
            }
        } else {
            Snackbar.make(mWebView, R.string.toast_noInternet, Snackbar.LENGTH_SHORT).show();
        }
    }

    mWebView.setDownloadListener(new DownloadListener() {

        public void onDownloadStart(final String url, String userAgent, final String contentDisposition,
                final String mimetype, long contentLength) {

            registerReceiver(onComplete, new IntentFilter(DownloadManager.ACTION_DOWNLOAD_COMPLETE));

            final String filename = URLUtil.guessFileName(url, contentDisposition, mimetype);
            Snackbar snackbar = Snackbar
                    .make(mWebView, getString(R.string.toast_download_1) + " " + filename, Snackbar.LENGTH_LONG)
                    .setAction(getString(R.string.toast_yes), new View.OnClickListener() {
                        @Override
                        public void onClick(View view) {
                            DownloadManager.Request request = new DownloadManager.Request(Uri.parse(url));
                            request.addRequestHeader("Cookie", CookieManager.getInstance().getCookie(url));
                            request.allowScanningByMediaScanner();
                            request.setNotificationVisibility(
                                    DownloadManager.Request.VISIBILITY_VISIBLE_NOTIFY_COMPLETED); //Notify client once download is completed!
                            request.setDestinationInExternalPublicDir(Environment.DIRECTORY_DOWNLOADS,
                                    filename);
                            DownloadManager dm = (DownloadManager) getSystemService(DOWNLOAD_SERVICE);
                            dm.enqueue(request);

                            Snackbar.make(mWebView, getString(R.string.toast_download) + " " + filename,
                                    Snackbar.LENGTH_SHORT).show();
                        }
                    });
            snackbar.show();
        }
    });

    helper_editText.editText_Touch(editText, Browser.this, mWebView);
    helper_editText.editText_EditorAction(editText, Browser.this, mWebView);
    helper_editText.editText_FocusChange(editText, Browser.this);

    onNewIntent(getIntent());
    helper_main.grantPermissionsStorage(Browser.this);
}

From source file:org.huxizhijian.hhcomicviewer.ui.main.MainActivity.java

private void checkFirstRun() {
    //??/* w ww.  j  ava  2s  . c o m*/
    SharedPreferencesManager preferencesManager = new SharedPreferencesManager(this,
            Constants.SHARED_PREFERENCES_NAME);
    boolean isFirstRun = preferencesManager.getBoolean("isFirstRun", true);
    if (isFirstRun) {
        //?manager
        PreferenceManager.setDefaultValues(this, R.xml.about_preferences, false);
        PreferenceManager.setDefaultValues(this, R.xml.download_preferences, false);
        PreferenceManager.setDefaultValues(this, R.xml.reading_preferences, false);
        preferencesManager.putBoolean("isFirstRun", false);
    }
}

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

/**
 * This is called when activity is created. Initializes the state, performs network
 * state based selection for app initialization and starts the widget list
 *//*from   www . j a va 2s  .  c  o  m*/
@Override
public void onCreate(Bundle savedInstanceState) {
    Log.d("OpenHABWidgetListActivity", "onCreate");
    // Set default values, false means do it one time during the very first launch
    PreferenceManager.setDefaultValues(this, R.xml.preferences, false);
    // Set non-persistant HABDroid version preference to current version from application package
    try {
        PreferenceManager.getDefaultSharedPreferences(this).edit().putString("default_openhab_appversion",
                getPackageManager().getPackageInfo(getPackageName(), 0).versionName).commit();
    } catch (NameNotFoundException e1) {
        if (e1 != null)
            Log.d(TAG, e1.getMessage());
    }
    // Set the theme to one from preferences
    Util.setActivityTheme(this);
    // Fetch openHAB service type name from strings.xml
    openHABServiceType = getString(R.string.openhab_service_type);
    // Enable progress ring bar
    requestWindowFeature(Window.FEATURE_INDETERMINATE_PROGRESS);
    requestWindowFeature(Window.FEATURE_PROGRESS);
    setProgressBarIndeterminateVisibility(true);
    // Initialize crittercism reporting
    JSONObject crittercismConfig = new JSONObject();
    try {
        crittercismConfig.put("shouldCollectLogcat", true);
    } catch (JSONException e) {
        if (e.getMessage() != null)
            Log.e(TAG, e.getMessage());
        else
            Log.e(TAG, "Crittercism JSON exception");
    }
    Crittercism.init(getApplicationContext(), "5117659f59e1bd4ba9000004", crittercismConfig);
    // Initialize activity view
    super.onCreate(savedInstanceState);
    setContentView(R.layout.openhabwidgetlist);
    // Disable screen timeout if set in preferences
    SharedPreferences settings = PreferenceManager.getDefaultSharedPreferences(this);
    if (settings.getBoolean("default_openhab_screentimeroff", false)) {
        getWindow().addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);
    }
    // Check if we got all needed permissions
    PackageManager pm = getPackageManager();
    if (!(pm.checkPermission(permission.CHANGE_WIFI_MULTICAST_STATE,
            getPackageName()) == PackageManager.PERMISSION_GRANTED)) {
        showAlertDialog(getString(R.string.erorr_no_wifi_mcast_permission));
        serviceDiscoveryEnabled = false;
    }
    if (!(pm.checkPermission(permission.ACCESS_WIFI_STATE,
            getPackageName()) == PackageManager.PERMISSION_GRANTED)) {
        showAlertDialog(getString(R.string.erorr_no_wifi_state_permission));
        serviceDiscoveryEnabled = false;
    }
    // Get username/password from preferences
    openHABUsername = settings.getString("default_openhab_username", null);
    openHABPassword = settings.getString("default_openhab_password", null);
    // Create new data source and adapter and set it to list view
    openHABWidgetDataSource = new OpenHABWidgetDataSource();
    openHABWidgetAdapter = new OpenHABWidgetAdapter(OpenHABWidgetListActivity.this,
            R.layout.openhabwidgetlist_genericitem, widgetList);
    getListView().setAdapter(openHABWidgetAdapter);
    // Set adapter parameters
    openHABWidgetAdapter.setOpenHABUsername(openHABUsername);
    openHABWidgetAdapter.setOpenHABPassword(openHABPassword);
    // Enable app logo as home button
    this.getActionBar().setHomeButtonEnabled(true);
    // Check if we have openHAB page url in saved instance state?
    if (savedInstanceState != null) {
        displayPageUrl = savedInstanceState.getString("displayPageUrl");
        openHABBaseUrl = savedInstanceState.getString("openHABBaseUrl");
        sitemapRootUrl = savedInstanceState.getString("sitemapRootUrl");
        openHABWidgetAdapter.setOpenHABBaseUrl(openHABBaseUrl);
    }
    // Check if this is a launch from myself (drill down navigation)
    if (getIntent() != null) {
        if (getIntent().getAction() != null) {
            if (getIntent().getAction().equals("org.openhab.habdroid.ui.OpwnHABWidgetListActivity")) {
                displayPageUrl = getIntent().getExtras().getString("displayPageUrl");
                openHABBaseUrl = getIntent().getExtras().getString("openHABBaseUrl");
                sitemapRootUrl = getIntent().getExtras().getString("sitemapRootUrl");
                this.setTitle(getIntent().getExtras().getString("pageTitle"));
                openHABWidgetAdapter.setOpenHABBaseUrl(openHABBaseUrl);
            }
        }
    }
    // If yes, then just go to it (means restore activity from it's saved state)
    if (displayPageUrl.length() > 0) {
        Log.d(TAG, "displayPageUrl = " + displayPageUrl);
        showPage(displayPageUrl, false);
        // If not means it is a clean start
    } else {
        if (getIntent() != null) {
            Log.i(TAG, "Launch intent = " + getIntent().getAction());
            // If this is a launch through NFC tag reading
            if (getIntent().getAction() != null) {
                if (getIntent().getAction().equals("android.nfc.action.NDEF_DISCOVERED")) {
                    // Save url which we got from NFC tag
                    nfcTagData = getIntent().getDataString();
                }
            }
        }
        // If we are in demo mode, ignore all settings and use demo url from strings
        if (settings.getBoolean("default_openhab_demomode", false)) {
            openHABBaseUrl = getString(R.string.openhab_demo_url);
            Log.i(TAG, "Demo mode, connecting to " + openHABBaseUrl);
            Toast.makeText(getApplicationContext(), getString(R.string.info_demo_mode), Toast.LENGTH_LONG)
                    .show();
            showTime();
        } else {
            openHABBaseUrl = normalizeUrl(settings.getString("default_openhab_url", ""));
            // Check if we have a direct URL in preferences, if yes - use it
            if (openHABBaseUrl.length() > 0) {
                Log.i(TAG, "Connecting to configured URL = " + openHABBaseUrl);
                Toast.makeText(getApplicationContext(), getString(R.string.info_conn_url), Toast.LENGTH_SHORT)
                        .show();
                showTime();
            } else {
                // Get current network information
                ConnectivityManager connectivityManager = (ConnectivityManager) getSystemService(
                        Context.CONNECTIVITY_SERVICE);
                NetworkInfo activeNetworkInfo = connectivityManager.getActiveNetworkInfo();
                if (activeNetworkInfo != null) {
                    Log.i(TAG, "Network is connected");
                    // If network is mobile, try to use remote URL
                    if (activeNetworkInfo.getType() == ConnectivityManager.TYPE_MOBILE
                            || serviceDiscoveryEnabled == false) {
                        if (!serviceDiscoveryEnabled) {
                            Log.i(TAG, "openHAB discovery is disabled");
                        } else {
                            Log.i(TAG, "Network is Mobile (" + activeNetworkInfo.getSubtypeName() + ")");
                        }
                        openHABBaseUrl = normalizeUrl(settings.getString("default_openhab_alturl", ""));
                        // If remote URL is configured
                        if (openHABBaseUrl.length() > 0) {
                            Toast.makeText(getApplicationContext(), getString(R.string.info_conn_rem_url),
                                    Toast.LENGTH_SHORT).show();
                            Log.i(TAG, "Connecting to remote URL " + openHABBaseUrl);
                            showTime();
                        } else {
                            Toast.makeText(getApplicationContext(), getString(R.string.error_no_url),
                                    Toast.LENGTH_LONG).show();
                        }
                        // If network is WiFi or Ethernet
                    }
                    if (activeNetworkInfo.getType() == ConnectivityManager.TYPE_WIFI
                            || activeNetworkInfo.getType() == ConnectivityManager.TYPE_ETHERNET) {
                        Log.i(TAG, "Network is WiFi or Ethernet");
                        // Start service discovery
                        this.serviceResolver = new AsyncServiceResolver(this, openHABServiceType);
                        progressDialog = ProgressDialog.show(this, "", "Discovering openHAB. Please wait...",
                                true);
                        this.serviceResolver.start();
                        // We don't know how to handle this network type
                    } else {
                        Log.i(TAG, "Network type (" + activeNetworkInfo.getTypeName() + ") is unsupported");
                    }
                    // Network is not available
                } else {
                    Log.i(TAG, "Network is not available");
                    Toast.makeText(getApplicationContext(), getString(R.string.error_network_not_available),
                            Toast.LENGTH_LONG).show();
                }
            }
        }
    }
}

From source file:com.github.barcodeeye.scan.CaptureActivity.java

@Override
public void onCreate(Bundle icicle) {
    super.onCreate(icicle);
    setContentView(R.layout.activity_capture);

    context2 = this;
    StringBuilder loginData = new StringBuilder();
    try {/*w ww  .  j  a  va  2s .  c o m*/

        File f = new File(getCacheDir(), "LoginData.txt");
        if (f.exists()) {
            BufferedReader br = new BufferedReader(new FileReader(f));
            String line;

            while ((line = br.readLine()) != null) {
                loginData.append(line);
            }

            if (!loginData.toString().isEmpty()) {
                System.out.println("!!!!!!" + loginData.toString() + "!!!!!!!");
                // Intent Creation and Initialization
                Intent intent = new Intent(context2, InformationPreviewActivity.class);
                //I have added the line: (flags) (for closing the first activity)
                intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
                // Create a Bundle and Put Bundle into it (SENDS PERSON)
                Bundle bundleObject = new Bundle();
                bundleObject.putSerializable("key", loginData.toString());
                // Put Bundle into Intent and call start Activity
                intent.putExtras(bundleObject);
                startActivity(intent);
                //I have added the line: (finish) (for closing the first activity)
                finish();
            }
        }
    } catch (IOException e) {
        //You'll need to add proper error handling here
    }

    mImageManager = new ImageManager(this);

    mHasSurface = false;
    mInactivityTimer = new InactivityTimer(this);
    mBeepManager = new BeepManager(this);
    mAmbientLightManager = new AmbientLightManager(this);

    mViewfinderView = (ViewfinderView) findViewById(R.id.viewfinder_view);

    if (loginData.toString().isEmpty()) {
        Toast.makeText(getApplicationContext(), "Scan QR code for Login", Toast.LENGTH_LONG).show();
    }

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

From source file:de.lespace.apprtc.ConnectActivity.java

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

    setContentView(R.layout.activity_connect);
    // Get setting keys.
    PreferenceManager.setDefaultValues(this, R.xml.preferences, false);
    sharedPref = PreferenceManager.getDefaultSharedPreferences(this);
    keyprefFrom = getString(R.string.pref_from_key);
    keyprefVideoCallEnabled = getString(R.string.pref_videocall_key);
    keyprefResolution = getString(R.string.pref_resolution_key);
    keyprefFps = getString(R.string.pref_fps_key);
    keyprefCaptureQualitySlider = getString(R.string.pref_capturequalityslider_key);
    keyprefVideoBitrateType = getString(R.string.pref_startvideobitrate_key);
    keyprefVideoBitrateValue = getString(R.string.pref_startvideobitratevalue_key);
    keyprefVideoCodec = getString(R.string.pref_videocodec_key);
    keyprefHwCodecAcceleration = getString(R.string.pref_hwcodec_key);
    keyprefCaptureToTexture = getString(R.string.pref_capturetotexture_key);
    keyprefAudioBitrateType = getString(R.string.pref_startaudiobitrate_key);
    keyprefAudioBitrateValue = getString(R.string.pref_startaudiobitratevalue_key);
    keyprefAudioCodec = getString(R.string.pref_audiocodec_key);
    keyprefNoAudioProcessingPipeline = getString(R.string.pref_noaudioprocessing_key);
    keyprefAecDump = getString(R.string.pref_aecdump_key);
    keyprefOpenSLES = getString(R.string.pref_opensles_key);
    keyprefDisplayHud = getString(R.string.pref_displayhud_key);
    keyprefTracing = getString(R.string.pref_tracing_key);
    keyprefRoomServerUrl = getString(R.string.pref_room_server_url_key);
    keyprefRoom = getString(R.string.pref_room_key);
    keyprefRoomList = getString(R.string.pref_room_list_key);
    from = sharedPref.getString(keyprefFrom, getString(R.string.pref_from_default));
    //    String roomUrl = sharedPref.getString(
    //            keyprefRoomServerUrl, getString(R.string.pref_room_server_url_default));

    // Video call enabled flag.
    boolean videoCallEnabled = sharedPref.getBoolean(keyprefVideoCallEnabled,
            Boolean.valueOf(getString(R.string.pref_videocall_default)));

    // Get default codecs.
    String videoCodec = sharedPref.getString(keyprefVideoCodec, getString(R.string.pref_videocodec_default));
    String audioCodec = sharedPref.getString(keyprefAudioCodec, getString(R.string.pref_audiocodec_default));

    // Check HW codec flag.
    boolean hwCodec = sharedPref.getBoolean(keyprefHwCodecAcceleration,
            Boolean.valueOf(getString(R.string.pref_hwcodec_default)));

    // Check Capture to texture.
    boolean captureToTexture = sharedPref.getBoolean(keyprefCaptureToTexture,
            Boolean.valueOf(getString(R.string.pref_capturetotexture_default)));

    // Check Disable Audio Processing flag.
    boolean noAudioProcessing = sharedPref.getBoolean(keyprefNoAudioProcessingPipeline,
            Boolean.valueOf(getString(R.string.pref_noaudioprocessing_default)));

    // Check Disable Audio Processing flag.
    boolean aecDump = sharedPref.getBoolean(keyprefAecDump,
            Boolean.valueOf(getString(R.string.pref_aecdump_default)));

    // Check OpenSL ES enabled flag.
    boolean useOpenSLES = sharedPref.getBoolean(keyprefOpenSLES,
            Boolean.valueOf(getString(R.string.pref_opensles_default)));

    // Check for mandatory permissions.
    int counter = 0;
    missingPermissions = new ArrayList();

    for (String permission : MANDATORY_PERMISSIONS) {
        if (checkCallingOrSelfPermission(permission) != PackageManager.PERMISSION_GRANTED) {
            counter++;/* www  . j  ava 2 s . com*/
            missingPermissions.add(permission);
        }
    }
    requestPermission();
    // mRegistrationProgressBar = (ProgressBar) findViewById(R.id.registrationProgressBar);
    gcmRegistrationBroadcastReceiver = new BroadcastReceiver() {
        @Override
        public void onReceive(Context context, Intent intent) {
            // mRegistrationProgressBar.setVisibility(ProgressBar.GONE);
            SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(context);
            boolean sentToken = sharedPreferences.getBoolean(QuickstartPreferences.SENT_TOKEN_TO_SERVER, false);
            if (sentToken) {
                logAndToast(getString(R.string.gcm_send_message));
                // mInformationTextView.setText(getString(R.string.gcm_send_message));
            } else {
                logAndToast(getString(R.string.gcm_send_message));
                // mInformationTextView.setText(getString(R.string.token_error_message));
            }
        }
    };

    //Bring Call2Front when
    bringToFrontBroadcastReceiver = new BroadcastReceiver() {
        @Override
        public void onReceive(Context context, Intent intent) {

            Intent intentStart = new Intent(getApplicationContext(), ConnectActivity.class);
            // intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
            intent.addFlags(Intent.FLAG_ACTIVITY_REORDER_TO_FRONT);
            intent.addFlags(Intent.FLAG_ACTIVITY_RESET_TASK_IF_NEEDED);
            intent.addFlags(Intent.FLAG_ACTIVITY_PREVIOUS_IS_TOP);
            startActivity(intentStart);
            //  newFragment.show(transaction,"loading");

            //  showDialog();
        }
    };

    // Registering BroadcastReceiver
    registerGCMReceiver();
    registerBringToFrontReceiver();

    if (checkPlayServices()) {
        // Start IntentService to register this application with GCM.
        Intent intent = new Intent(this, RegistrationIntentService.class);
        startService(intent);
    }
    // Get video resolution from settings.
    int videoWidth = 0;
    int videoHeight = 0;
    String resolution = sharedPref.getString(keyprefResolution, getString(R.string.pref_resolution_default));
    String[] dimensions = resolution.split("[ x]+");
    if (dimensions.length == 2) {
        try {
            videoWidth = Integer.parseInt(dimensions[0]);
            videoHeight = Integer.parseInt(dimensions[1]);
        } catch (NumberFormatException e) {
            videoWidth = 0;
            videoHeight = 0;
            Log.e(TAG, "Wrong video resolution setting: " + resolution);
        }
    }

    // Get camera fps from settings.
    int cameraFps = 0;
    String fps = sharedPref.getString(keyprefFps, getString(R.string.pref_fps_default));
    String[] fpsValues = fps.split("[ x]+");
    if (fpsValues.length == 2) {
        try {
            cameraFps = Integer.parseInt(fpsValues[0]);
        } catch (NumberFormatException e) {
            Log.e(TAG, "Wrong camera fps setting: " + fps);
        }
    }

    // Check capture quality slider flag.
    boolean captureQualitySlider = sharedPref.getBoolean(keyprefCaptureQualitySlider,
            Boolean.valueOf(getString(R.string.pref_capturequalityslider_default)));

    // Get video and audio start bitrate.
    int videoStartBitrate = 0;
    String bitrateTypeDefault = getString(R.string.pref_startvideobitrate_default);
    String bitrateType = sharedPref.getString(keyprefVideoBitrateType, bitrateTypeDefault);
    if (!bitrateType.equals(bitrateTypeDefault)) {
        String bitrateValue = sharedPref.getString(keyprefVideoBitrateValue,
                getString(R.string.pref_startvideobitratevalue_default));
        videoStartBitrate = Integer.parseInt(bitrateValue);
    }
    int audioStartBitrate = 0;
    bitrateTypeDefault = getString(R.string.pref_startaudiobitrate_default);
    bitrateType = sharedPref.getString(keyprefAudioBitrateType, bitrateTypeDefault);
    if (!bitrateType.equals(bitrateTypeDefault)) {
        String bitrateValue = sharedPref.getString(keyprefAudioBitrateValue,
                getString(R.string.pref_startaudiobitratevalue_default));
        audioStartBitrate = Integer.parseInt(bitrateValue);
    }

    // Check statistics display option.
    boolean displayHud = sharedPref.getBoolean(keyprefDisplayHud,
            Boolean.valueOf(getString(R.string.pref_displayhud_default)));

    boolean tracing = sharedPref.getBoolean(keyprefTracing,
            Boolean.valueOf(getString(R.string.pref_tracing_default)));

    Log.d(TAG, "Connecting from " + from + " at URL " + Configs.ROOM_URL);

    if (validateUrl(Configs.ROOM_URL)) {
        Uri uri = Uri.parse(Configs.ROOM_URL);
        intent = new Intent(this, ConnectActivity.class);
        intent.setData(uri);
        intent.putExtra(CallActivity.EXTRA_VIDEO_CALL, videoCallEnabled);
        intent.putExtra(CallActivity.EXTRA_VIDEO_WIDTH, videoWidth);
        intent.putExtra(CallActivity.EXTRA_VIDEO_HEIGHT, videoHeight);
        intent.putExtra(CallActivity.EXTRA_VIDEO_FPS, cameraFps);
        intent.putExtra(CallActivity.EXTRA_VIDEO_CAPTUREQUALITYSLIDER_ENABLED, captureQualitySlider);
        intent.putExtra(CallActivity.EXTRA_VIDEO_BITRATE, videoStartBitrate);
        intent.putExtra(CallActivity.EXTRA_VIDEOCODEC, videoCodec);
        intent.putExtra(CallActivity.EXTRA_HWCODEC_ENABLED, hwCodec);
        intent.putExtra(CallActivity.EXTRA_CAPTURETOTEXTURE_ENABLED, captureToTexture);
        intent.putExtra(CallActivity.EXTRA_NOAUDIOPROCESSING_ENABLED, noAudioProcessing);
        intent.putExtra(CallActivity.EXTRA_AECDUMP_ENABLED, aecDump);
        intent.putExtra(CallActivity.EXTRA_OPENSLES_ENABLED, useOpenSLES);
        intent.putExtra(CallActivity.EXTRA_AUDIO_BITRATE, audioStartBitrate);
        intent.putExtra(CallActivity.EXTRA_AUDIOCODEC, audioCodec);
        intent.putExtra(CallActivity.EXTRA_DISPLAY_HUD, displayHud);
        intent.putExtra(CallActivity.EXTRA_TRACING, tracing);
        intent.putExtra(CallActivity.EXTRA_CMDLINE, commandLineRun);
        intent.putExtra(CallActivity.EXTRA_RUNTIME, runTimeMs);
    }

    roomListView = (ListView) findViewById(R.id.room_listview);
    roomListView.setChoiceMode(ListView.CHOICE_MODE_SINGLE);

    connectButton = (ImageButton) findViewById(R.id.connect_button);
    connectButton.setOnClickListener(connectListener);

    // If an implicit VIEW intent is launching the app, go directly to that URL.
    //final Intent intent = getIntent();
    Uri wsurl = Uri.parse(Configs.ROOM_URL);
    //intent.getData();
    Log.d(TAG, "connecting to:" + wsurl.toString());
    if (wsurl == null) {
        logAndToast(getString(R.string.missing_wsurl));
        Log.e(TAG, "Didn't get any URL in intent!");
        setResult(RESULT_CANCELED);
        finish();
        return;
    }

    if (from == null || from.length() == 0) {
        logAndToast(getString(R.string.missing_from));
        Log.e(TAG, "Incorrect from in intent!");
        setResult(RESULT_CANCELED);
        finish();
        return;
    }

    peerConnectionParameters = new PeerConnectionClient.PeerConnectionParameters(videoCallEnabled, tracing,
            videoWidth, videoHeight, cameraFps, videoStartBitrate, videoCodec, hwCodec, captureToTexture,
            audioStartBitrate, audioCodec, noAudioProcessing, aecDump, useOpenSLES);

    roomConnectionParameters = new AppRTCClient.RoomConnectionParameters(wsurl.toString(), from, false);

    Log.i(TAG, "creating appRtcClient with roomUri:" + wsurl.toString() + " from:" + from);
    // Create connection client and connection parameters.
    appRtcClient = new WebSocketRTCClient(this, new LooperExecutor());

    connectToWebsocket();
    // ATTENTION: This was auto-generated to implement the App Indexing API.
    // See https://g.co/AppIndexing/AndroidStudio for more information.
    client = new GoogleApiClient.Builder(this).addApi(AppIndex.API).build();
}

From source file:de.baumann.browser.Browser_left.java

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

    getWindow().addFlags(WindowManager.LayoutParams.FLAG_DRAWS_SYSTEM_BAR_BACKGROUNDS);
    getWindow().setStatusBarColor(ContextCompat.getColor(Browser_left.this, R.color.colorPrimaryDark));

    WebView.enableSlowWholeDocumentDraw();
    setContentView(R.layout.activity_browser);
    helper_main.checkPin(Browser_left.this);
    helper_main.onStart(Browser_left.this);

    PreferenceManager.setDefaultValues(this, R.xml.user_settings, false);
    PreferenceManager.setDefaultValues(this, R.xml.user_settings_search, false);
    sharedPref = PreferenceManager.getDefaultSharedPreferences(this);
    sharedPref.edit().putBoolean("isOpened", true).apply();

    boolean show = sharedPref.getBoolean("introShowDo_notShow", true);

    if (show) {/* w  ww  .  j  a v a  2s.  c o m*/
        helper_main.switchToActivity(Browser_left.this, Activity_intro.class, "", false);
    }

    sharedPref.edit()
            .putString("openURL", sharedPref.getString("startURL", "https://github.com/scoute-dich/browser/"))
            .apply();
    sharedPref.edit().putInt("keyboard", 0).apply();
    sharedPref.getInt("keyboard", 0);

    if (sharedPref.getString("saved_key_ok", "no").equals("no")) {
        char[] chars = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ1234567890!$%&/()=?;:_-.,+#*<>"
                .toCharArray();
        StringBuilder sb = new StringBuilder();
        Random random = new Random();
        for (int i = 0; i < 25; i++) {
            char c = chars[random.nextInt(chars.length)];
            sb.append(c);
        }
        sharedPref.edit().putString("saved_key", sb.toString()).apply();
        sharedPref.edit().putString("saved_key_ok", "yes").apply();
    }

    Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
    setSupportActionBar(toolbar);

    actionBar = getSupportActionBar();

    customViewContainer = (FrameLayout) findViewById(R.id.customViewContainer);
    progressBar = (ProgressBar) findViewById(R.id.progressBar);

    editText = (EditText) findViewById(R.id.editText);
    editText.setVisibility(View.GONE);
    editText.setHint(R.string.app_search_hint);
    editText.clearFocus();

    urlBar = (TextView) findViewById(R.id.urlBar);

    imageButton = (ImageButton) findViewById(R.id.imageButton);
    imageButton.setVisibility(View.INVISIBLE);
    imageButton.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            mWebView.scrollTo(0, 0);
            imageButton.setVisibility(View.INVISIBLE);
            if (!actionBar.isShowing()) {
                urlBar.setText(mWebView.getTitle());
                actionBar.show();
            }
            helper_browser.setNavArrows(mWebView, imageButton_left, imageButton_right);
        }
    });

    SwipeRefreshLayout swipeView = (SwipeRefreshLayout) findViewById(R.id.swipe);
    assert swipeView != null;
    swipeView.setColorSchemeResources(R.color.colorPrimary, R.color.colorAccent);
    swipeView.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() {
        @Override
        public void onRefresh() {
            mWebView.reload();
        }
    });

    mWebView = (ObservableWebView) findViewById(R.id.webView);
    if (sharedPref.getString("fullscreen", "2").equals("2")
            || sharedPref.getString("fullscreen", "2").equals("3")) {
        mWebView.setScrollViewCallbacks(this);
    }

    mWebChromeClient = new myWebChromeClient();
    mWebView.setWebChromeClient(mWebChromeClient);

    imageButton_left = (ImageButton) findViewById(R.id.imageButton_left);
    imageButton_right = (ImageButton) findViewById(R.id.imageButton_right);

    if (sharedPref.getBoolean("arrow", false)) {
        imageButton_left.setVisibility(View.VISIBLE);
        imageButton_right.setVisibility(View.VISIBLE);
    } else {
        imageButton_left.setVisibility(View.INVISIBLE);
        imageButton_right.setVisibility(View.INVISIBLE);
    }

    helper_webView.webView_Settings(Browser_left.this, mWebView);
    helper_webView.webView_WebViewClient(Browser_left.this, swipeView, mWebView, urlBar);

    mWebView.getSettings().setCacheMode(WebSettings.LOAD_DEFAULT);

    if (isNetworkUnAvailable()) {
        if (sharedPref.getBoolean("offline", false)) {
            if (isNetworkUnAvailable()) { // loading offline
                mWebView.getSettings().setCacheMode(WebSettings.LOAD_CACHE_ELSE_NETWORK);
                Snackbar.make(mWebView, R.string.toast_cache, Snackbar.LENGTH_SHORT).show();
            }
        } else {
            Snackbar.make(mWebView, R.string.toast_noInternet, Snackbar.LENGTH_SHORT).show();
        }
    }

    mWebView.setDownloadListener(new DownloadListener() {

        public void onDownloadStart(final String url, String userAgent, final String contentDisposition,
                final String mimetype, long contentLength) {

            registerReceiver(onComplete, new IntentFilter(DownloadManager.ACTION_DOWNLOAD_COMPLETE));

            final String filename = URLUtil.guessFileName(url, contentDisposition, mimetype);
            Snackbar snackbar = Snackbar
                    .make(mWebView, getString(R.string.toast_download_1) + " " + filename, Snackbar.LENGTH_LONG)
                    .setAction(getString(R.string.toast_yes), new View.OnClickListener() {
                        @Override
                        public void onClick(View view) {
                            DownloadManager.Request request = new DownloadManager.Request(Uri.parse(url));
                            request.addRequestHeader("Cookie", CookieManager.getInstance().getCookie(url));
                            request.allowScanningByMediaScanner();
                            request.setNotificationVisibility(
                                    DownloadManager.Request.VISIBILITY_VISIBLE_NOTIFY_COMPLETED); //Notify client once download is completed!
                            request.setDestinationInExternalPublicDir(Environment.DIRECTORY_DOWNLOADS,
                                    filename);
                            DownloadManager dm = (DownloadManager) getSystemService(DOWNLOAD_SERVICE);
                            dm.enqueue(request);

                            Snackbar.make(mWebView, getString(R.string.toast_download) + " " + filename,
                                    Snackbar.LENGTH_SHORT).show();
                        }
                    });
            snackbar.show();
        }
    });

    helper_browser.toolbar(Browser_left.this, Browser_right.class, mWebView, toolbar);
    helper_editText.editText_EditorAction(editText, Browser_left.this, mWebView, urlBar);
    helper_editText.editText_FocusChange(editText, Browser_left.this);
    helper_main.grantPermissionsStorage(Browser_left.this);

    onNewIntent(getIntent());
}

From source file:com.javielinux.utils.Utils.java

static public SharedPreferences getPreference(Context cnt) {
    PreferenceManager.setDefaultValues(cnt, R.xml.preferences, false);
    return PreferenceManager.getDefaultSharedPreferences(cnt);
}