List of usage examples for android.preference PreferenceManager setDefaultValues
public static void setDefaultValues(Context context, @XmlRes int resId, boolean readAgain)
From source file:com.kncwallet.wallet.ui.WalletActivity.java
@Override protected void onResume() { super.onResume(); //load up the default prefs in case this is first run PreferenceManager.setDefaultValues(this, R.xml.preferences, false); getWalletApplication().startBlockchainService(true); checkLowStorageAlert();/*from ww w .j a v a2 s.co m*/ checkPin(); new ContactsDownloader(this, prefs, application.GetPhoneNumber(), new ContactsDownloader.ContactsDownloaderListener() { @Override public void onSuccess(int newContacts) { if (newContacts > 0) Toast.makeText(getBaseContext(), getString(R.string.contacts_lookup_contacts_added, "" + newContacts), Toast.LENGTH_SHORT).show(); } @Override public void onError(String message) { Toast.makeText(getBaseContext(), message, Toast.LENGTH_SHORT).show(); } }).checkContactsLookup(); }
From source file:edu.mit.viral.shen.DroidFish.java
/** Called when the activity is first created. */ @Override// w w w .j av a2 s . c o m public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); game_number = getIntent().getExtras().getInt("game_id", 0); // sendGame(); Pair<String, String> pair = getPgnOrFenIntent(); String intentPgnOrFen = pair.first; String intentFilename = pair.second; createDirectories(); PreferenceManager.setDefaultValues(this, R.xml.preferences, false); settings = PreferenceManager.getDefaultSharedPreferences(this); settings.registerOnSharedPreferenceChangeListener(new OnSharedPreferenceChangeListener() { @Override public void onSharedPreferenceChanged(SharedPreferences sharedPreferences, String key) { handlePrefsChange(); } }); PowerManager pm = (PowerManager) getSystemService(Context.POWER_SERVICE); setWakeLock(false); wakeLock = pm.newWakeLock(PowerManager.SCREEN_BRIGHT_WAKE_LOCK, "droidfish"); wakeLock.setReferenceCounted(false); custom1ButtonActions = new ButtonActions("custom1", CUSTOM1_BUTTON_DIALOG, R.string.select_action); custom2ButtonActions = new ButtonActions("custom2", CUSTOM2_BUTTON_DIALOG, R.string.select_action); custom3ButtonActions = new ButtonActions("custom3", CUSTOM3_BUTTON_DIALOG, R.string.select_action); figNotation = Typeface.createFromAsset(getAssets(), "fonts/DroidFishChessNotationDark.otf"); setPieceNames(PGNOptions.PT_LOCAL); requestWindowFeature(Window.FEATURE_NO_TITLE); initUI(); gameTextListener = new PgnScreenText(pgnOptions); if (ctrl != null) ctrl.shutdownEngine(); ctrl = new DroidChessController(this, gameTextListener, pgnOptions); egtbForceReload = true; readPrefs(); TimeControlData tcData = new TimeControlData(); mDatabase = new SudokuDatabase(getApplicationContext()); game_id = Long.valueOf(game_number); ctrl = mDatabase.getSudoku(ctrl, game_id); startPosition = ctrl.getData(); tcData.setTimeControl(timeControl, movesPerSession, timeIncrement); int version = 1; version = settings.getInt("gameStateVersion", version); // System.out.println("this is the version" + version); ctrl.newGame(gameMode, tcData); if (game_number >= 37 && (startPosition.equals("8/8/8/8/8/8/8/8 w - - 0 1") | startPosition.equals("8/8/8/8/8/8/8/8 w KQkq - 0 1"))) { // System.out.println("greater than 37"); startEditBoard("8/8/8/8/8/8/8/8 w KQkq - 0 1"); } if (ctrl.getState() == DroidChessController.GAME_STATE_NOT_STARTED) { ctrl.start(); System.out.println("GAME_STATE_NOT_STARTED"); } else if (ctrl.getState() == DroidChessController.GAME_STATE_PLAYING) { System.out.println("GAME_STATE_PLAYING"); String dataStr = ctrl.getNote(); // System.out.println(ctrl.getNote()); byte[] data = strToByteArr(dataStr); // ctrl.newGame(gameMode, tcData, "8/8/8/8/8/8/8/8 w KQkq - 0 1"); ctrl.fromByteArray(data, 3); } ctrl.setGuiPaused(true); ctrl.setGuiPaused(false); ctrl.startGame(); if (intentPgnOrFen != null) { try { ctrl.setFENOrPGN(intentPgnOrFen); setBoardFlip(true); } catch (ChessParseError e) { // If FEN corresponds to illegal chess position, go into edit board mode. try { TextIO.readFEN(intentPgnOrFen); } catch (ChessParseError e2) { if (e2.pos != null) startEditBoard(intentPgnOrFen); } } } else if (intentFilename != null) { if (intentFilename.toLowerCase(Locale.US).endsWith(".fen") || intentFilename.toLowerCase(Locale.US).endsWith(".epd")) loadFENFromFile(intentFilename); else loadPGNFromFile(intentFilename); } // commented out 04/12/15 // sendDataone(startPosition, 1); utils = new Utils(getApplicationContext()); client = new WebSocketClient(URI.create(Const.URL_WEBSOCKET + URLEncoder.encode(name)), new WebSocketClient.Listener() { @Override public void onConnect() { } /** * On receiving the message from web socket server * */ @Override public void onMessage(String message) { Log.d(TAG, String.format("Got string message! %s", message)); parseMessage(message); } @Override public void onMessage(byte[] data) { Log.d(TAG, String.format("Got binary message! %s", bytesToHex(data))); parseMessage(bytesToHex(data)); // Message will be in JSON format } /** * Called when the connection is terminated * */ @Override public void onDisconnect(int code, String reason) { String message = String.format(Locale.US, "Disconnected! Code: %d Reason: %s", code, reason); // showToast(message); // clear the session id from shared preferences utils.storeSessionId(null); } @Override public void onError(Exception error) { Log.e(TAG, "Error! : " + error); } }, null); client.connect(); }
From source file:at.alladin.rmbt.android.main.RMBTMainActivity.java
/** * *//*from w ww. j a v a2 s . c om*/ @Override public void onCreate(final Bundle savedInstanceState) { //Log.i("MAIN ACTIVITY", "onCreate"); restoreInstance(savedInstanceState); super.onCreate(savedInstanceState); NetworkInfoCollector.init(this); networkInfoCollector = NetworkInfoCollector.getInstance(); preferencesUpdate(); setContentView(R.layout.main_with_navigation_drawer); if (VIEW_HIERARCHY_SERVER_ENABLED) { ViewServer.get(this).addWindow(this); } ActionBar actionBar = getActionBar(); actionBar.setDisplayOptions(ActionBar.DISPLAY_SHOW_HOME | ActionBar.DISPLAY_SHOW_TITLE); actionBar.setDisplayUseLogoEnabled(true); // initialize the navigation drawer with the main menu list adapter: String[] mainTitles = getResources().getStringArray(R.array.navigation_main_titles); int[] navIcons = new int[] { R.drawable.ic_action_home, R.drawable.ic_action_history, R.drawable.ic_action_map, R.drawable.ic_action_stat, R.drawable.ic_action_help, R.drawable.ic_action_about, R.drawable.ic_action_settings, R.drawable.ic_action_about }; MainMenuListAdapter mainMenuAdapter = new MainMenuListAdapter(this, mainTitles, navIcons); drawerLayout = (DrawerLayout) findViewById(R.id.drawer_layout); drawerList = (ListView) findViewById(R.id.left_drawer); drawerLayout.setBackgroundResource(R.drawable.ic_drawer); drawerToggle = new ActionBarDrawerToggle(this, drawerLayout, R.drawable.ic_drawer, R.string.page_title_title_page, R.string.page_title_title_page) { /** Called when a drawer has settled in a completely closed state. */ public void onDrawerClosed(View view) { super.onDrawerClosed(view); //refreshActionBar(null); exitAfterDrawerClose = false; } /** Called when a drawer has settled in a completely open state. */ public void onDrawerOpened(View drawerView) { super.onDrawerOpened(drawerView); } }; drawerLayout.setOnKeyListener(new OnKeyListener() { @Override public boolean onKey(View v, int keyCode, KeyEvent event) { if (KeyEvent.KEYCODE_BACK == event.getKeyCode() && exitAfterDrawerClose) { onBackPressed(); return true; } return false; } }); drawerLayout.setDrawerListener(drawerToggle); drawerList.setAdapter(mainMenuAdapter); drawerList.setOnItemClickListener(new OnItemClickListener() { final int[] menuIds = new int[] { R.id.action_title_page, R.id.action_history, R.id.action_map, R.id.action_stats, R.id.action_help, R.id.action_info, R.id.action_settings, R.id.action_netstat, R.id.action_log }; @Override public void onItemClick(AdapterView<?> parent, View view, int position, long id) { selectMenuItem(menuIds[position]); drawerLayout.closeDrawers(); } }); actionBar.setDisplayHomeAsUpEnabled(true); actionBar.setHomeButtonEnabled(true); // Do something against banding effect in gradients // Dither flag might mess up on certain devices?? final Window window = getWindow(); window.setFormat(PixelFormat.RGBA_8888); window.addFlags(WindowManager.LayoutParams.FLAG_DITHER); // Setzt Default-Werte, wenn noch keine Werte vorhanden PreferenceManager.setDefaultValues(this, R.xml.preferences, false); final String uuid = ConfigHelper.getUUID(getApplicationContext()); fm = getFragmentManager(); final Fragment fragment = fm.findFragmentById(R.id.fragment_content); if (!ConfigHelper.isTCAccepted(this)) { if (fragment != null && fm.getBackStackEntryCount() >= 1) // clear fragment back stack fm.popBackStack(fm.getBackStackEntryAt(0).getId(), FragmentManager.POP_BACK_STACK_INCLUSIVE); getActionBar().hide(); setLockNavigationDrawer(true); showTermsCheck(); } else { currentMapOptions.put("highlight", uuid); if (fragment == null) { if (false) // deactivated for si // ! ConfigHelper.isNDTDecisionMade(this)) { showTermsCheck(); showNdtCheck(); } else initApp(true); } } geoLocation = new MainGeoLocation(getApplicationContext()); mNetworkStateChangedFilter = new IntentFilter(); mNetworkStateChangedFilter.addAction(ConnectivityManager.CONNECTIVITY_ACTION); mNetworkStateIntentReceiver = new BroadcastReceiver() { @Override public void onReceive(final Context context, final Intent intent) { if (intent.getAction().equals(ConnectivityManager.CONNECTIVITY_ACTION)) { final boolean connected = !intent.getBooleanExtra(ConnectivityManager.EXTRA_NO_CONNECTIVITY, false); final boolean isFailover = intent.getBooleanExtra(ConnectivityManager.EXTRA_IS_FAILOVER, false); if (connected) { if (networkInfoCollector != null) { networkInfoCollector.setHasConnectionFromAndroidApi(true); } } else { if (networkInfoCollector != null) { networkInfoCollector.setHasConnectionFromAndroidApi(false); } } Log.i(DEBUG_TAG, "CONNECTED: " + connected + " FAILOVER: " + isFailover); } } }; }
From source file:org.mdc.chess.MDChess.java
/** * Called when the activity is first created. *///w w w . j a v a 2 s.c om @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); Pair<String, String> pair = getPgnOrFenIntent(); String intentPgnOrFen = pair.first; String intentFilename = pair.second; createDirectories(); PreferenceManager.setDefaultValues(this, R.xml.preferences, false); settings = PreferenceManager.getDefaultSharedPreferences(this); setWakeLock(false); figNotation = Typeface.createFromAsset(getAssets(), "fonts/KlinicSlabBold.otf"); setPieceNames(PGNOptions.PT_LOCAL); initUI(); gameTextListener = new PgnScreenText(pgnOptions); moveList.setOnLinkClickListener(gameTextListener); moveList.setBackgroundColor(Color.WHITE); if (ctrl != null) { ctrl.shutdownEngine(); } ctrl = new MDChessController(this, gameTextListener, pgnOptions); egtbForceReload = true; readPrefs(); TimeControlData tcData = new TimeControlData(); tcData.setTimeControl(timeControl, movesPerSession, timeIncrement); ctrl.newGame(gameMode, tcData); setAutoMode(AutoMode.OFF); { byte[] data = null; int version = 1; if (savedInstanceState != null) { data = savedInstanceState.getByteArray("gameState"); version = savedInstanceState.getInt("gameStateVersion", version); } else { String dataStr = settings.getString("gameState", null); version = settings.getInt("gameStateVersion", version); if (dataStr != null) { data = strToByteArr(dataStr); } } if (data != null) { ctrl.fromByteArray(data, version); } } ctrl.setGuiPaused(true); ctrl.setGuiPaused(false); ctrl.startGame(); if (intentPgnOrFen != null) { try { ctrl.setFENOrPGN(intentPgnOrFen); setBoardFlip(true); } catch (ChessParseError e) { // If FEN corresponds to illegal chess position, go into edit board mode. try { TextIO.readFEN(intentPgnOrFen); } catch (ChessParseError e2) { if (e2.pos != null) { startEditBoard(intentPgnOrFen); } } } } else if (intentFilename != null) { if (intentFilename.toLowerCase(Locale.US).endsWith(".fen") || intentFilename.toLowerCase(Locale.US).endsWith(".epd")) { loadFENFromFile(intentFilename); } else { loadPGNFromFile(intentFilename); } } }
From source file:io.github.data4all.activity.MapViewActivity.java
private void bodyheightdialog() { PreferenceManager.setDefaultValues(this, R.xml.settings, false); this.prefs = PreferenceManager.getDefaultSharedPreferences(this); final SharedPreferences userPrefs = getSharedPreferences("UserPrefs", 0); firstUse = userPrefs.getBoolean("firstUse", true); if (firstUse) { RelativeLayout linearLayout = new RelativeLayout(this); final NumberPicker numberPicker = new NumberPicker(this); numberPicker.setMaxValue(250);// w ww . j av a 2 s .c o m numberPicker.setMinValue(80); numberPicker.setValue(180); RelativeLayout.LayoutParams params = new RelativeLayout.LayoutParams(50, 50); RelativeLayout.LayoutParams numPicerParams = new RelativeLayout.LayoutParams( RelativeLayout.LayoutParams.WRAP_CONTENT, RelativeLayout.LayoutParams.WRAP_CONTENT); numPicerParams.addRule(RelativeLayout.CENTER_HORIZONTAL); linearLayout.setLayoutParams(params); linearLayout.addView(numberPicker, numPicerParams); AlertDialog.Builder alertDialogBuilder = new AlertDialog.Builder(this); alertDialogBuilder.setTitle(R.string.pref_bodyheight_dialog_title); alertDialogBuilder.setMessage(R.string.pref_bodyheight_dialog_message); alertDialogBuilder.setView(linearLayout); alertDialogBuilder.setCancelable(false).setPositiveButton(R.string.ok, new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int id) { Log.d(TAG, "set bodyheight to: " + numberPicker.getValue()); prefs.edit().putString("PREF_BODY_HEIGHT", String.valueOf(numberPicker.getValue())) .commit(); } }); AlertDialog alertDialog = alertDialogBuilder.create(); alertDialog.show(); // set firstUse to false so this dialog is not shown again. ever. userPrefs.edit().putBoolean("firstUse", false).commit(); firstUse = false; } }
From source file:uni.oulu.mentor.TeacherVisionActivity.java
@Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); //DO NOT USE THIS SERVICE YET, DOES NOT WORK //Intent intent = new Intent(this, TeacherVisionService.class); //startService(intent); /*Idea from http://stackoverflow.com/questions/2902640/android-get-the-screen-resolution-pixels-as-integer-values */ @SuppressWarnings("deprecation") int screenWidthPix = getWindowManager().getDefaultDisplay().getWidth(); @SuppressWarnings("deprecation") int screenHeightPix = getWindowManager().getDefaultDisplay().getHeight(); /*Idea from http://stackoverflow.com/questions/5015094/determine-device-screen-category-small-normal-large-xlarge-using-code*/ if ((getResources().getConfiguration().screenLayout & Configuration.SCREENLAYOUT_SIZE_MASK) == Configuration.SCREENLAYOUT_SIZE_LARGE) screenType = 3;/* w ww .j a v a 2 s . c o m*/ else if ((getResources().getConfiguration().screenLayout & Configuration.SCREENLAYOUT_SIZE_MASK) == Configuration.SCREENLAYOUT_SIZE_XLARGE) screenType = 4; else if ((getResources().getConfiguration().screenLayout & Configuration.SCREENLAYOUT_SIZE_MASK) == Configuration.SCREENLAYOUT_SIZE_SMALL) screenType = 1; else if ((getResources().getConfiguration().screenLayout & Configuration.SCREENLAYOUT_SIZE_MASK) == Configuration.SCREENLAYOUT_SIZE_NORMAL) screenType = 2; //screen density is investigated here DisplayMetrics metrics = new DisplayMetrics(); getWindowManager().getDefaultDisplay().getMetrics(metrics); int density = metrics.densityDpi; if (density == DisplayMetrics.DENSITY_HIGH) { //400 dpi is 600px if (screenType == 1) translationX = 240; //240 / 1.5 = 160 else if (screenType == 2) translationX = 315; //315 / 1.5 = 210 in dpi, screen 800 pix wide screen, needs about 1024/400 = 800/x => 312,5, 2.56 else if (screenType == 3) translationX = 540; //540 / 1.5 = 360 in dpi else if (screenType == 4) translationX = 600; //600 / 1.5 = 400 in dpi } else if (density == DisplayMetrics.DENSITY_MEDIUM) { //400 dpi is 400px if (screenType == 1) translationX = 160; //160 / 1 = 160 in dpi else if (screenType == 2) translationX = 210; //210 / 1 = 210 in dpi else if (screenType == 3) translationX = 360; //360 / 1 = 360 in dpi else if (screenType == 4) translationX = 400; //400 / 1 = 400 in dpi } else if (density == DisplayMetrics.DENSITY_LOW) { //400 dpi is 300px if (screenType == 1) translationX = 120; //120 / 0.75 = 160 in dpi else if (screenType == 2) translationX = 158; //158 / 0.75 = 210 in dpi else if (screenType == 3) translationX = 270; //270 / 0.75 = 360 in dpi else if (screenType == 4) translationX = 300; //300 / 0.75 = 400 in dpi } else if (density == DisplayMetrics.DENSITY_XHIGH || density == DisplayMetrics.DENSITY_XXHIGH) { //400 dpi is 800px if (screenType == 1) translationX = 320; //320 / 2 = 160 in dpi else if (screenType == 2) translationX = 420; // 420 / 2 = 210 in dpi else if (screenType == 3) translationX = 720; // 720 / 2 = 360 in dpi else if (screenType == 4) translationX = 800; // 800 / 2 = 400 in dpi } else { //not supported } int offsetX = ((int) screenWidthPix / 20); int offsetY = ((int) screenHeightPix / 10); maxPosOpenX = screenWidthPix; //boundary for minimum amount of width on x-axis, where the touch is seen as panel open touch minPosOpenX = screenWidthPix - offsetX; //boundary for maximum amount of width on x-axis, where the touch is seen as panel close touch maxPosCloseX = screenWidthPix - translationX + offsetX; //boundary for minimum amount of width on x-axis, where the touch is seen as panel close touch minPosCloseX = screenWidthPix - translationX - offsetX; //boundary for maximum amount of height on y-axis, where the touch is seen as panel open or close touch maxPosY = (screenHeightPix / 2) + offsetY; //boundary for minimum amount of height on y-axis, where the touch is seen as panel open or close touch minPosY = (screenHeightPix / 2) - offsetY; //instantiation of lists onlineStudentsList = new ArrayList<Student>(); feedbacksList = new ArrayList<Feedback>(); questionsList = new ArrayList<Question>(); answersList = new ArrayList<Answer>(); ownQuestionsList = new ArrayList<Question>(); //data stored for this user is fetched here, from the previous activity, and stored into the teacher instance Intent intent2 = getIntent(); teacher = (Teacher) intent2.getParcelableExtra("teacherObj"); ipStr = getResources().getString(R.string.IP); usersUrl = "http://" + ipStr + "/mentor/users"; coursesUrl = "http://" + ipStr + "/mentor/courses"; //default preferences are fetched, and listener is set to listen for preference changes PreferenceManager.setDefaultValues(this, R.xml.preferences, false); sp = PreferenceManager.getDefaultSharedPreferences(getApplicationContext()); sp.registerOnSharedPreferenceChangeListener(this); //SharedPreferences.Editor editor = sp.edit(); //editor.putString("flaretimePref", "5"); //editor.clear(); //editor.commit(); // In case of notifications are added later /*String ns = Context.NOTIFICATION_SERVICE; mNotificationManager = (NotificationManager) getSystemService(ns); icon = R.drawable.mlogo2;*/ //AndAR preview renderer = new CustomRenderer();//optional, may be set to null super.setNonARRenderer(renderer);//or might be omitted try { //register an object for each marker type artoolkit = super.getArtoolkit(); oneObject = new CustomObject("onePatt", "onePatt.patt", 80.0, new double[] { 0, 0 }); //name, pattern, markerWidth, markerCenter, customColor twoObject = new CustomObject("twoPatt", "twoPatt.patt", 80.0, new double[] { 0, 0 }); //name, pattern, markerWidth, markerCenter threeObject = new CustomObject("threePatt", "threePatt.patt", 80.0, new double[] { 0, 0 }); //name, pattern, markerWidth, markerCenter artoolkit.registerARObject(oneObject); artoolkit.registerARObject(twoObject); artoolkit.registerARObject(threeObject); } catch (AndARException ex) { Log.e("AndARException ", ex.getMessage()); } LayoutInflater inflater = (LayoutInflater) getSystemService(Context.LAYOUT_INFLATER_SERVICE); View vv = inflater.inflate(R.layout.activity_teacher_vision, null); //screen width and height in pixels screenWidth = (float) this.getApplicationContext().getResources().getDisplayMetrics().widthPixels; screenHeight = (float) this.getApplicationContext().getResources().getDisplayMetrics().heightPixels; inflater.inflate(R.layout.fragment_teacher_vision, null); //UI elements are added on top of AndAR by calling this addContentView-method instead of setContentView super.addContentView(vv, (new LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT))); //create a layout for settings button. add it over video frames LinearLayout lil = new LinearLayout(this); Button settingsButton = new Button(this); settingsButton.setText("Settings"); settingsButton.setLayoutParams(new LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT)); settingsButton.setOnClickListener(new OnClickListener() { public void onClick(View v) { getFragmentManager().beginTransaction().replace(android.R.id.content, new PrefsFragment()) .addToBackStack("settings").commit(); } }); lil.addView(settingsButton); super.addContentView(lil, (new LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT))); //starts the AndAR startPreview(); //mDetector is instantiated here for detecting gestures mDetector = new GestureDetectorCompat(this, new SwipeGestureListener()); //view pager instantiation, also mAdapter instantiated and set as adapter for view pager mPager = (ViewPager) findViewById(R.id.pager); mAdapter = new TabAdapter(getFragmentManager(), mPager); mPager.setAdapter(mAdapter); //begin to poll online users pollUsersCancelled = false; pollUsersTask = new PollUsersTask(this); pollUsersTask.execute(); //begin to poll feedbacks pollFeedbacksCancelled = false; pollFeedbacksTask = new PollFeedbacksTask(this); pollFeedbacksTask.execute(); //begin to poll questions pollQuestionsCancelled = false; pollQuestionsTask = new PollQuestionsTask(this); pollQuestionsTask.execute(); //begin to poll answers pollAnswersCancelled = false; pollAnswersTask = new PollAnswersTask(this); pollAnswersTask.execute(); //initialize tab buttons button = (Button) findViewById(R.id.goto_first); //first one is not enabled at the beginning, because the user is in first tab at first button.setEnabled(false); button2 = (Button) findViewById(R.id.goto_second); button3 = (Button) findViewById(R.id.goto_last); button.setOnClickListener(new View.OnClickListener() { public void onClick(View v) { mPager.setCurrentItem(0); button.setEnabled(false); button2.setEnabled(true); button3.setEnabled(true); } }); button2.setOnClickListener(new View.OnClickListener() { public void onClick(View v) { mPager.setCurrentItem(1); button.setEnabled(true); button2.setEnabled(false); button3.setEnabled(true); } }); button3.setOnClickListener(new View.OnClickListener() { public void onClick(View v) { mPager.setCurrentItem(2); button.setEnabled(true); button2.setEnabled(true); button3.setEnabled(false); } }); }
From source file:com.stoutner.privacybrowser.MainWebViewActivity.java
@Override // Remove Android Studio's warning about the dangers of using SetJavaScriptEnabled. The whole premise of Privacy Browser is built around an understanding of these dangers. @SuppressLint("SetJavaScriptEnabled") protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.main_coordinatorlayout); // We need to use the SupportActionBar from android.support.v7.app.ActionBar until the minimum API is >= 21. Toolbar supportAppBar = (Toolbar) findViewById(R.id.appBar); setSupportActionBar(supportAppBar);/*from w w w . ja v a 2 s.c om*/ final ActionBar appBar = getSupportActionBar(); // This is needed to get rid of the Android Studio warning that appBar might be null. assert appBar != null; // Add the custom url_bar layout, which shows the favoriteIcon, urlTextBar, and progressBar. appBar.setCustomView(R.layout.url_bar); appBar.setDisplayOptions(ActionBar.DISPLAY_SHOW_CUSTOM); // Set the "go" button on the keyboard to load the URL in urlTextBox. urlTextBox = (EditText) appBar.getCustomView().findViewById(R.id.urlTextBox); urlTextBox.setOnKeyListener(new View.OnKeyListener() { public boolean onKey(View v, int keyCode, KeyEvent event) { // If the event is a key-down event on the "enter" button, load the URL. if ((event.getAction() == KeyEvent.ACTION_DOWN) && (keyCode == KeyEvent.KEYCODE_ENTER)) { // Load the URL into the mainWebView and consume the event. try { loadUrlFromTextBox(); } catch (UnsupportedEncodingException e) { e.printStackTrace(); } // If the enter key was pressed, consume the event. return true; } else { // If any other key was pressed, do not consume the event. return false; } } }); final FrameLayout fullScreenVideoFrameLayout = (FrameLayout) findViewById(R.id.fullScreenVideoFrameLayout); // Implement swipe to refresh swipeToRefresh = (SwipeRefreshLayout) findViewById(R.id.swipeRefreshLayout); assert swipeToRefresh != null; //This assert removes the incorrect warning on the following line that swipeToRefresh might be null. swipeToRefresh.setColorSchemeResources(R.color.blue); swipeToRefresh.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() { @Override public void onRefresh() { mainWebView.reload(); } }); mainWebView = (WebView) findViewById(R.id.mainWebView); // Create the navigation drawer. drawerLayout = (DrawerLayout) findViewById(R.id.drawerLayout); // The DrawerTitle identifies the drawer in accessibility mode. drawerLayout.setDrawerTitle(GravityCompat.START, getString(R.string.navigation_drawer)); // Listen for touches on the navigation menu. final NavigationView navigationView = (NavigationView) findViewById(R.id.navigationView); assert navigationView != null; // This assert removes the incorrect warning on the following line that navigationView might be null. navigationView.setNavigationItemSelectedListener(this); // drawerToggle creates the hamburger icon at the start of the AppBar. drawerToggle = new ActionBarDrawerToggle(this, drawerLayout, supportAppBar, R.string.open_navigation, R.string.close_navigation); mainWebView.setWebViewClient(new WebViewClient() { // shouldOverrideUrlLoading makes this WebView the default handler for URLs inside the app, so that links are not kicked out to other apps. @Override public boolean shouldOverrideUrlLoading(WebView view, String url) { mainWebView.loadUrl(url); return true; } // Update the URL in urlTextBox when the page starts to load. @Override public void onPageStarted(WebView view, String url, Bitmap favicon) { urlTextBox.setText(url); } // Update formattedUrlString and urlTextBox. It is necessary to do this after the page finishes loading because the final URL can change during load. @Override public void onPageFinished(WebView view, String url) { formattedUrlString = url; // Only update urlTextBox if the user is not typing in it. if (!urlTextBox.hasFocus()) { urlTextBox.setText(formattedUrlString); } } }); mainWebView.setWebChromeClient(new WebChromeClient() { // Update the progress bar when a page is loading. @Override public void onProgressChanged(WebView view, int progress) { // Make sure that appBar is not null. if (appBar != null) { ProgressBar progressBar = (ProgressBar) appBar.getCustomView().findViewById(R.id.progressBar); progressBar.setProgress(progress); if (progress < 100) { progressBar.setVisibility(View.VISIBLE); } else { progressBar.setVisibility(View.GONE); //Stop the SwipeToRefresh indicator if it is running swipeToRefresh.setRefreshing(false); } } } // Set the favorite icon when it changes. @Override public void onReceivedIcon(WebView view, Bitmap icon) { // Save a copy of the favorite icon for use if a shortcut is added to the home screen. favoriteIcon = icon; // Place the favorite icon in the appBar if it is not null. if (appBar != null) { ImageView imageViewFavoriteIcon = (ImageView) appBar.getCustomView() .findViewById(R.id.favoriteIcon); imageViewFavoriteIcon.setImageBitmap(Bitmap.createScaledBitmap(icon, 64, 64, true)); } } // Enter full screen video @Override public void onShowCustomView(View view, CustomViewCallback callback) { if (appBar != null) { appBar.hide(); } // Show the fullScreenVideoFrameLayout. assert fullScreenVideoFrameLayout != null; //This assert removes the incorrect warning on the following line that fullScreenVideoFrameLayout might be null. fullScreenVideoFrameLayout.addView(view); fullScreenVideoFrameLayout.setVisibility(View.VISIBLE); // Hide the mainWebView. mainWebView.setVisibility(View.GONE); // Hide the ad if this is the free flavor. BannerAd.hideAd(adView); /* SYSTEM_UI_FLAG_HIDE_NAVIGATION hides the navigation bars on the bottom or right of the screen. * SYSTEM_UI_FLAG_FULLSCREEN hides the status bar across the top of the screen. * SYSTEM_UI_FLAG_IMMERSIVE_STICKY makes the navigation and status bars ghosted overlays and automatically rehides them. */ // Set the one flag supported by API >= 14. view.setSystemUiVisibility(View.SYSTEM_UI_FLAG_HIDE_NAVIGATION); // Set the two flags that are supported by API >= 16. if (Build.VERSION.SDK_INT >= 16) { view.setSystemUiVisibility( View.SYSTEM_UI_FLAG_HIDE_NAVIGATION | View.SYSTEM_UI_FLAG_FULLSCREEN); } // Set all three flags that are supported by API >= 19. if (Build.VERSION.SDK_INT >= 19) { view.setSystemUiVisibility(View.SYSTEM_UI_FLAG_HIDE_NAVIGATION | View.SYSTEM_UI_FLAG_FULLSCREEN | View.SYSTEM_UI_FLAG_IMMERSIVE_STICKY); } } // Exit full screen video public void onHideCustomView() { if (appBar != null) { appBar.show(); } // Show the mainWebView. mainWebView.setVisibility(View.VISIBLE); // Show the ad if this is the free flavor. BannerAd.showAd(adView); // Hide the fullScreenVideoFrameLayout. assert fullScreenVideoFrameLayout != null; //This assert removes the incorrect warning on the following line that fullScreenVideoFrameLayout might be null. fullScreenVideoFrameLayout.removeAllViews(); fullScreenVideoFrameLayout.setVisibility(View.GONE); } }); // Allow the downloading of files. mainWebView.setDownloadListener(new DownloadListener() { // Launch the Android download manager when a link leads to a download. @Override public void onDownloadStart(String url, String userAgent, String contentDisposition, String mimetype, long contentLength) { DownloadManager downloadManager = (DownloadManager) getSystemService(DOWNLOAD_SERVICE); DownloadManager.Request requestUri = new DownloadManager.Request(Uri.parse(url)); // Add the URL as the description for the download. requestUri.setDescription(url); // Show the download notification after the download is completed. requestUri.setNotificationVisibility(DownloadManager.Request.VISIBILITY_VISIBLE_NOTIFY_COMPLETED); // Initiate the download and display a Snackbar. downloadManager.enqueue(requestUri); Snackbar.make(findViewById(R.id.mainWebView), R.string.download_started, Snackbar.LENGTH_SHORT) .show(); } }); // Allow pinch to zoom. mainWebView.getSettings().setBuiltInZoomControls(true); // Hide zoom controls. mainWebView.getSettings().setDisplayZoomControls(false); // Initialize the default preference values the first time the program is run. PreferenceManager.setDefaultValues(this, R.xml.preferences, false); // Get the shared preference values. SharedPreferences savedPreferences = PreferenceManager.getDefaultSharedPreferences(this); // Set JavaScript initial status. The default value is false. javaScriptEnabled = savedPreferences.getBoolean("javascript_enabled", false); mainWebView.getSettings().setJavaScriptEnabled(javaScriptEnabled); // Initialize cookieManager. cookieManager = CookieManager.getInstance(); // Set cookies initial status. The default value is false. firstPartyCookiesEnabled = savedPreferences.getBoolean("first_party_cookies_enabled", false); cookieManager.setAcceptCookie(firstPartyCookiesEnabled); // Set third-party cookies initial status if API >= 21. The default value is false. if (Build.VERSION.SDK_INT >= 21) { thirdPartyCookiesEnabled = savedPreferences.getBoolean("third_party_cookies_enabled", false); cookieManager.setAcceptThirdPartyCookies(mainWebView, thirdPartyCookiesEnabled); } // Set DOM storage initial status. The default value is false. domStorageEnabled = savedPreferences.getBoolean("dom_storage_enabled", false); mainWebView.getSettings().setDomStorageEnabled(domStorageEnabled); // Set the user agent initial status. String userAgentString = savedPreferences.getString("user_agent", "Default user agent"); switch (userAgentString) { case "Default user agent": // Do nothing. break; case "Custom user agent": // Set the custom user agent on mainWebView, The default is "PrivacyBrowser/1.0". mainWebView.getSettings() .setUserAgentString(savedPreferences.getString("custom_user_agent", "PrivacyBrowser/1.0")); break; default: // Set the selected user agent on mainWebView. The default is "PrivacyBrowser/1.0". mainWebView.getSettings() .setUserAgentString(savedPreferences.getString("user_agent", "PrivacyBrowser/1.0")); break; } // Set the initial string for JavaScript disabled search. if (savedPreferences.getString("javascript_disabled_search", "https://duckduckgo.com/html/?q=") .equals("Custom URL")) { // Get the custom URL string. The default is "". javaScriptDisabledSearchURL = savedPreferences.getString("javascript_disabled_search_custom_url", ""); } else { // Use the string from javascript_disabled_search. javaScriptDisabledSearchURL = savedPreferences.getString("javascript_disabled_search", "https://duckduckgo.com/html/?q="); } // Set the initial string for JavaScript enabled search. if (savedPreferences.getString("javascript_enabled_search", "https://duckduckgo.com/?q=") .equals("Custom URL")) { // Get the custom URL string. The default is "". javaScriptEnabledSearchURL = savedPreferences.getString("javascript_enabled_search_custom_url", ""); } else { // Use the string from javascript_enabled_search. javaScriptEnabledSearchURL = savedPreferences.getString("javascript_enabled_search", "https://duckduckgo.com/?q="); } // Set homepage initial status. The default value is "https://www.duckduckgo.com". homepage = savedPreferences.getString("homepage", "https://www.duckduckgo.com"); // Set swipe to refresh initial status. The default is true. swipeToRefreshEnabled = savedPreferences.getBoolean("swipe_to_refresh_enabled", true); swipeToRefresh.setEnabled(swipeToRefreshEnabled); // Get the intent information that started the app. final Intent intent = getIntent(); if (intent.getData() != null) { // Get the intent data and convert it to a string. final Uri intentUriData = intent.getData(); formattedUrlString = intentUriData.toString(); } // If formattedUrlString is null assign the homepage to it. if (formattedUrlString == null) { formattedUrlString = homepage; } // Load the initial website. mainWebView.loadUrl(formattedUrlString); // Initialize AdView for the free flavor and request an ad. If this is not the free flavor BannerAd.requestAd() does nothing. adView = findViewById(R.id.adView); BannerAd.requestAd(adView); }
From source file:de.frank_durr.ble_v_monitor.MainActivity.java
@Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); restoreDataModel(savedInstanceState); if (bluetoothAdapter == null) { BluetoothManager bluetoothManager = (BluetoothManager) getSystemService(Context.BLUETOOTH_SERVICE); bluetoothAdapter = bluetoothManager.getAdapter(); }/*from w ww. j a v a2s . c o m*/ if (savedInstanceState != null && savedInstanceState.containsKey(BUNDLE_KEY_BLUETOOTH_DEVICE)) { bluetoothDevice = savedInstanceState.getParcelable(BUNDLE_KEY_BLUETOOTH_DEVICE); } PreferenceManager.setDefaultValues(this, R.xml.preferences, false); gattHandler = new GattCallbackHandler(); taskTimoutHandler = new Handler(); updateTriggerHandler = new ModelUpdateTriggerHandler(); Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar); String appName = getString(R.string.app_name); toolbar.setTitle(appName); setSupportActionBar(toolbar); FragmentManager fm = getSupportFragmentManager(); ViewPager viewPager = (ViewPager) findViewById(R.id.viewpager); FPAdapter fpAdapter = new FPAdapter(fm); viewPager.setAdapter(fpAdapter); // Get references to already existing tags if (savedInstanceState != null) { if (savedInstanceState.containsKey(BUNDLE_KEY_CURRENT_VOLTAGE_FRAGMENT)) { String tag = savedInstanceState.getString(BUNDLE_KEY_CURRENT_VOLTAGE_FRAGMENT); fragmentCurrentVoltage = (CurrentVoltageFragment) fm.findFragmentByTag(tag); } if (savedInstanceState.containsKey(BUNDLE_KEY_MINUTELY_HISTORY_FRAGMENT)) { String tag = savedInstanceState.getString(BUNDLE_KEY_MINUTELY_HISTORY_FRAGMENT); fragmentMinutelyHistory = (HistoryFragment) fm.findFragmentByTag(tag); } if (savedInstanceState.containsKey(BUNDLE_KEY_HOURLY_HISTORY_FRAGMENT)) { String tag = savedInstanceState.getString(BUNDLE_KEY_HOURLY_HISTORY_FRAGMENT); fragmentHourlyHistory = (HistoryFragment) fm.findFragmentByTag(tag); } if (savedInstanceState.containsKey(BUNDLE_KEY_DAILY_HISTORY_FRAGMENT)) { String tag = savedInstanceState.getString(BUNDLE_KEY_DAILY_HISTORY_FRAGMENT); fragmentDailyHistory = (HistoryFragment) fm.findFragmentByTag(tag); } } TabLayout tabLayout = (TabLayout) findViewById(R.id.tablayout); tabLayout.setupWithViewPager(viewPager); }
From source file:net.emilymaier.movebot.MoveBotActivity.java
@Override @SuppressWarnings({ "deprecation", "unchecked" }) public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.main);//from www. j a va 2 s . c om PreferenceManager.setDefaultValues(this, R.xml.preferences, false); Units.initialize(this); Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar); setSupportActionBar(toolbar); runs = new ArrayList<>(); try { FileInputStream fis = openFileInput("runs.ser"); ObjectInputStream ois = new ObjectInputStream(fis); runs = (ArrayList<Run>) ois.readObject(); ois.close(); fis.close(); } catch (FileNotFoundException e) { } catch (IOException e) { throw new RuntimeException("IOException", e); } catch (ClassNotFoundException e) { throw new RuntimeException("ClassNotFoundException", e); } font = Typeface.createFromAsset(getAssets(), "fonts/led_real.ttf"); pager = (ViewPager) findViewById(R.id.pager); adapter = new MainPagerAdapter(getSupportFragmentManager()); runsFragment = new RunsFragment(); heartFragment = new HeartFragment(this); developerFragment = new DeveloperFragment(); controlFragment = new ControlFragment(); mapFragment = SupportMapFragment.newInstance(); pager.setAdapter(adapter); updateDeveloperMode(); gpsInfoTimer = new Timer(); gpsInfoTimer.schedule(new GpsInfoTask(), 2 * 1000); mapFragment.getMapAsync(this); BluetoothAdapter bluetoothAdapter = BluetoothAdapter.getDefaultAdapter(); if (bluetoothAdapter != null) { if (!bluetoothAdapter.isEnabled()) { Intent intent = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE); startActivityForResult(intent, 1); } } }
From source file:org.physical_web.physicalweb.Utils.java
/** * Saves the default settings to the SharedPreferences. * @param context The context for the SharedPreferences. *//* w ww .j a va 2s . c om*/ public static void setSharedPreferencesDefaultValues(Context context) { PreferenceManager.setDefaultValues(context, R.xml.settings, false); setPwsEndpointPreference(context, getCurrentPwsEndpointString(context)); if (context.getSharedPreferences(MAIN_PREFS_KEY, Context.MODE_PRIVATE).getBoolean(USER_OPTED_IN_KEY, false)) { setOptInPreference(context); deletePreference(context, MAIN_PREFS_KEY); deletePreference(context, DISCOVERY_SERVICE_PREFS_KEY); } }