List of usage examples for android.os Bundle getInt
public int getInt(String key)
From source file:uk.co.senab.photoview.sample.ViewPagerActivity.java
public void contributeThreeDollars() { new Thread(new Runnable() { public void run() { ArrayList skuList = new ArrayList(); skuList.add(threeDollars);/* w w w. ja v a 2 s . c o m*/ Bundle querySkus = new Bundle(); querySkus.putStringArrayList("ITEM_ID_LIST", skuList); final Bundle skuDetails; try { skuDetails = mservice.getSkuDetails(3, getPackageName(), "inapp", querySkus); int response = skuDetails.getInt("RESPONSE_CODE"); if (response == 0) { ArrayList<String> responseList = skuDetails.getStringArrayList("DETAILS_LIST"); for (String thisResponse : responseList) { JSONObject object = new JSONObject(thisResponse); String sku = object.getString("productId"); String price = object.getString("price"); if (sku.equals(threeDollars)) { System.out.println("price " + price); Bundle buyIntentBundle = mservice.getBuyIntent(3, getPackageName(), sku, "inapp", "bGoa+V7g/yqDXvKRqq+JTFn4uQZbPiQJo4pf9RzJ"); PendingIntent pendingIntent = buyIntentBundle.getParcelable("BUY_INTENT"); startIntentSenderForResult(pendingIntent.getIntentSender(), 1001, new Intent(), Integer.valueOf(0), Integer.valueOf(0), Integer.valueOf(0)); } } } // } catch (RemoteException e) { // e.printStackTrace(); } catch (JSONException e) { // e.printStackTrace(); } catch (SendIntentException e) { // TODO Auto-generated catch block e.printStackTrace(); } } }).start(); }
From source file:uk.co.senab.photoview.sample.ViewPagerActivity.java
public void contributeFourDollars() { new Thread(new Runnable() { public void run() { ArrayList skuList = new ArrayList(); skuList.add(fourDollars);/* ww w . j a v a2s . co m*/ Bundle querySkus = new Bundle(); querySkus.putStringArrayList("ITEM_ID_LIST", skuList); final Bundle skuDetails; try { skuDetails = mservice.getSkuDetails(3, getPackageName(), "inapp", querySkus); int response = skuDetails.getInt("RESPONSE_CODE"); if (response == 0) { ArrayList<String> responseList = skuDetails.getStringArrayList("DETAILS_LIST"); for (String thisResponse : responseList) { JSONObject object = new JSONObject(thisResponse); String sku = object.getString("productId"); String price = object.getString("price"); if (sku.equals(fourDollars)) { System.out.println("price " + price); Bundle buyIntentBundle = mservice.getBuyIntent(3, getPackageName(), sku, "inapp", "bGoa+V7g/yqDXvKRqq+JTFn4uQZbPiQJo4pf9RzJ"); PendingIntent pendingIntent = buyIntentBundle.getParcelable("BUY_INTENT"); startIntentSenderForResult(pendingIntent.getIntentSender(), 1001, new Intent(), Integer.valueOf(0), Integer.valueOf(0), Integer.valueOf(0)); } } } // } catch (RemoteException e) { // e.printStackTrace(); } catch (JSONException e) { // e.printStackTrace(); } catch (SendIntentException e) { // e.printStackTrace(); } } }).start(); }
From source file:uk.co.senab.photoview.sample.ViewPagerActivity.java
@Override protected void onActivityResult(int requestCode, int resultCode, Intent data) { if (requestCode == 1001) { int responseCode = data.getIntExtra("RESPONSE_CODE", 0); final String purchaseData = data.getStringExtra("INAPP_PURCHASE_DATA"); String dataSignature = data.getStringExtra("INAPP_DATA_SIGNATURE"); new Thread(new Runnable() { public void run() { //Thread.sleep(5*1000); try { Bundle ownedItems = mservice.getPurchases(3, getPackageName(), "inapp", null); // Check response int responseCode = ownedItems.getInt("RESPONSE_CODE"); if (responseCode != 0) { throw new Exception("Error"); }/* w ww .j av a 2s. c o m*/ // Get the list of purchased items ArrayList<String> purchaseDataList = ownedItems .getStringArrayList("INAPP_PURCHASE_DATA_LIST"); for (String purchaseData : purchaseDataList) { JSONObject o = new JSONObject(purchaseData); String purchaseToken = o.optString("token", o.optString("purchaseToken")); // Consume purchaseToken, handling any errors mservice.consumePurchase(3, getPackageName(), purchaseToken); } } catch (RemoteException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (Exception e) { // TODO Auto-generated catch block e.printStackTrace(); } } }).start(); if (resultCode == RESULT_OK) { try { JSONObject jo = new JSONObject(purchaseData); String sku = jo.getString("productId"); new Thread(new Runnable() { public void run() { try { Bundle ownedItems = mservice.getPurchases(3, getPackageName(), "inapp", null); // Check response int responseCode = ownedItems.getInt("RESPONSE_CODE"); if (responseCode != 0) { throw new Exception("Error"); } // Get the list of purchased items ArrayList<String> purchaseDataList = ownedItems .getStringArrayList("INAPP_PURCHASE_DATA_LIST"); for (String purchaseData : purchaseDataList) { JSONObject o = new JSONObject(purchaseData); String purchaseToken = o.optString("token", o.optString("purchaseToken")); // Consume purchaseToken, handling any errors mservice.consumePurchase(3, getPackageName(), purchaseToken); } } catch (RemoteException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (Exception e) { // TODO Auto-generated catch block e.printStackTrace(); } } }).start(); } catch (JSONException e) { e.printStackTrace(); } } } }
From source file:com.hichinaschool.flashcards.anki.CardEditor.java
@Override protected void onCreate(Bundle savedInstanceState) { // Log.i(AnkiDroidApp.TAG, "CardEditor: onCreate"); Themes.applyTheme(this); super.onCreate(savedInstanceState); this.getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_ALWAYS_HIDDEN); Intent intent = getIntent();/*from w ww . ja va2s . c om*/ if (savedInstanceState != null) { mCaller = savedInstanceState.getInt("caller"); mAddNote = savedInstanceState.getBoolean("addFact"); } else { mCaller = intent.getIntExtra(EXTRA_CALLER, CALLER_NOCALLER); if (mCaller == CALLER_NOCALLER) { String action = intent.getAction(); if (action != null && (ACTION_CREATE_FLASHCARD.equals(action) || ACTION_CREATE_FLASHCARD_SEND.equals(action))) { mCaller = CALLER_INDICLASH; } } } // Log.i(AnkiDroidApp.TAG, "CardEditor: caller: " + mCaller); SharedPreferences preferences = AnkiDroidApp.getSharedPrefs(getBaseContext()); if (mCaller == CALLER_INDICLASH && preferences.getBoolean("intentAdditionInstantAdd", false)) { // save information without showing card editor fetchIntentInformation(intent); MetaDB.saveIntentInformation(CardEditor.this, Utils.joinFields(mSourceText)); Themes.showThemedToast(CardEditor.this, getResources().getString(R.string.app_name) + ": " + getResources().getString(R.string.CardEditorLaterMessage), false); finish(); return; } mCol = AnkiDroidApp.getCol(); if (mCol == null) { reloadCollection(savedInstanceState); return; } registerExternalStorageListener(); View mainView = getLayoutInflater().inflate(R.layout.card_editor, null); setContentView(mainView); Themes.setWallpaper(mainView); Themes.setContentStyle(mainView, Themes.CALLER_CARD_EDITOR); mFieldsLayoutContainer = (LinearLayout) findViewById(R.id.CardEditorEditFieldsLayout); mSave = (Button) findViewById(R.id.CardEditorSaveButton); mCancel = (Button) findViewById(R.id.CardEditorCancelButton); mLater = (Button) findViewById(R.id.CardEditorLaterButton); mDeckButton = (TextView) findViewById(R.id.CardEditorDeckText); mModelButton = (TextView) findViewById(R.id.CardEditorModelText); mTagsButton = (TextView) findViewById(R.id.CardEditorTagText); mSwapButton = (Button) findViewById(R.id.CardEditorSwapButton); mSwapButton.setOnClickListener(new View.OnClickListener() { public void onClick(View v) { swapText(false); } }); mAedictIntent = false; switch (mCaller) { case CALLER_NOCALLER: // Log.i(AnkiDroidApp.TAG, "CardEditor: no caller could be identified, closing"); finish(); return; case CALLER_REVIEWER: mCurrentEditedCard = Reviewer.getEditorCard(); if (mCurrentEditedCard == null) { finish(); return; } mEditorNote = mCurrentEditedCard.note(); mAddNote = false; break; case CALLER_STUDYOPTIONS: case CALLER_DECKPICKER: mAddNote = true; break; case CALLER_BIGWIDGET_EDIT: // Card widgetCard = AnkiDroidWidgetBig.getCard(); // if (widgetCard == null) { // finish(); // return; // } // mEditorNote = widgetCard.getFact(); // mAddNote = false; break; case CALLER_BIGWIDGET_ADD: mAddNote = true; break; case CALLER_CARDBROWSER_EDIT: mCurrentEditedCard = CardBrowser.sCardBrowserCard; if (mCurrentEditedCard == null) { finish(); return; } mEditorNote = mCurrentEditedCard.note(); mAddNote = false; break; case CALLER_CARDBROWSER_ADD: mAddNote = true; break; case CALLER_CARDEDITOR: mAddNote = true; break; case CALLER_CARDEDITOR_INTENT_ADD: mAddNote = true; break; case CALLER_INDICLASH: fetchIntentInformation(intent); if (mSourceText == null) { finish(); return; } if (mSourceText[0].equals("Aedict Notepad") && addFromAedict(mSourceText[1])) { finish(); return; } mAddNote = true; break; } setNote(mEditorNote); if (mAddNote) { setTitle(R.string.cardeditor_title_add_note); // set information transferred by intent String contents = null; if (mSourceText != null) { if (mAedictIntent && (mEditFields.size() == 3) && mSourceText[1].contains("[")) { contents = mSourceText[1].replaceFirst("\\[", "\u001f"); contents = contents.substring(0, contents.length() - 1); } else { mEditFields.get(0).setText(mSourceText[0]); mEditFields.get(1).setText(mSourceText[1]); } } else { contents = intent.getStringExtra(EXTRA_CONTENTS); } if (contents != null) { setEditFieldTexts(contents); } LinearLayout modelButton = ((LinearLayout) findViewById(R.id.CardEditorModelButton)); modelButton.setOnClickListener(new View.OnClickListener() { public void onClick(View v) { showDialog(DIALOG_MODEL_SELECT); } }); modelButton.setVisibility(View.VISIBLE); mSave.setText(getResources().getString(R.string.add)); mCancel.setText(getResources().getString(R.string.close)); mLater.setVisibility(View.VISIBLE); mLater.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { String content = getFieldsText(); if (content.length() > mEditFields.size() - 1) { MetaDB.saveIntentInformation(CardEditor.this, content); populateEditFields(); mSourceText = null; Themes.showThemedToast(CardEditor.this, getResources().getString(R.string.CardEditorLaterMessage), false); } if (mCaller == CALLER_INDICLASH || mCaller == CALLER_CARDEDITOR_INTENT_ADD) { closeCardEditor(); } } }); } else { setTitle(R.string.cardeditor_title_edit_card); mSwapButton.setVisibility(View.GONE); mSwapButton = (Button) findViewById(R.id.CardEditorLaterButton); mSwapButton.setVisibility(View.VISIBLE); mSwapButton.setText(getResources().getString(R.string.fact_adder_swap)); mSwapButton.setOnClickListener(new View.OnClickListener() { public void onClick(View v) { swapText(false); } }); } ((LinearLayout) findViewById(R.id.CardEditorDeckButton)).setOnClickListener(new View.OnClickListener() { public void onClick(View v) { showDialog(DIALOG_DECK_SELECT); } }); mPrefFixArabic = preferences.getBoolean("fixArabicText", false); // if Arabic reshaping is enabled, disable the Save button to avoid // saving the reshaped string to the deck if (mPrefFixArabic && !mAddNote) { mSave.setEnabled(false); } ((LinearLayout) findViewById(R.id.CardEditorTagButton)).setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { showDialog(DIALOG_TAGS_SELECT); } }); mSave.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { if (duplicateCheck(true)) { return; } boolean modified = false; for (FieldEditText f : mEditFields) { modified = modified | f.updateField(); } if (mAddNote) { DeckTask.launchDeckTask(DeckTask.TASK_TYPE_ADD_FACT, mSaveFactHandler, new DeckTask.TaskData(mEditorNote)); } else { // added tag? for (String t : mCurrentTags) { modified = modified || !mEditorNote.hasTag(t); } // removed tag? modified = modified || mEditorNote.getTags().size() > mCurrentTags.size(); // changed did? boolean changedDid = mCurrentEditedCard.getDid() != mCurrentDid; modified = modified || changedDid; if (modified) { mEditorNote.setTags(mCurrentTags); // set did for card if (changedDid) { mCurrentEditedCard.setDid(mCurrentDid); } mChanged = true; } closeCardEditor(); // if (mCaller == CALLER_BIGWIDGET_EDIT) { // // DeckTask.launchDeckTask(DeckTask.TASK_TYPE_UPDATE_FACT, // // mSaveFactHandler, new // // DeckTask.TaskData(Reviewer.UPDATE_CARD_SHOW_QUESTION, // // mDeck, AnkiDroidWidgetBig.getCard())); // } else if (!mCardReset) { // // Only send result to save if something was actually // // changed // if (mModified) { // setResult(RESULT_OK); // } else { // setResult(RESULT_CANCELED); // } // closeCardEditor(); // } } } }); mCancel.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { closeCardEditor(); } }); }
From source file:com.blueverdi.rosietheriveter.PhotoViewActivity.java
@Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); Bundle b = getIntent().getExtras();/*from w w w . ja va 2 s .c o m*/ try { details = b.getParcelable(SiteDetails.PARCEL_NAME); } catch (Exception e) { MyLog.d(TAG, "exception retrieving site info"); finish(); } if (details == null) { MyLog.d(TAG, "no details"); finish(); } setContentView(R.layout.activity_photo_view); View view = findViewById(R.id.photoView); view.setOnTouchListener(new OnSwipeTouchListener(this) { @Override public void onSwipeLeft() { nextPhoto(); } @Override public void onSwipeRight() { lastPhoto(); } @Override public void onTap() { zoomIn(); } }); view = findViewById(R.id.leftArrow); view.setOnClickListener(this); view = findViewById(R.id.rightArrow); view.setOnClickListener(this); TextView tv = (TextView) findViewById(R.id.name); tv.setText(details.name); caption = (TextView) findViewById(R.id.caption); photoView = (ImageView) findViewById(R.id.photoView); imageSource = PHOTO_BASE + File.separator + details.photoDirectory; try { imageFiles = this.getAssets().list(imageSource); } catch (Exception e) { MyLog.d(TAG, e.toString()); e.printStackTrace(); imageFiles = new String[0]; } if (imageFiles.length == 0) { MyLog.d(TAG, "no photos to display"); finish(); } captions = getResources().getStringArray(details.captionArrayID); if (savedInstanceState != null) { index = savedInstanceState.getInt(INDEX); } displayImage(index); rosieHelpMenu = new RosieHelpMenu(this); hintScreen(); }
From source file:com.vegnab.vegnab.MainVNActivity.java
public void onPlaceholderActionButtonClicked(Bundle args) { Bundle argsOut = new Bundle(); if (LDebug.ON) Log.d(LOG_TAG, "In onPlaceholderActionButtonClicked"); switch (args.getInt(EditPlaceholderFragment.BUTTON_KEY)) { case VNContract.PhActions.GO_TO_PICTURES: // go to the show/take/edit photos screen argsOut.putLong(PhPixGridFragment.ARG_PLACEHOLDER_ID, args.getLong(EditPlaceholderFragment.ARG_PLACEHOLDER_ID)); PhPixGridFragment phGridFrag = PhPixGridFragment.newInstance(argsOut); FragmentTransaction transaction = getSupportFragmentManager().beginTransaction(); // put the present fragment on the backstack so the user can navigate back to it // the tag is for the fragment now being added, not the one replaced transaction.replace(R.id.fragment_container, phGridFrag, Tags.PLACEHOLDER_PIX_GRID); transaction.addToBackStack(null); transaction.commit();//from ww w . ja v a 2s . c o m break; } }
From source file:com.carlrice.reader.activity.EditFeedActivity.java
@Override protected void onCreate(Bundle savedInstanceState) { UiUtils.setPreferenceTheme(this); super.onCreate(savedInstanceState); setContentView(R.layout.activity_feed_edit); Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar); setSupportActionBar(toolbar);// www . java 2s . co m getSupportActionBar().setDisplayHomeAsUpEnabled(true); setResult(RESULT_CANCELED); Intent intent = getIntent(); mTabHost = (TabHost) findViewById(R.id.tabHost); mNameEditText = (EditText) findViewById(R.id.feed_title); mUrlEditText = (EditText) findViewById(R.id.feed_url); mRetrieveFulltextCb = (CheckBox) findViewById(R.id.retrieve_fulltext); mFiltersListView = (ListView) findViewById(android.R.id.list); View tabWidget = findViewById(android.R.id.tabs); View buttonLayout = findViewById(R.id.button_layout); mTabHost.setup(); mTabHost.addTab(mTabHost.newTabSpec("feedTab").setIndicator(getString(R.string.tab_feed_title)) .setContent(R.id.feed_tab)); mTabHost.addTab(mTabHost.newTabSpec("filtersTab").setIndicator(getString(R.string.tab_filters_title)) .setContent(R.id.filters_tab)); mTabHost.setOnTabChangedListener(new TabHost.OnTabChangeListener() { @Override public void onTabChanged(String s) { invalidateOptionsMenu(); } }); if (savedInstanceState != null) { mTabHost.setCurrentTab(savedInstanceState.getInt(STATE_CURRENT_TAB)); } if (intent.getAction().equals(Intent.ACTION_INSERT) || intent.getAction().equals(Intent.ACTION_SEND)) { setTitle(R.string.new_feed_title); tabWidget.setVisibility(View.GONE); if (intent.hasExtra(Intent.EXTRA_TEXT)) { mUrlEditText.setText(intent.getStringExtra(Intent.EXTRA_TEXT)); } } else if (intent.getAction().equals(Intent.ACTION_EDIT)) { setTitle(R.string.edit_feed_title); buttonLayout.setVisibility(View.GONE); mFiltersCursorAdapter = new FiltersCursorAdapter(this, Constants.EMPTY_CURSOR); mFiltersListView.setAdapter(mFiltersCursorAdapter); mFiltersListView.setOnItemLongClickListener(new OnItemLongClickListener() { @Override public boolean onItemLongClick(AdapterView<?> parent, View view, int position, long id) { startSupportActionMode(mFilterActionModeCallback); mFiltersCursorAdapter.setSelectedFilter(position); mFiltersListView.invalidateViews(); return true; } }); getLoaderManager().initLoader(0, null, this); if (savedInstanceState == null) { Cursor cursor = getContentResolver().query(intent.getData(), FEED_PROJECTION, null, null, null); if (cursor.moveToNext()) { mNameEditText.setText(cursor.getString(0)); mUrlEditText.setText(cursor.getString(1)); mRetrieveFulltextCb.setChecked(cursor.getInt(2) == 1); cursor.close(); } else { cursor.close(); Toast.makeText(EditFeedActivity.this, R.string.error, Toast.LENGTH_SHORT).show(); finish(); } } } }
From source file:org.dvbviewer.controller.ui.fragments.ChannelList.java
@Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); mContext = getActivity().getApplicationContext(); ConnectivityManager connManager = (ConnectivityManager) getActivity() .getSystemService(Context.CONNECTIVITY_SERVICE); mNetworkInfo = connManager.getNetworkInfo(ConnectivityManager.TYPE_WIFI); prefs = new DVBViewerPreferences(getActivity()); showFavs = prefs.getPrefs().getBoolean(DVBViewerPreferences.KEY_CHANNELS_USE_FAVS, false); showNowPlaying = prefs.getPrefs().getBoolean(DVBViewerPreferences.KEY_CHANNELS_SHOW_NOW_PLAYING, true); showNowPlayingWifi = prefs.getPrefs() .getBoolean(DVBViewerPreferences.KEY_CHANNELS_SHOW_NOW_PLAYING_WIFI_ONLY, true); mAdapter = new ChannelAdapter(getActivity()); if (getArguments() != null) { if (getArguments().containsKey(ChannelList.KEY_HAS_OPTIONMENU)) { hasOptionsMenu = getArguments().getBoolean(KEY_HAS_OPTIONMENU); }/*from w ww. j ava 2 s .com*/ } if (savedInstanceState != null) { if (savedInstanceState.containsKey(KEY_SELECTED_POSITION)) { selectedPosition = savedInstanceState.getInt(KEY_SELECTED_POSITION); } } else { selectedPosition = getActivity().getIntent().getIntExtra(KEY_SELECTED_POSITION, selectedPosition); } setHasOptionsMenu(hasOptionsMenu); }
From source file:com.andrewshu.android.reddit.profile.ProfileActivity.java
/** * Called when the activity starts up. Do activity initialization * here, not in a constructor./*from www. ja v a 2 s . c o m*/ * * @see Activity#onCreate */ @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); CookieSyncManager.createInstance(getApplicationContext()); mSettings.loadRedditPreferences(this, mClient); setRequestedOrientation(mSettings.getRotation()); setTheme(mSettings.getTheme()); requestWindowFeature(Window.FEATURE_PROGRESS); requestWindowFeature(Window.FEATURE_INDETERMINATE_PROGRESS); setContentView(R.layout.profile_list_content); if (savedInstanceState != null) { if (Constants.LOGGING) Log.d(TAG, "using savedInstanceState"); mUsername = savedInstanceState.getString(Constants.USERNAME_KEY); mAfter = savedInstanceState.getString(Constants.AFTER_KEY); mBefore = savedInstanceState.getString(Constants.BEFORE_KEY); mCount = savedInstanceState.getInt(Constants.THREAD_COUNT_KEY); mLastAfter = savedInstanceState.getString(Constants.LAST_AFTER_KEY); mLastBefore = savedInstanceState.getString(Constants.LAST_BEFORE_KEY); mLastCount = savedInstanceState.getInt(Constants.THREAD_LAST_COUNT_KEY); mKarma = savedInstanceState.getStringArray(Constants.KARMA_KEY); mSortByUrl = savedInstanceState.getString(Constants.CommentsSort.SORT_BY_KEY); mJumpToThreadId = savedInstanceState.getString(Constants.JUMP_TO_THREAD_ID_KEY); mVoteTargetThingInfo = savedInstanceState.getParcelable(Constants.VOTE_TARGET_THING_INFO_KEY); // try to restore mThingsList using getLastNonConfigurationInstance() // (separate function to avoid a compiler warning casting ArrayList<ThingInfo> restoreLastNonConfigurationInstance(); if (mThingsList == null) { // Load previous page of profile items if (mLastAfter != null) { new DownloadProfileTask(mUsername, mLastAfter, null, mLastCount).execute(); } else if (mLastBefore != null) { new DownloadProfileTask(mUsername, null, mLastBefore, mLastCount).execute(); } else { new DownloadProfileTask(mUsername).execute(); } } else { // Orientation change. Use prior instance. resetUI(new ThingsListAdapter(this, mThingsList)); setTitle(mUsername + "'s profile"); } return; } // Handle subreddit Uri passed via Intent else if (getIntent().getData() != null) { Matcher userPathMatcher = USER_PATH_PATTERN.matcher(getIntent().getData().getPath()); if (userPathMatcher.matches()) { mUsername = userPathMatcher.group(1); new DownloadProfileTask(mUsername).execute(); return; } } // No username specified by Intent, so load the logged in user's profile if (mSettings.isLoggedIn()) { mUsername = mSettings.getUsername(); new DownloadProfileTask(mUsername).execute(); return; } // Can't find a username to use. Quit. if (Constants.LOGGING) Log.e(TAG, "Could not find a username to use for ProfileActivity"); finish(); }
From source file:com.heightechllc.breakify.MainActivity.java
/** * Skips to the next timer state/* w ww .j a v a 2 s .c o m*/ */ private void skipToNextState() { int oldWorkState = getWorkState(); // Record the state we're about to skip from, in case the user chooses to undo Bundle undoStateBundle = new Bundle(); undoStateBundle.putLong("totalTime", circleTimer.getTotalTime()); undoStateBundle.putLong("remainingTime", circleTimer.getRemainingTime()); undoStateBundle.putInt("workState", oldWorkState); String toastMessage = getString(R.string.skip_toast); // Get duration from preferences, in minutes long duration; if (oldWorkState == WORK_STATE_WORKING) { // Means we're skipping to break duration = sharedPref.getInt(TimerDurationsSettingsFragment.KEY_BREAK_DURATION, 0); toastMessage += " break"; } else { // Means we're skipping to work duration = sharedPref.getInt(TimerDurationsSettingsFragment.KEY_WORK_DURATION, 0); toastMessage += " work"; } // Create and show the undo bar showUndoBar(toastMessage, undoStateBundle, new UndoBarController.UndoListener() { @Override public void onUndo(Parcelable parcelable) { if (parcelable == null) return; // Extract the saved state from the Parcelable Bundle undoStateBundle = (Bundle) parcelable; long prevTotalTime = undoStateBundle.getLong("totalTime"); long prevRemainingTime = undoStateBundle.getLong("remainingTime"); int prevWorkState = undoStateBundle.getInt("workState"); // Cause startTimer() to treat it like we're resuming (b/c we are) timerState = TIMER_STATE_PAUSED; setWorkState(prevWorkState); // Restore to the previous timer state, similar to how we restore a // running timer from SharedPreferences in onCreate() circleTimer.setTotalTime(prevTotalTime); circleTimer.updateTimeLbl(prevRemainingTime); // Record the total duration, so we can resume if the activity is destroyed sharedPref.edit().putLong("schedTotalTime", prevTotalTime).apply(); startTimer(prevRemainingTime); // Analytics if (mixpanel != null) mixpanel.track("Skip undone", null); } }); // Set the new state if (oldWorkState == WORK_STATE_WORKING) setWorkState(WORK_STATE_BREAKING); else setWorkState(WORK_STATE_WORKING); // We want to start the timer from scratch, not from a paused state timerState = TIMER_STATE_STOPPED; // Start the timer startTimer(duration * 60000); // Multiply into milliseconds // Analytics if (mixpanel != null) { JSONObject props = new JSONObject(); try { props.put("Duration", duration); } catch (JSONException e) { e.printStackTrace(); } String eventName = getWorkState() == WORK_STATE_WORKING ? "Skipped to work" : "Skipped to break"; mixpanel.track(eventName, props); } }