List of usage examples for android.os Bundle getParcelable
@Nullable public <T extends Parcelable> T getParcelable(@Nullable String key)
From source file:com.chen.mail.ui.AbstractActivityController.java
/** * The application can be started from the following entry points: * <ul>/*from ww w .j av a 2s. c o m*/ * <li>Launcher: you tap on the Gmail icon in the launcher. This is what most users think of * as Starting the app?.</li> * <li>Shortcut: Users can make a shortcut to take them directly to a label.</li> * <li>Widget: Shows the contents of a synced label, and allows: * <ul> * <li>Viewing the list (tapping on the title)</li> * <li>Composing a new message (tapping on the new message icon in the title. This * launches the {@link ComposeActivity}. * </li> * <li>Viewing a single message (tapping on a list element)</li> * </ul> * * </li> * <li>Tapping on a notification: * <ul> * <li>Shows message list if more than one message</li> * <li>Shows the conversation if the notification is for a single message</li> * </ul> * </li> * <li>...and most importantly, the activity life cycle can tear down the application and * restart it: * <ul> * <li>Rotate the application: it is destroyed and recreated.</li> * <li>Navigate away, and return from recent applications.</li> * </ul> * </li> * <li>Add a new account: fires off an intent to add an account, * and returns in {@link #onActivityResult(int, int, android.content.Intent)} .</li> * <li>Re-authenticate your account: again returns in onActivityResult().</li> * <li>Composing can happen from many entry points: third party applications fire off an * intent to compose email, and launch directly into the {@link ComposeActivity} * .</li> * </ul> * {@inheritDoc} */ @Override public boolean onCreate(Bundle savedState) { initializeActionBar(); initializeDevLoggingService(); // Allow shortcut keys to function for the ActionBar and menus. mActivity.setDefaultKeyMode(Activity.DEFAULT_KEYS_SHORTCUT); mResolver = mActivity.getContentResolver(); mNewEmailReceiver = new SuppressNotificationReceiver(); mRecentFolderList.initialize(mActivity); mVeiledMatcher.initialize(this); // the "open drawer description" argument is for when the drawer is open // so tell the user that interacting will cause the drawer to close // and vice versa for the "close drawer description" argument mDrawerToggle = new ActionBarDrawerToggle((Activity) mActivity, mDrawerContainer, R.drawable.ic_drawer, R.string.drawer_close, R.string.drawer_open); mDrawerListener = new MailDrawerListener(); mDrawerContainer.setDrawerListener(mDrawerListener); mDrawerContainer.setDrawerShadow(mContext.getResources().getDrawable(R.drawable.drawer_shadow), Gravity.START); mDrawerToggle.setDrawerIndicatorEnabled(isDrawerEnabled()); // All the individual UI components listen for ViewMode changes. This // simplifies the amount of logic in the AbstractActivityController, but increases the // possibility of timing-related bugs. mViewMode.addListener(this); mPagerController = new ConversationPagerController(mActivity, this); mToastBar = (ActionableToastBar) mActivity.findViewById(R.id.toast_bar); attachActionBar(); FolderSelectionDialog.setDialogDismissed(); mDrawIdler.setRootView(mActivity.getWindow().getDecorView()); final Intent intent = mActivity.getIntent(); // Immediately handle a clean launch with intent, and any state restoration // that does not rely on restored fragments or loader data // any state restoration that relies on those can be done later in // onRestoreInstanceState, once fragments are up and loader data is re-delivered if (savedState != null) { if (savedState.containsKey(SAVED_ACCOUNT)) { setAccount((Account) savedState.getParcelable(SAVED_ACCOUNT)); } if (savedState.containsKey(SAVED_FOLDER)) { final Folder folder = savedState.getParcelable(SAVED_FOLDER); final String query = savedState.getString(SAVED_QUERY, null); setListContext(folder, query); } if (savedState.containsKey(SAVED_ACTION)) { mDialogAction = savedState.getInt(SAVED_ACTION); } mDialogFromSelectedSet = savedState.getBoolean(SAVED_ACTION_FROM_SELECTED, false); mViewMode.handleRestore(savedState); } else if (intent != null) { handleIntent(intent); } // Create the accounts loader; this loads the account switch spinner. mActivity.getLoaderManager().initLoader(LOADER_ACCOUNT_CURSOR, Bundle.EMPTY, mAccountCallbacks); return true; }
From source file:com.android.mail.ui.AbstractActivityController.java
/** * The application can be started from the following entry points: * <ul>// w ww. ja v a 2 s.co m * <li>Launcher: you tap on the Gmail icon in the launcher. This is what most users think of * as Starting the app?.</li> * <li>Shortcut: Users can make a shortcut to take them directly to a label.</li> * <li>Widget: Shows the contents of a synced label, and allows: * <ul> * <li>Viewing the list (tapping on the title)</li> * <li>Composing a new message (tapping on the new message icon in the title. This * launches the {@link ComposeActivity}. * </li> * <li>Viewing a single message (tapping on a list element)</li> * </ul> * * </li> * <li>Tapping on a notification: * <ul> * <li>Shows message list if more than one message</li> * <li>Shows the conversation if the notification is for a single message</li> * </ul> * </li> * <li>...and most importantly, the activity life cycle can tear down the application and * restart it: * <ul> * <li>Rotate the application: it is destroyed and recreated.</li> * <li>Navigate away, and return from recent applications.</li> * </ul> * </li> * <li>Add a new account: fires off an intent to add an account, * and returns in {@link #onActivityResult(int, int, android.content.Intent)} .</li> * <li>Re-authenticate your account: again returns in onActivityResult().</li> * <li>Composing can happen from many entry points: third party applications fire off an * intent to compose email, and launch directly into the {@link ComposeActivity} * .</li> * </ul> * {@inheritDoc} */ @Override public void onCreate(Bundle savedState) { initializeActionBar(); initializeDevLoggingService(); // Allow shortcut keys to function for the ActionBar and menus. mActivity.setDefaultKeyMode(Activity.DEFAULT_KEYS_SHORTCUT); mResolver = mActivity.getContentResolver(); mNewEmailReceiver = new SuppressNotificationReceiver(); mRecentFolderList.initialize(mActivity); mVeiledMatcher.initialize(this); mFloatingComposeButton = mActivity.findViewById(R.id.compose_button); mFloatingComposeButton.setOnClickListener(this); if (isDrawerEnabled()) { mDrawerToggle = new ActionBarDrawerToggle(mActivity, mDrawerContainer, R.string.drawer_open, R.string.drawer_close); mDrawerContainer.setDrawerListener(mDrawerListener); mDrawerContainer.setDrawerShadow(mContext.getResources().getDrawable(R.drawable.drawer_shadow), Gravity.START); // Disable default drawer indicator as we are setting the drawer indicator icons. // TODO(shahrk): Once we can disable/enable drawer animation, go back to using // drawer indicators. mDrawerToggle.setDrawerIndicatorEnabled(false); mDrawerToggle.setHomeAsUpIndicator(R.drawable.ic_menu_wht_24dp); } else { final ActionBar ab = mActivity.getSupportActionBar(); ab.setHomeAsUpIndicator(R.drawable.ic_menu_wht_24dp); ab.setHomeActionContentDescription(R.string.drawer_open); ab.setDisplayHomeAsUpEnabled(true); } // All the individual UI components listen for ViewMode changes. This // simplifies the amount of logic in the AbstractActivityController, but increases the // possibility of timing-related bugs. mViewMode.addListener(this); mPagerController = new ConversationPagerController(mActivity, this); mToastBar = findActionableToastBar(mActivity); attachActionBar(); mDrawIdler.setRootView(mActivity.getWindow().getDecorView()); final Intent intent = mActivity.getIntent(); mSearchViewController = new MaterialSearchViewController(mActivity, this, intent, savedState); addConversationListLayoutListener(mSearchViewController); // Immediately handle a clean launch with intent, and any state restoration // that does not rely on restored fragments or loader data // any state restoration that relies on those can be done later in // onRestoreInstanceState, once fragments are up and loader data is re-delivered if (savedState != null) { if (savedState.containsKey(SAVED_ACCOUNT)) { setAccount((Account) savedState.getParcelable(SAVED_ACCOUNT)); } if (savedState.containsKey(SAVED_FOLDER)) { final Folder folder = savedState.getParcelable(SAVED_FOLDER); final String query = savedState.getString(SAVED_QUERY, null); setListContext(folder, query); } if (savedState.containsKey(SAVED_ACTION)) { mDialogAction = savedState.getInt(SAVED_ACTION); } mDialogFromSelectedSet = savedState.getBoolean(SAVED_ACTION_FROM_SELECTED, false); mViewMode.handleRestore(savedState); } else if (intent != null) { handleIntent(intent); } // Create the accounts loader; this loads the account switch spinner. mActivity.getLoaderManager().initLoader(LOADER_ACCOUNT_CURSOR, Bundle.EMPTY, mAccountCallbacks); }
From source file:com.owncloud.android.authentication.AuthenticatorActivity.java
/** * {@inheritDoc}// w ww . j av a2s. co m * * IMPORTANT ENTRY POINT 1: activity is shown to the user */ @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); getWindow().requestFeature(Window.FEATURE_NO_TITLE); setContentView(R.layout.account_setup); mAuthMessage = (TextView) findViewById(R.id.auth_message); mHostUrlInput = (EditText) findViewById(R.id.hostUrlInput); mHostUrlInput.setText(getString(R.string.server_url)); // valid although // R.string.server_url // is an empty // string mUsernameInput = (EditText) findViewById(R.id.account_username); mPasswordInput = (EditText) findViewById(R.id.account_password); mPasswordInput2 = (EditText) findViewById(R.id.account_password2); mOAuthAuthEndpointText = (TextView) findViewById(R.id.oAuthEntryPoint_1); mOAuthTokenEndpointText = (TextView) findViewById(R.id.oAuthEntryPoint_2); mOAuth2Check = (CheckBox) findViewById(R.id.oauth_onOff_check); mOkButton = findViewById(R.id.buttonOK); mAuthStatusLayout = (TextView) findViewById(R.id.auth_status_text); // / set Host Url Input Enabled mHostUrlInputEnabled = getResources().getBoolean(R.bool.show_server_url_input); locationSpinner = (Spinner) findViewById(R.id.spinner1); // / complete label for 'register account' button Button b = (Button) findViewById(R.id.account_register); if (b != null) { b.setText(String.format(getString(R.string.auth_register), getString(R.string.app_name))); } // / initialization mAccountMgr = AccountManager.get(this); mNewCapturedUriFromOAuth2Redirection = null; mAction = getIntent().getByteExtra(EXTRA_ACTION, ACTION_CREATE); mAccount = null; mHostBaseUrl = ""; location = " ";//locationSpinner.getSelectedItem(); locationSpinner.setOnItemSelectedListener(this); boolean refreshButtonEnabled = false; // URL input configuration applied if (!mHostUrlInputEnabled) { findViewById(R.id.hostUrlFrame).setVisibility(View.GONE); mRefreshButton = findViewById(R.id.centeredRefreshButton); } else { mRefreshButton = findViewById(R.id.embeddedRefreshButton); } if (savedInstanceState == null) { mResumed = false; // / connection state and info mAuthMessageVisibility = View.GONE; mServerStatusText = mServerStatusIcon = 0; mServerIsValid = false; mServerIsChecked = false; mIsSslConn = false; mAuthStatusText = mAuthStatusIcon = 0; // / retrieve extras from intent mAccount = getIntent().getExtras().getParcelable(EXTRA_ACCOUNT); if (mAccount != null) { String ocVersion = mAccountMgr.getUserData(mAccount, AccountAuthenticator.KEY_OC_VERSION); Log.d("!!!!!!!!!!!!!!!!!!!!!!!!! ", mAccount.name); if (ocVersion != null) { mDiscoveredVersion = new OwnCloudVersion(ocVersion); } mHostBaseUrl = normalizeUrl( mAccountMgr.getUserData(mAccount, AccountAuthenticator.KEY_OC_BASE_URL)); mHostUrlInput.setText(mHostBaseUrl); String userName = mAccount.name.substring(0, mAccount.name.lastIndexOf('@')); Log.d("!!!!!!!!!!!!!!!!!!!!!!!!!4234 ", userName); mUsernameInput.setText(userName); } initAuthorizationMethod(); // checks intent and setup.xml to // determine mCurrentAuthorizationMethod mJustCreated = true; if (mAction == ACTION_UPDATE_TOKEN || !mHostUrlInputEnabled) { checkOcServer(); } } else { mResumed = true; // / connection state and info mAuthMessageVisibility = savedInstanceState.getInt(KEY_AUTH_MESSAGE_VISIBILITY); mAuthMessageText = savedInstanceState.getString(KEY_AUTH_MESSAGE_TEXT); mServerIsValid = savedInstanceState.getBoolean(KEY_SERVER_VALID); mServerIsChecked = savedInstanceState.getBoolean(KEY_SERVER_CHECKED); mServerStatusText = savedInstanceState.getInt(KEY_SERVER_STATUS_TEXT); mServerStatusIcon = savedInstanceState.getInt(KEY_SERVER_STATUS_ICON); mIsSslConn = savedInstanceState.getBoolean(KEY_IS_SSL_CONN); mAuthStatusText = savedInstanceState.getInt(KEY_AUTH_STATUS_TEXT); mAuthStatusIcon = savedInstanceState.getInt(KEY_AUTH_STATUS_ICON); if (savedInstanceState.getBoolean(KEY_PASSWORD_VISIBLE, false)) { showPassword(); } // / server data String ocVersion = savedInstanceState.getString(KEY_OC_VERSION); if (ocVersion != null) { mDiscoveredVersion = new OwnCloudVersion(ocVersion); } mHostBaseUrl = savedInstanceState.getString(KEY_HOST_URL_TEXT); // account data, if updating mAccount = savedInstanceState.getParcelable(KEY_ACCOUNT); // Log.d("////////////////// ",mAccount.name); mAuthTokenType = savedInstanceState.getString(AccountAuthenticator.KEY_AUTH_TOKEN_TYPE); if (mAuthTokenType == null) { mAuthTokenType = AccountAuthenticator.AUTH_TOKEN_TYPE_PASSWORD; } // check if server check was interrupted by a configuration change if (savedInstanceState.getBoolean(KEY_SERVER_CHECK_IN_PROGRESS, false)) { checkOcServer(); } // refresh button enabled refreshButtonEnabled = savedInstanceState.getBoolean(KEY_REFRESH_BUTTON_ENABLED); } if (mAuthMessageVisibility == View.VISIBLE) { showAuthMessage(mAuthMessageText); } else { hideAuthMessage(); } adaptViewAccordingToAuthenticationMethod(); showServerStatus(); showAuthStatus(); if (mAction == ACTION_UPDATE_TOKEN) { // / lock things that should not change mHostUrlInput.setEnabled(false); mHostUrlInput.setFocusable(false); mUsernameInput.setEnabled(false); mUsernameInput.setFocusable(false); mOAuth2Check.setVisibility(View.GONE); } // if (mServerIsChecked && !mServerIsValid && mRefreshButtonEnabled) // showRefreshButton(); if (mServerIsChecked && !mServerIsValid && refreshButtonEnabled) showRefreshButton(); mOkButton.setEnabled(mServerIsValid); // state not automatically // recovered in configuration // changes if (AccountAuthenticator.AUTH_TOKEN_TYPE_SAML_WEB_SSO_SESSION_COOKIE.equals(mAuthTokenType) || !AUTH_OPTIONAL.equals(getString(R.string.auth_method_oauth2))) { mOAuth2Check.setVisibility(View.GONE); } mPasswordInput.setText(""); // clean password to avoid social hacking // (disadvantage: password in removed if the // device is turned aside) // / bind view elements to listeners and other friends mHostUrlInput.setOnFocusChangeListener(this); mHostUrlInput.setImeOptions(EditorInfo.IME_ACTION_NEXT); mHostUrlInput.setOnEditorActionListener(this); mHostUrlInput.addTextChangedListener(new TextWatcher() { @Override public void afterTextChanged(Editable s) { if (!mHostBaseUrl.equals(normalizeUrl(mHostUrlInput.getText().toString()))) { mOkButton.setEnabled(false); } } @Override public void beforeTextChanged(CharSequence s, int start, int count, int after) { } @Override public void onTextChanged(CharSequence s, int start, int before, int count) { if (!mResumed) { mAuthStatusIcon = 0; mAuthStatusText = 0; showAuthStatus(); } mResumed = false; } }); mPasswordInput.setOnFocusChangeListener(this); mPasswordInput.setImeOptions(EditorInfo.IME_ACTION_DONE); mPasswordInput.setOnEditorActionListener(this); mPasswordInput.setOnTouchListener(new RightDrawableOnTouchListener() { @Override public boolean onDrawableTouch(final MotionEvent event) { if (event.getAction() == MotionEvent.ACTION_UP) { AuthenticatorActivity.this.onViewPasswordClick(); } return true; } }); findViewById(R.id.scroll).setOnTouchListener(new OnTouchListener() { @Override public boolean onTouch(View view, MotionEvent event) { if (event.getAction() == MotionEvent.ACTION_DOWN) { if (AccountAuthenticator.AUTH_TOKEN_TYPE_SAML_WEB_SSO_SESSION_COOKIE.equals(mAuthTokenType) && mHostUrlInput.hasFocus()) { checkOcServer(); } } return false; } }); }
From source file:android.app.Activity.java
/** * Called when the activity is starting. This is where most initialization * should go: calling {@link #setContentView(int)} to inflate the * activity's UI, using {@link #findViewById} to programmatically interact * with widgets in the UI, calling//ww w. j a v a 2 s . c o m * {@link #managedQuery(android.net.Uri , String[], String, String[], String)} to retrieve * cursors for data being displayed, etc. * * <p>You can call {@link #finish} from within this function, in * which case onDestroy() will be immediately called without any of the rest * of the activity lifecycle ({@link #onStart}, {@link #onResume}, * {@link #onPause}, etc) executing. * * <p><em>Derived classes must call through to the super class's * implementation of this method. If they do not, an exception will be * thrown.</em></p> * * @param savedInstanceState If the activity is being re-initialized after * previously being shut down then this Bundle contains the data it most * recently supplied in {@link #onSaveInstanceState}. <b><i>Note: Otherwise it is null.</i></b> * * @see #onStart * @see #onSaveInstanceState * @see #onRestoreInstanceState * @see #onPostCreate */ protected void onCreate(Bundle savedInstanceState) { if (DEBUG_LIFECYCLE) Slog.v(TAG, "onCreate " + this + ": " + savedInstanceState); if (mLastNonConfigurationInstances != null) { mAllLoaderManagers = mLastNonConfigurationInstances.loaders; } if (mActivityInfo.parentActivityName != null) { if (mActionBar == null) { mEnableDefaultActionBarUp = true; } else { mActionBar.setDefaultDisplayHomeAsUpEnabled(true); } } if (isAvailable()) { /* if this device can use the platform */ Log.w("MIGRATOR", "This is " + getLocalClassName()); Intent intent = getIntent(); Bundle tmpBundle = intent.getBundleExtra("MIGRATED"); ArrayList<Bundle> stacked = intent.getParcelableArrayListExtra("MIGRATED STACK"); if (tmpBundle != null) { /* true if this Activity was migrated */ if (stacked != null) { /* true if this Activity called next Activity */ Intent next = new Intent(); Bundle nextBundle = stacked.get(0); next.setClassName(nextBundle.getString("MIGRATED PNAME"), nextBundle.getString("MIGRATED CNAME")); next.putExtra("MIGRATED", nextBundle); stacked.remove(0); int code = tmpBundle.getInt("MIGRATED REQUEST CODE"); Bundle option = nextBundle.getBundle("MIGRATED REQUEST OPTIONS"); if (!stacked.isEmpty()) { /* store for next Activity */ next.putParcelableArrayListExtra("MIGRATED STACK", stacked); } Log.w("MIGRATOR", "Start ForResult: code=" + code); mReceiverStackFlag = true; mStackedNextIntent = next; mStackedNextCode = code; mStackedNextOption = option; } else { /* for debug */ Log.w("MIGRATOR", "stack is null"); } savedInstanceState = null; mMigFlag = true; migratedState = tmpBundle; Intent tmpIntent = tmpBundle.getParcelable("MIGRATED_INTENT"); if (tmpIntent != null) { tmpIntent.setAction(Intent.ACTION_MIGRATE); setIntent(tmpIntent); } /* File handling */ ArrayList<String> tmpNames = tmpBundle.getStringArrayList("TARGET_FILE_NAME"); if (tmpNames != null) { FileWorker fw = new FileWorker(tmpNames.toArray(new String[tmpNames.size()]), FileWorker.WRITE_MODE); fw.start(); tmpNames = null; } Log.w("MIGRATOR", "successed migaration: " + tmpBundle.toString()); tmpBundle = null; } else { /* for debug */ Log.w("MIGRATOR", "tmpBundle is null"); } } if (savedInstanceState != null) { Parcelable p = savedInstanceState.getParcelable(FRAGMENTS_TAG); mFragments.restoreAllState(p, mLastNonConfigurationInstances != null ? mLastNonConfigurationInstances.fragments : null); } mFragments.dispatchCreate(); getApplication().dispatchActivityCreated(this, savedInstanceState); mCalled = true; }
From source file:androidx.media.MediaSession2StubImplBase.java
@Override public void onCommand(String command, final Bundle extras, final ResultReceiver cb) { switch (command) { case CONTROLLER_COMMAND_CONNECT: connect(extras, cb);/*from w ww.j av a 2 s . c om*/ break; case CONTROLLER_COMMAND_DISCONNECT: disconnect(extras); break; case CONTROLLER_COMMAND_BY_COMMAND_CODE: { final int commandCode = extras.getInt(ARGUMENT_COMMAND_CODE); IMediaControllerCallback caller = (IMediaControllerCallback) extras .getBinder(ARGUMENT_ICONTROLLER_CALLBACK); if (caller == null) { return; } onCommand2(caller.asBinder(), commandCode, new Session2Runnable() { @Override public void run(ControllerInfo controller) { switch (commandCode) { case COMMAND_CODE_PLAYBACK_PLAY: mSession.play(); break; case COMMAND_CODE_PLAYBACK_PAUSE: mSession.pause(); break; case COMMAND_CODE_PLAYBACK_RESET: mSession.reset(); break; case COMMAND_CODE_PLAYBACK_PREPARE: mSession.prepare(); break; case COMMAND_CODE_PLAYBACK_SEEK_TO: { long seekPos = extras.getLong(ARGUMENT_SEEK_POSITION); mSession.seekTo(seekPos); break; } case COMMAND_CODE_PLAYLIST_SET_REPEAT_MODE: { int repeatMode = extras.getInt(ARGUMENT_REPEAT_MODE); mSession.setRepeatMode(repeatMode); break; } case COMMAND_CODE_PLAYLIST_SET_SHUFFLE_MODE: { int shuffleMode = extras.getInt(ARGUMENT_SHUFFLE_MODE); mSession.setShuffleMode(shuffleMode); break; } case COMMAND_CODE_PLAYLIST_SET_LIST: { List<MediaItem2> list = MediaUtils2 .fromMediaItem2ParcelableArray(extras.getParcelableArray(ARGUMENT_PLAYLIST)); MediaMetadata2 metadata = MediaMetadata2 .fromBundle(extras.getBundle(ARGUMENT_PLAYLIST_METADATA)); mSession.setPlaylist(list, metadata); break; } case COMMAND_CODE_PLAYLIST_SET_LIST_METADATA: { MediaMetadata2 metadata = MediaMetadata2 .fromBundle(extras.getBundle(ARGUMENT_PLAYLIST_METADATA)); mSession.updatePlaylistMetadata(metadata); break; } case COMMAND_CODE_PLAYLIST_ADD_ITEM: { int index = extras.getInt(ARGUMENT_PLAYLIST_INDEX); MediaItem2 item = MediaItem2.fromBundle(extras.getBundle(ARGUMENT_MEDIA_ITEM)); mSession.addPlaylistItem(index, item); break; } case COMMAND_CODE_PLAYLIST_REMOVE_ITEM: { MediaItem2 item = MediaItem2.fromBundle(extras.getBundle(ARGUMENT_MEDIA_ITEM)); mSession.removePlaylistItem(item); break; } case COMMAND_CODE_PLAYLIST_REPLACE_ITEM: { int index = extras.getInt(ARGUMENT_PLAYLIST_INDEX); MediaItem2 item = MediaItem2.fromBundle(extras.getBundle(ARGUMENT_MEDIA_ITEM)); mSession.replacePlaylistItem(index, item); break; } case COMMAND_CODE_PLAYLIST_SKIP_TO_NEXT_ITEM: { mSession.skipToNextItem(); break; } case COMMAND_CODE_PLAYLIST_SKIP_TO_PREV_ITEM: { mSession.skipToPreviousItem(); break; } case COMMAND_CODE_PLAYLIST_SKIP_TO_PLAYLIST_ITEM: { MediaItem2 item = MediaItem2.fromBundle(extras.getBundle(ARGUMENT_MEDIA_ITEM)); mSession.skipToPlaylistItem(item); break; } case COMMAND_CODE_VOLUME_SET_VOLUME: { int value = extras.getInt(ARGUMENT_VOLUME); int flags = extras.getInt(ARGUMENT_VOLUME_FLAGS); VolumeProviderCompat vp = mSession.getVolumeProvider(); if (vp == null) { // TODO: Revisit } else { vp.onSetVolumeTo(value); } break; } case COMMAND_CODE_VOLUME_ADJUST_VOLUME: { int direction = extras.getInt(ARGUMENT_VOLUME_DIRECTION); int flags = extras.getInt(ARGUMENT_VOLUME_FLAGS); VolumeProviderCompat vp = mSession.getVolumeProvider(); if (vp == null) { // TODO: Revisit } else { vp.onAdjustVolume(direction); } break; } case COMMAND_CODE_SESSION_REWIND: { mSession.getCallback().onRewind(mSession.getInstance(), controller); break; } case COMMAND_CODE_SESSION_FAST_FORWARD: { mSession.getCallback().onFastForward(mSession.getInstance(), controller); break; } case COMMAND_CODE_SESSION_PLAY_FROM_MEDIA_ID: { String mediaId = extras.getString(ARGUMENT_MEDIA_ID); Bundle extra = extras.getBundle(ARGUMENT_EXTRAS); mSession.getCallback().onPlayFromMediaId(mSession.getInstance(), controller, mediaId, extra); break; } case COMMAND_CODE_SESSION_PLAY_FROM_SEARCH: { String query = extras.getString(ARGUMENT_QUERY); Bundle extra = extras.getBundle(ARGUMENT_EXTRAS); mSession.getCallback().onPlayFromSearch(mSession.getInstance(), controller, query, extra); break; } case COMMAND_CODE_SESSION_PLAY_FROM_URI: { Uri uri = extras.getParcelable(ARGUMENT_URI); Bundle extra = extras.getBundle(ARGUMENT_EXTRAS); mSession.getCallback().onPlayFromUri(mSession.getInstance(), controller, uri, extra); break; } case COMMAND_CODE_SESSION_PREPARE_FROM_MEDIA_ID: { String mediaId = extras.getString(ARGUMENT_MEDIA_ID); Bundle extra = extras.getBundle(ARGUMENT_EXTRAS); mSession.getCallback().onPrepareFromMediaId(mSession.getInstance(), controller, mediaId, extra); break; } case COMMAND_CODE_SESSION_PREPARE_FROM_SEARCH: { String query = extras.getString(ARGUMENT_QUERY); Bundle extra = extras.getBundle(ARGUMENT_EXTRAS); mSession.getCallback().onPrepareFromSearch(mSession.getInstance(), controller, query, extra); break; } case COMMAND_CODE_SESSION_PREPARE_FROM_URI: { Uri uri = extras.getParcelable(ARGUMENT_URI); Bundle extra = extras.getBundle(ARGUMENT_EXTRAS); mSession.getCallback().onPrepareFromUri(mSession.getInstance(), controller, uri, extra); break; } case COMMAND_CODE_SESSION_SET_RATING: { String mediaId = extras.getString(ARGUMENT_MEDIA_ID); Rating2 rating = Rating2.fromBundle(extras.getBundle(ARGUMENT_RATING)); mSession.getCallback().onSetRating(mSession.getInstance(), controller, mediaId, rating); break; } case COMMAND_CODE_SESSION_SUBSCRIBE_ROUTES_INFO: { mSession.getCallback().onSubscribeRoutesInfo(mSession.getInstance(), controller); break; } case COMMAND_CODE_SESSION_UNSUBSCRIBE_ROUTES_INFO: { mSession.getCallback().onUnsubscribeRoutesInfo(mSession.getInstance(), controller); break; } case COMMAND_CODE_SESSION_SELECT_ROUTE: { Bundle route = extras.getBundle(ARGUMENT_ROUTE_BUNDLE); mSession.getCallback().onSelectRoute(mSession.getInstance(), controller, route); break; } case COMMAND_CODE_PLAYBACK_SET_SPEED: { float speed = extras.getFloat(ARGUMENT_PLAYBACK_SPEED); mSession.setPlaybackSpeed(speed); break; } } } }); break; } case CONTROLLER_COMMAND_BY_CUSTOM_COMMAND: { final SessionCommand2 customCommand = SessionCommand2 .fromBundle(extras.getBundle(ARGUMENT_CUSTOM_COMMAND)); IMediaControllerCallback caller = (IMediaControllerCallback) extras .getBinder(ARGUMENT_ICONTROLLER_CALLBACK); if (caller == null || customCommand == null) { return; } final Bundle args = extras.getBundle(ARGUMENT_ARGUMENTS); onCommand2(caller.asBinder(), customCommand, new Session2Runnable() { @Override public void run(ControllerInfo controller) throws RemoteException { mSession.getCallback().onCustomCommand(mSession.getInstance(), controller, customCommand, args, cb); } }); break; } } }
From source file:com.android.contacts.ContactSaveService.java
private void saveContact(Intent intent) { RawContactDeltaList state = intent.getParcelableExtra(EXTRA_CONTACT_STATE); boolean isProfile = intent.getBooleanExtra(EXTRA_SAVE_IS_PROFILE, false); Bundle updatedPhotos = intent.getParcelableExtra(EXTRA_UPDATED_PHOTOS); if (state == null) { Log.e(TAG, "Invalid arguments for saveContact request"); return;//from w ww. j av a 2s . c o m } int saveMode = intent.getIntExtra(EXTRA_SAVE_MODE, -1); // Trim any empty fields, and RawContacts, before persisting final AccountTypeManager accountTypes = AccountTypeManager.getInstance(this); RawContactModifier.trimEmpty(state, accountTypes); Uri lookupUri = null; final ContentResolver resolver = getContentResolver(); boolean succeeded = false; // Keep track of the id of a newly raw-contact (if any... there can be at most one). long insertedRawContactId = -1; // Attempt to persist changes int tries = 0; while (tries++ < PERSIST_TRIES) { try { // Build operations and try applying final ArrayList<CPOWrapper> diffWrapper = state.buildDiffWrapper(); final ArrayList<ContentProviderOperation> diff = Lists.newArrayList(); for (CPOWrapper cpoWrapper : diffWrapper) { diff.add(cpoWrapper.getOperation()); } if (DEBUG) { Log.v(TAG, "Content Provider Operations:"); for (ContentProviderOperation operation : diff) { Log.v(TAG, operation.toString()); } } int numberProcessed = 0; boolean batchFailed = false; final ContentProviderResult[] results = new ContentProviderResult[diff.size()]; while (numberProcessed < diff.size()) { final int subsetCount = applyDiffSubset(diff, numberProcessed, results, resolver); if (subsetCount == -1) { Log.w(TAG, "Resolver.applyBatch failed in saveContacts"); batchFailed = true; break; } else { numberProcessed += subsetCount; } } if (batchFailed) { // Retry save continue; } final long rawContactId = getRawContactId(state, diffWrapper, results); if (rawContactId == -1) { throw new IllegalStateException("Could not determine RawContact ID after save"); } // We don't have to check to see if the value is still -1. If we reach here, // the previous loop iteration didn't succeed, so any ID that we obtained is bogus. insertedRawContactId = getInsertedRawContactId(diffWrapper, results); if (isProfile) { // Since the profile supports local raw contacts, which may have been completely // removed if all information was removed, we need to do a special query to // get the lookup URI for the profile contact (if it still exists). Cursor c = resolver.query(Profile.CONTENT_URI, new String[] { Contacts._ID, Contacts.LOOKUP_KEY }, null, null, null); if (c == null) { continue; } try { if (c.moveToFirst()) { final long contactId = c.getLong(0); final String lookupKey = c.getString(1); lookupUri = Contacts.getLookupUri(contactId, lookupKey); } } finally { c.close(); } } else { final Uri rawContactUri = ContentUris.withAppendedId(RawContacts.CONTENT_URI, rawContactId); lookupUri = RawContacts.getContactLookupUri(resolver, rawContactUri); } if (lookupUri != null && Log.isLoggable(TAG, Log.VERBOSE)) { Log.v(TAG, "Saved contact. New URI: " + lookupUri); } // We can change this back to false later, if we fail to save the contact photo. succeeded = true; break; } catch (RemoteException e) { // Something went wrong, bail without success FeedbackHelper.sendFeedback(this, TAG, "Problem persisting user edits", e); break; } catch (IllegalArgumentException e) { // This is thrown by applyBatch on malformed requests FeedbackHelper.sendFeedback(this, TAG, "Problem persisting user edits", e); showToast(R.string.contactSavedErrorToast); break; } catch (OperationApplicationException e) { // Version consistency failed, re-parent change and try again Log.w(TAG, "Version consistency failed, re-parenting: " + e.toString()); final StringBuilder sb = new StringBuilder(RawContacts._ID + " IN("); boolean first = true; final int count = state.size(); for (int i = 0; i < count; i++) { Long rawContactId = state.getRawContactId(i); if (rawContactId != null && rawContactId != -1) { if (!first) { sb.append(','); } sb.append(rawContactId); first = false; } } sb.append(")"); if (first) { throw new IllegalStateException("Version consistency failed for a new contact", e); } final RawContactDeltaList newState = RawContactDeltaList.fromQuery( isProfile ? RawContactsEntity.PROFILE_CONTENT_URI : RawContactsEntity.CONTENT_URI, resolver, sb.toString(), null, null); state = RawContactDeltaList.mergeAfter(newState, state); // Update the new state to use profile URIs if appropriate. if (isProfile) { for (RawContactDelta delta : state) { delta.setProfileQueryUri(); } } } } // Now save any updated photos. We do this at the end to ensure that // the ContactProvider already knows about newly-created contacts. if (updatedPhotos != null) { for (String key : updatedPhotos.keySet()) { Uri photoUri = updatedPhotos.getParcelable(key); long rawContactId = Long.parseLong(key); // If the raw-contact ID is negative, we are saving a new raw-contact; // replace the bogus ID with the new one that we actually saved the contact at. if (rawContactId < 0) { rawContactId = insertedRawContactId; } // If the save failed, insertedRawContactId will be -1 if (rawContactId < 0 || !saveUpdatedPhoto(rawContactId, photoUri, saveMode)) { succeeded = false; } } } Intent callbackIntent = intent.getParcelableExtra(EXTRA_CALLBACK_INTENT); if (callbackIntent != null) { if (succeeded) { // Mark the intent to indicate that the save was successful (even if the lookup URI // is now null). For local contacts or the local profile, it's possible that the // save triggered removal of the contact, so no lookup URI would exist.. callbackIntent.putExtra(EXTRA_SAVE_SUCCEEDED, true); } callbackIntent.setData(lookupUri); deliverCallback(callbackIntent); } }
From source file:com.android.gallery3d.app.PhotoPage.java
@Override public void onCreate(Bundle data, Bundle restoreState) { super.onCreate(data, restoreState); mActionBar = mActivity.getGalleryActionBar(); mSelectionManager = new SelectionManager(mActivity, false); mMenuExecutor = new MenuExecutor(mActivity, mSelectionManager); mPhotoView = new PhotoView(mActivity); mPhotoView.setListener(this); mRootPane.addComponent(mPhotoView);/*from w ww .j ava 2 s .c om*/ mApplication = (GalleryApp) ((Activity) mActivity).getApplication(); mOrientationManager = mActivity.getOrientationManager(); mActivity.getGLRoot().setOrientationSource(mOrientationManager); mHandler = new SynchronizedHandler(mActivity.getGLRoot()) { @Override public void handleMessage(Message message) { switch (message.what) { case MSG_HIDE_BARS: { /// M: [BUG.MODIFY] @{ /* hideBars(); */ if (mIsActive) { hideBars(); } else { Log.i(TAG, "<mHandler.MSG_HIDE_BARS> mIsActive = " + mIsActive + ", not hideBars"); } /// @} break; } case MSG_REFRESH_BOTTOM_CONTROLS: { if (mCurrentPhoto == message.obj && mBottomControls != null) { mIsPanorama = message.arg1 == 1; mIsPanorama360 = message.arg2 == 1; mBottomControls.refresh(); fresh(mBottomControls.getContainerVisibility()); } break; } case MSG_ON_FULL_SCREEN_CHANGED: { if (mAppBridge != null) { mAppBridge.onFullScreenChanged(message.arg1 == 1); } break; } case MSG_UPDATE_ACTION_BAR: { updateBars(); break; } case MSG_WANT_BARS: { wantBars(); break; } case MSG_UNFREEZE_GLROOT: { mActivity.getGLRoot().unfreeze(); break; } case MSG_UPDATE_DEFERRED: { long nextUpdate = mDeferUpdateUntil - SystemClock.uptimeMillis(); if (nextUpdate <= 0) { mDeferredUpdateWaiting = false; updateUIForCurrentPhoto(); } else { mHandler.sendEmptyMessageDelayed(MSG_UPDATE_DEFERRED, nextUpdate); } break; } case MSG_ON_CAMERA_CENTER: { mSkipUpdateCurrentPhoto = false; boolean stayedOnCamera = false; if (!mPhotoView.getFilmMode()) { stayedOnCamera = true; } else if (SystemClock.uptimeMillis() < mCameraSwitchCutoff && mMediaSet.getMediaItemCount() > 1) { mPhotoView.switchToImage(1); } else { if (mAppBridge != null) mPhotoView.setFilmMode(false); stayedOnCamera = true; } if (stayedOnCamera) { if (mAppBridge == null && mMediaSet.getTotalMediaItemCount() > 1) { launchCamera(); /// M: [FEATURE.ADD] @{ mPhotoView.stopUpdateEngineData(); /// @} /* We got here by swiping from photo 1 to the placeholder, so make it be the thing that is in focus when the user presses back from the camera app */ mPhotoView.switchToImage(1); } else { updateBars(); /// M: [BUG.MODIFY] getMediaItem(0) may be null, fix JE @{ /*updateCurrentPhoto(mModel.getMediaItem(0));*/ MediaItem photo = mModel.getMediaItem(0); if (photo != null) { updateCurrentPhoto(photo); } /// @} } } break; } case MSG_ON_PICTURE_CENTER: { if (!mPhotoView.getFilmMode() && mCurrentPhoto != null && (mCurrentPhoto.getSupportedOperations() & MediaObject.SUPPORT_ACTION) != 0) { /// M: [BUG.MODIFY] @{ /*mPhotoView.setFilmMode(true);*/ showEmptyAlbumToast(Toast.LENGTH_SHORT); /// @} } break; } case MSG_REFRESH_IMAGE: { final MediaItem photo = mCurrentPhoto; mCurrentPhoto = null; updateCurrentPhoto(photo); break; } case MSG_UPDATE_PHOTO_UI: { updateUIForCurrentPhoto(); break; } case MSG_UPDATE_SHARE_URI: { /// M: [BUG.ADD] @{ // never update share uri when PhotoPage is not active if (!mIsActive) { break; } /// @} /// M: [BUG.MARK] @{ // No matter what message.obj is, we update share intent for current photo /* if (mCurrentPhoto == message.obj) {*/ /// @} boolean isPanorama360 = message.arg1 != 0; Uri contentUri = mCurrentPhoto.getContentUri(); Intent panoramaIntent = null; if (isPanorama360) { panoramaIntent = createSharePanoramaIntent(contentUri); } Intent shareIntent = createShareIntent(mCurrentPhoto); mActionBar.setShareIntents(panoramaIntent, shareIntent, PhotoPage.this); setNfcBeamPushUri(contentUri); /// M: [BUG.MARK] @{ // } /// @} break; } case MSG_UPDATE_PANORAMA_UI: { if (mCurrentPhoto == message.obj) { boolean isPanorama360 = message.arg1 != 0; updatePanoramaUI(isPanorama360); } break; } default: throw new AssertionError(message.what); } } }; mSetPathString = data.getString(KEY_MEDIA_SET_PATH); /// M: [FEATURE.ADD] [Camera independent from Gallery] @{ mLaunchFromCamera = data.getBoolean(KEY_LAUNCH_FROM_CAMERA, false); /// @} /// M: [BUG.MODIFY] @{ // if there is mSetPathString, view is not read only, enable edit /*mReadOnlyView = data.getBoolean(KEY_READONLY);*/ mReadOnlyView = data.getBoolean(KEY_READONLY) && (mSetPathString == null || mSetPathString.equals("")); Log.i(TAG, "<onCreate> mSetPathString = " + mSetPathString + ", mReadOnlyView = " + mReadOnlyView); /// @} mOriginalSetPathString = mSetPathString; setupNfcBeamPush(); String itemPathString = data.getString(KEY_MEDIA_ITEM_PATH); Path itemPath = itemPathString != null ? Path.fromString(data.getString(KEY_MEDIA_ITEM_PATH)) : null; mTreatBackAsUp = data.getBoolean(KEY_TREAT_BACK_AS_UP, false); mStartInFilmstrip = data.getBoolean(KEY_START_IN_FILMSTRIP, false); boolean inCameraRoll = data.getBoolean(KEY_IN_CAMERA_ROLL, false); mCurrentIndex = data.getInt(KEY_INDEX_HINT, 0); if (mSetPathString != null) { mShowSpinner = true; /// M: [FEATURE.ADD] [Camera independent from Gallery] @{ // Launch from secure camera if (!mSetPathString.equals("/local/all/0") && SecureSource.isSecurePath(mSetPathString)) { Log.d(TAG, "<onCreate> secure album"); mFlags |= FLAG_SHOW_WHEN_LOCKED; mSecureAlbum = (SecureAlbum) mActivity.getDataManager().getMediaSet(mSetPathString); mSecureAlbum.clearAll(); ArrayList<String> secureAlbum = (ArrayList<String>) data.getSerializable(SECURE_ALBUM); if (secureAlbum != null) { int albumCount = secureAlbum.size(); Log.d(TAG, "<onCreate> albumCount " + albumCount); for (int i = 0; i < albumCount; i++) { try { String[] albumItem = secureAlbum.get(i).split("\\+"); int albumItemSize = albumItem.length; Log.d(TAG, "<onCreate> albumItemSize " + albumItemSize); if (albumItemSize == 2) { int id = Integer.parseInt(albumItem[0].trim()); boolean isVideo = Boolean.parseBoolean(albumItem[1].trim()); Log.d(TAG, "<onCreate> secure item : id " + id + ", isVideo " + isVideo); mSecureAlbum.addMediaItem(isVideo, id); } } catch (NullPointerException ex) { Log.e(TAG, "<onCreate> exception " + ex); } catch (PatternSyntaxException ex) { Log.e(TAG, "<onCreate> exception " + ex); } catch (NumberFormatException ex) { Log.e(TAG, "<onCreate> exception " + ex); } } } mShowSpinner = false; mSetPathString = "/filter/empty/{" + mSetPathString + "}"; mSetPathString = "/combo/item/{" + mSetPathString + "}"; } /// @} mAppBridge = (AppBridge) data.getParcelable(KEY_APP_BRIDGE); if (mAppBridge != null) { mShowBars = false; mHasCameraScreennailOrPlaceholder = true; mAppBridge.setServer(this); // Get the ScreenNail from AppBridge and register it. int id = SnailSource.newId(); Path screenNailSetPath = SnailSource.getSetPath(id); Path screenNailItemPath = SnailSource.getItemPath(id); mScreenNailSet = (SnailAlbum) mActivity.getDataManager().getMediaObject(screenNailSetPath); mScreenNailItem = (SnailItem) mActivity.getDataManager().getMediaObject(screenNailItemPath); mScreenNailItem.setScreenNail(mAppBridge.attachScreenNail()); if (data.getBoolean(KEY_SHOW_WHEN_LOCKED, false)) { // Set the flag to be on top of the lock screen. mFlags |= FLAG_SHOW_WHEN_LOCKED; } // Don't display "empty album" action item for capture intents. if (!mSetPathString.equals("/local/all/0")) { // Check if the path is a secure album. if (SecureSource.isSecurePath(mSetPathString)) { mSecureAlbum = (SecureAlbum) mActivity.getDataManager().getMediaSet(mSetPathString); mShowSpinner = false; } mSetPathString = "/filter/empty/{" + mSetPathString + "}"; } // Combine the original MediaSet with the one for ScreenNail // from AppBridge. mSetPathString = "/combo/item/{" + screenNailSetPath + "," + mSetPathString + "}"; // Start from the screen nail. itemPath = screenNailItemPath; /// M: [FEATURE.MARK] [Camera independent from Gallery] @{ // After camera is removed from gallery, modify the behavior as below: // When view the first image in camera folder, slide to left, // there is no place holder of camera, and it can not launch camera too. /*} else if (inCameraRoll && GalleryUtils.isCameraAvailable(mActivity)) { mSetPathString = "/combo/item/{" + FilterSource.FILTER_CAMERA_SHORTCUT + "," + mSetPathString + "}"; mCurrentIndex++; mHasCameraScreennailOrPlaceholder = true;*/ /// @} /// M: [FEATURE.ADD] [Camera independent from Gallery] @{ // When launch from camera, and not from secure camera, we show empty item // after delete all images. } else if (mLaunchFromCamera && mSecureAlbum == null) { mSetPathString = "/filter/empty/{" + mSetPathString + "}"; Log.i(TAG, "<onCreate> launch from camera, not secure, mSetPathString = " + mSetPathString); /// @} } MediaSet originalSet = mActivity.getDataManager().getMediaSet(mSetPathString); if (mHasCameraScreennailOrPlaceholder && originalSet instanceof ComboAlbum) { // Use the name of the camera album rather than the default // ComboAlbum behavior ((ComboAlbum) originalSet).useNameOfChild(1); } /// M: [BUG.ADD] @{ // tell PhotoView whether this album is cluster if (originalSet != null && originalSet instanceof ClusterAlbum) { mPhotoView.setIsCluster(true); } else { mPhotoView.setIsCluster(false); } /// @} mSelectionManager.setSourceMediaSet(originalSet); mSetPathString = "/filter/delete/{" + mSetPathString + "}"; mMediaSet = (FilterDeleteSet) mActivity.getDataManager().getMediaSet(mSetPathString); if (mMediaSet == null) { Log.w(TAG, "failed to restore " + mSetPathString); } if (itemPath == null) { int mediaItemCount = mMediaSet.getMediaItemCount(); if (mediaItemCount > 0) { if (mCurrentIndex >= mediaItemCount) mCurrentIndex = 0; itemPath = mMediaSet.getMediaItem(mCurrentIndex, 1).get(0).getPath(); } else { // Bail out, PhotoPage can't load on an empty album return; } } PhotoDataAdapter pda = new PhotoDataAdapter(mActivity, mPhotoView, mMediaSet, itemPath, mCurrentIndex, mAppBridge == null ? -1 : 0, mAppBridge == null ? false : mAppBridge.isPanorama(), mAppBridge == null ? false : mAppBridge.isStaticCamera()); mModel = pda; mPhotoView.setModel(mModel); pda.setDataListener(new PhotoDataAdapter.DataListener() { @Override public void onPhotoChanged(int index, Path item) { int oldIndex = mCurrentIndex; mCurrentIndex = index; if (mHasCameraScreennailOrPlaceholder) { if (mCurrentIndex > 0) { mSkipUpdateCurrentPhoto = false; } /// M: [FEATURE.MODIFY] @{ /*if (oldIndex == 0 && mCurrentIndex > 0 && !mPhotoView.getFilmMode()) { mPhotoView.setFilmMode(true);*/ if (oldIndex == 0 && mCurrentIndex > 0) { onActionBarAllowed(true); mPhotoView.setFilmMode(false); /// @} if (mAppBridge != null) { UsageStatistics.onEvent("CameraToFilmstrip", UsageStatistics.TRANSITION_SWIPE, null); } } else if (oldIndex == 2 && mCurrentIndex == 1) { mCameraSwitchCutoff = SystemClock.uptimeMillis() + CAMERA_SWITCH_CUTOFF_THRESHOLD_MS; mPhotoView.stopScrolling(); } else if (oldIndex >= 1 && mCurrentIndex == 0) { mPhotoView.setWantPictureCenterCallbacks(true); mSkipUpdateCurrentPhoto = true; } } if (!mSkipUpdateCurrentPhoto) { if (item != null) { MediaItem photo = mModel.getMediaItem(0); if (photo != null) updateCurrentPhoto(photo); } updateBars(); } // Reset the timeout for the bars after a swipe /// M: [DEBUG.ADD] @{ Log.i(TAG, "<onPhotoChanged> refreshHidingMessage"); /// @} refreshHidingMessage(); } @Override public void onLoadingFinished(boolean loadingFailed) { /// M: [BUG.ADD] @{ mLoadingFinished = true; // Refresh bottom controls when data loading done refreshBottomControlsWhenReady(); /// @} if (!mModel.isEmpty()) { MediaItem photo = mModel.getMediaItem(0); if (photo != null) updateCurrentPhoto(photo); } else if (mIsActive) { // We only want to finish the PhotoPage if there is no // deletion that the user can undo. if (mMediaSet.getNumberOfDeletions() == 0) { /// M: [BUG.ADD] pause PhotoView before finish PhotoPage @{ mPhotoView.pause(); /// @} mActivity.getStateManager().finishState(PhotoPage.this); } } } @Override public void onLoadingStarted() { /// M: [BUG.ADD] @{ mLoadingFinished = false; /// @} } }); } else { // Get default media set by the URI MediaItem mediaItem = (MediaItem) mActivity.getDataManager().getMediaObject(itemPath); /// M: [BUG.ADD] fix JE when mediaItem is deleted@{ if (mediaItem == null) { Toast.makeText(((Activity) mActivity), R.string.no_such_item, Toast.LENGTH_LONG).show(); mPhotoView.pause(); mActivity.getStateManager().finishState(this); return; } /// @} /// M: [BUG.ADD] @{ // no PhotoDataAdapter style loading in SinglePhotoDataAdapter mLoadingFinished = true; /// @} mModel = new SinglePhotoDataAdapter(mActivity, mPhotoView, mediaItem); mPhotoView.setModel(mModel); updateCurrentPhoto(mediaItem); mShowSpinner = false; } mPhotoView.setFilmMode(mStartInFilmstrip && mMediaSet.getMediaItemCount() > 1); RelativeLayout galleryRoot = (RelativeLayout) ((Activity) mActivity) .findViewById(mAppBridge != null ? R.id.content : R.id.gallery_root); if (galleryRoot != null) { if (mSecureAlbum == null) { mBottomControls = new PhotoPageBottomControls(this, mActivity, galleryRoot); } } /// M: [BUG.MODIFY] set change listener to current GLRootView @{ // onResume also need to set this listener, so modify it. /*((GLRootView) mActivity.getGLRoot()).setOnSystemUiVisibilityChangeListener( new View.OnSystemUiVisibilityChangeListener() { @Override public void onSystemUiVisibilityChange(int visibility) { int diff = mLastSystemUiVis ^ visibility; mLastSystemUiVis = visibility; if ((diff & View.SYSTEM_UI_FLAG_FULLSCREEN) != 0 && (visibility & View.SYSTEM_UI_FLAG_FULLSCREEN) == 0) { /// M: [BUG.MODIFY] Don't need show bars in camera preview. @{ /*showBars();*/ /*wantBars(); /// @} } } });*/ setOnSystemUiVisibilityChangeListener(); /// @} /// M: [FEATURE.ADD] VTSP: share as video @{ initAnimatedContentSharer(); /// @} /// M: [FEATURE.ADD] add backward controller for layer @{ mPhotoView.setBackwardControllerForLayerManager(mBackwardContollerForLayer); /// @} }