List of usage examples for android.content Intent getLongExtra
public long getLongExtra(String name, long defaultValue)
From source file:com.newtifry.android.NewtificationService2.java
public void onStart(Intent intent, int startId) { super.onStart(intent, startId); // On null intent, give up. if (intent == null) { return;//from w w w.j av a 2 s . co m } if (Preferences.getMasterEnable(this) == false) { Log.d(TAG, "Master enable is off, so not doing anything."); return; } int unreadMessages = 0; int unreadSources = 0; NewtifrySource uniqueUnreadSource = null; List<NewtifryAccount> accounts = NewtifryAccount.FACTORY.listAll(this); List<String> inboxStyleStringArray = new ArrayList<String>(); for (NewtifryAccount account : accounts) { List<NewtifrySource> sources = NewtifrySource.FACTORY.listAll(this, account.getAccountName()); for (NewtifrySource source : sources) { int unread = NewtifryMessage.FACTORY.countUnread(this, source); unreadMessages += unread; if (unread != 0) { unreadSources++; uniqueUnreadSource = source; if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN) { String bigContentText = source.getTitle() + " : " + String.format(getString(R.string.notificationFormat), unread); inboxStyleStringArray.add(bigContentText); //inboxStyle.addLine(bigContentText); } } } } // try to read account less (aka serverless) unred messages // get Newtifry source long newtifrySourceId = Preferences.getNewtifrySource(this); if (newtifrySourceId != 0L) { NewtifrySource newtifrySource = NewtifrySource.FACTORY.getByServerId(this, newtifrySourceId); int unread = NewtifryMessage.FACTORY.countUnread(this, newtifrySource); unreadMessages += unread; if (unread != 0) { unreadSources++; uniqueUnreadSource = newtifrySource; if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN) { String bigContentText = newtifrySource.getTitle() + " : " + String.format(getString(R.string.notificationFormat), unread); inboxStyleStringArray.add(bigContentText); //inboxStyle.addLine(bigContentText); } } } if (unreadMessages == 0) { // clear notification mNotificationManager.cancel(NOTIFICATION_ID); return; } Long messageId = intent.getLongExtra("messageId", 0); NewtifryMessage message = NewtifryMessage.FACTORY.get(this, messageId); // If the message is NULL, then we've been passed an invalid message - return. if (message == null) { Log.d(TAG, "Message " + messageId + " not found, so not doing anything."); return; } // NEW : always update : update or create new notification NewtifyDecision decision = NewtifyDecision.shouldNotify(this, message); if (decision.getShouldNotify()) { // if( globalOrOverrideBoolean(R.string.useNotifierPro, settings, message.getSource(), false) ) { if (Preferences.getUseNotifierPro(message.getSource(), this)) { // for notifierPro Intent notifierProIntent = new Intent("com.productigeeky.NOTIFICATION"); notifierProIntent.putExtra("title", message.getTitle()); notifierProIntent.putExtra("subtitle", message.getMessage()); notifierProIntent.putExtra("action", "com.newtifry.android.MessageList"); getBaseContext().sendBroadcast(notifierProIntent); return; // that's all } NotificationCompat.Builder notification = new NotificationCompat.Builder(this) .setSmallIcon(R.drawable.icon_statusbar).setOnlyAlertOnce(true) .setWhen(System.currentTimeMillis()).setAutoCancel(true); if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB) { notification.setLargeIcon(bigNotificationIcon); } /* // Creates an explicit intent for an Activity in your app Intent resultIntent = new Intent(this, MessageList.class); // TODO : add extra to show if App is visible or not // TODO : add info to indicate that the messageList is called from notification resultIntent.putExtra("app_visible", NewtifryApp.isAppVisible()); resultIntent.putExtra("from_notification", true); // The stack builder object will contain an artificial back stack for the // started Activity. // This ensures that navigating backward from the Activity leads out of // your application to the Home screen. TaskStackBuilder stackBuilder = TaskStackBuilder.create(this); // Adds the back stack for the Intent (but not the Intent itself) stackBuilder.addParentStack(Newtifry.class); // Adds the Intent that starts the Activity to the top of the stack stackBuilder.addNextIntent(resultIntent); PendingIntent resultPendingIntent = stackBuilder.getPendingIntent( 0, PendingIntent.FLAG_UPDATE_CURRENT ); */ Intent notificationIntent = new Intent(this, MessageList.class); notificationIntent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP); notificationIntent.putExtra("from_notification", true); PendingIntent contentIntent = PendingIntent.getActivity(this, 0, notificationIntent, PendingIntent.FLAG_UPDATE_CURRENT); notification.setContentIntent(contentIntent); // if( globalOrOverrideBoolean(R.string.vibrateNotify, settings, message.getSource(), true) ) { if (Preferences.getVibrateNotify(message.getSource(), this)) { long[] vibratePattern = { 0, 500, 250, 500 }; notification.setVibrate(vibratePattern); } // if( globalOrOverrideBoolean(R.string.ledFlash, settings, message.getSource(), true) ) { if (Preferences.getLedFlash(this)) { // if( settings.getBoolean(getString(R.string.fastLedFlash), false) ) { if (Preferences.getFastLedFlash(this)) { // Special "fast flash" mode for phones with poor notification LEDs. // Ie, my G2 that flashes very slowly so it's hard to notice. notification.setLights(0xff00ff00, 300, 300); } else { // Use the default device flash notifications. notification.setLights(0xff00ff00, 300, 1000); // notification.defaults |= Notification.DEFAULT_LIGHTS; } } // If we're speaking, dispatch the message to the speaking service. // if( globalOrOverrideBoolean(R.string.speakMessage, settings, message.getSource(), true) ) if (Preferences.getSpeakMessage(message.getSource(), this)) { Intent intentData = new Intent(getBaseContext(), SpeakService.class); Log.d(TAG, "Speaking text: " + decision.getOutputMessage()); intentData.putExtra("text", decision.getOutputMessage()); startService(intentData); } else { String tone = Preferences.getRingtone(message.getSource(), this); Log.d(TAG, "Notification selected by user: " + tone); if (tone != null) { notification.setSound(Uri.parse(tone)); } } // now build text // for each source // get unread messages // add text for this source NotificationCompat.InboxStyle inboxStyle = null; if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN) { inboxStyle = new NotificationCompat.InboxStyle(); inboxStyle.setBigContentTitle(getString(R.string.app_name)); // Moves the big view style object into the notification object. for (String str : inboxStyleStringArray) { inboxStyle.addLine(str); } notification.setStyle(inboxStyle); } if (unreadMessages == 1 || unreadSources == 1) { notification.setContentTitle(getString(R.string.app_name) + " : " + uniqueUnreadSource.getTitle()); notification.setContentText(String.format(getString(R.string.notificationFormat), unreadMessages)); } else { notification.setContentTitle(getString(R.string.app_name)); notification.setContentText(String.format(getString(R.string.notificationFormat), unreadMessages)); } notification.setNumber(unreadMessages); mNotificationManager.notify(NOTIFICATION_ID, notification.build()); } /* NotificationCompat.Builder b = new NotificationCompat.Builder(c); b.setNumber(g_push.Counter) .setLargeIcon(BitmapFactory.decodeResource(c.getResources(), R.drawable.list_avatar)) .setSmallIcon(R.drawable.ic_stat_example) .setAutoCancel(true) .setContentTitle(pushCount > 1 ? c.getString(R.string.stat_messages_title) + pushCount : title) .setContentText(pushCount > 1 ? push.ProfileID : mess) .setWhen(g_push.Timestamp) .setContentIntent(PendingIntent.getActivity(c, 0, it, PendingIntent.FLAG_UPDATE_CURRENT)) .setDeleteIntent(PendingIntent.getBroadcast(c, 0, new Intent(ACTION_CLEAR_NOTIFICATION), PendingIntent.FLAG_CANCEL_CURRENT)) .setDefaults(Notification.DEFAULT_LIGHTS | Notification.DEFAULT_VIBRATE) .setSound(Uri.parse(prefs.getString( SharedPreferencesID.PREFERENCE_ID_PUSH_SOUND_URI, "android.resource://ru.mail.mailapp/raw/new_message_bells"))); */ /* // Determine our action. String operation = intent.getStringExtra("operation"); if( operation.equals("newtifry") ) { // Ok, let's start notifying! Notification notification = this.setLatestEventInfo(message.getSource(), message); // Now, other notification methods. if( globalOrOverrideBoolean(R.string.vibrateNotify, settings, message.getSource(), true) ) { notification.defaults |= Notification.DEFAULT_VIBRATE; } if( globalOrOverrideBoolean(R.string.ledFlash, settings, message.getSource(), true) ) { if( settings.getBoolean(getString(R.string.fastLedFlash), false) ) { // Special "fast flash" mode for phones with poor notification LEDs. // Ie, my G2 that flashes very slowly so it's hard to notice. notification.ledARGB = 0xff00ff00; notification.ledOnMS = 300; notification.ledOffMS = 1000; notification.flags |= Notification.FLAG_SHOW_LIGHTS; } else { // Use the default device flash notifications. notification.defaults |= Notification.DEFAULT_LIGHTS; } } // If we're speaking, dispatch the message to the speaking service. if( globalOrOverrideBoolean(R.string.speakMessage, settings, message.getSource(), true) ) { Intent intentData = new Intent(getBaseContext(), SpeakService.class); Log.d(TAG, "Speaking text: " + decision.getOutputMessage()); intentData.putExtra("text", decision.getOutputMessage()); startService(intentData); } else { if( globalOrOverrideBoolean(R.string.playRingtone, settings, message.getSource(), true) ) { String tone = globalOrOverrideString(R.string.choosenNotification, settings, message.getSource(), ""); Log.d(TAG, "Notification selected by user: " + tone); if( tone.equals("") ) { // Set the default notification tone. notification.defaults |= Notification.DEFAULT_SOUND; } else { // Load the notification and add it. notification.sound = Uri.parse(tone); } } } // Put the notification in the tray. Use the source's local ID to identify it. this.notificationManager.notify(message.getSource().getNotificationId(), notification); } } else if( operation.equals("update") ) { // Clear the notifications for a given source - if there are no unread messages. NewtifrySource source = NewtifrySource.FACTORY.get(this, intent.getLongExtra("sourceId", 0)); if( source != null ) { this.updateNotificationFor(source); } else { // Do it for all sources. List<NewtifryAccount> accounts = NewtifryAccount.FACTORY.listAll(this); for( NewtifryAccount account: accounts ) { List<NewtifrySource> sources = NewtifrySource.FACTORY.listAll(this, account.getAccountName()); for( NewtifrySource thisSource: sources ) { this.updateNotificationFor(thisSource); } } } } */ return; }
From source file:org.mariotaku.twidere.fragment.support.UserFragment.java
@Override public void onActivityResult(final int requestCode, final int resultCode, final Intent data) { final ParcelableUser user = getUser(); final UserColorNameManager manager = UserColorNameManager.getInstance(getActivity()); switch (requestCode) { case REQUEST_SET_COLOR: { if (user == null) return; if (resultCode == Activity.RESULT_OK) { if (data == null) return; final int color = data.getIntExtra(EXTRA_COLOR, Color.TRANSPARENT); manager.setUserColor(mUser.id, color); } else if (resultCode == ColorPickerDialogActivity.RESULT_CLEARED) { manager.clearUserColor(mUser.id); }/*from w w w . j av a 2s. c o m*/ break; } case REQUEST_ADD_TO_LIST: { if (user == null) return; if (resultCode == Activity.RESULT_OK && data != null) { final AsyncTwitterWrapper twitter = getTwitterWrapper(); final ParcelableUserList list = data.getParcelableExtra(EXTRA_USER_LIST); if (list == null || twitter == null) return; twitter.addUserListMembersAsync(user.account_id, list.id, user); } break; } case REQUEST_SELECT_ACCOUNT: { if (user == null) return; if (resultCode == Activity.RESULT_OK) { if (data == null || !data.hasExtra(EXTRA_ID)) return; final long accountId = data.getLongExtra(EXTRA_ID, -1); Utils.openUserProfile(getActivity(), accountId, user.id, user.screen_name, null); } break; } } }
From source file:nz.ac.otago.psyanlab.common.designer.ExperimentDesignerActivity.java
@Override public void onActivityResult(final int requestCode, final int resultCode, final Intent data) { switch (requestCode) { case REQUEST_EDIT_STAGE: { switch (resultCode) { case RESULT_OK: ArrayList<PropIdPair> props = data.getParcelableArrayListExtra(Args.EXPERIMENT_PROPS); long sceneId = data.getLongExtra(Args.SCENE_ID, -1); int height = data.getIntExtra(Args.STAGE_HEIGHT, -1); int width = data.getIntExtra(Args.STAGE_WIDTH, -1); int orientation = data.getIntExtra(Args.STAGE_ORIENTATION, Scene.ORIENTATION_LANDSCAPE); updateStageInScene(sceneId, props, orientation, width, height); break; default:/*from w ww .j ava 2 s . c om*/ break; } break; } case REQUEST_ASSET_IMPORT: { switch (resultCode) { case RESULT_OK: String[] paths = data.getStringArrayExtra(Args.PICKED_PATHS); Time t = new Time(); t.setToNow(); mExperiment.assets.put(ModelUtils.findUnusedKey(mExperiment.assets), Asset.getFactory().newAsset(paths[0])); mAssetAdapter.notifyDataSetChanged(); break; default: break; } break; } case REQUEST_SOURCE_IMPORT: { switch (resultCode) { case RESULT_OK: String[] paths = data.getStringArrayExtra(Args.PICKED_PATHS); Time t = new Time(); t.setToNow(); Source newSource = new Source(); newSource.setExternalFile(new File(paths[0])); mExperiment.sources.put(ModelUtils.findUnusedKey(mExperiment.sources), newSource); mSourceAdapter.notifyDataSetChanged(); break; default: break; } } default: break; } }
From source file:aarddict.android.ArticleViewActivity.java
@Override void onDictionaryServiceReady() { if (this.backItems.isEmpty()) { final Intent intent = getIntent(); if (intent != null && intent.getAction() != null) { String action = intent.getAction(); String _word = null;// w ww . j a v a2 s .c o m if (action.equals(Intent.ACTION_SEARCH)) { _word = intent.getStringExtra("query"); } else if (action.equals(Intent.ACTION_SEND)) { _word = intent.getStringExtra(Intent.EXTRA_TEXT); } final String word = _word; if (word != null) { if (currentTask != null) { currentTask.cancel(); } currentTask = new TimerTask() { @Override public void run() { setProgress(500); String currentWord = word; Log.d(TAG, "intent.getDataString(): " + intent.getDataString()); while (currentWord.length() > 0) { Iterator<Entry> results = dictionaryService.lookup(currentWord); Log.d(TAG, "Looked up " + word); if (results.hasNext()) { currentTask = null; Entry entry = results.next(); showArticle(entry); break; } else { currentWord = currentWord.substring(0, currentWord.length() - 1); } } if (currentWord.length() == 0) { onSearchRequested(); } } }; try { timer.schedule(currentTask, 0); } catch (Exception e) { Log.d(TAG, "Failed to schedule task", e); showError(getString(R.string.msgErrorLoadingArticle, word)); } } } else { String word = intent.getStringExtra("word"); String section = intent.getStringExtra("section"); String volumeId = intent.getStringExtra("volumeId"); long articlePointer = intent.getLongExtra("articlePointer", -1); dictionaryService.setPreferred(volumeId); showArticle(volumeId, articlePointer, word, section); } } else { showCurrentArticle(); } }
From source file:com.socialdisasters.other.service.ChatService.java
@Override protected void onHandleIntent(Intent intent) { // stop processing if the session is not assigned if (_session == null) return;//w w w . j a v a 2s .co m String action = intent.getAction(); // create a task to process concurrently if (ACTION_PRESENCE_ALARM.equals(action)) { SharedPreferences preferences = PreferenceManager.getDefaultSharedPreferences(ChatService.this); // check if the screen is active PowerManager pm = (PowerManager) getSystemService(Context.POWER_SERVICE); Boolean screenOn = pm.isScreenOn(); String presence_tag = preferences.getString("presencetag", "unavailable"); String presence_nick = getLocalNickname(); String presence_text = preferences.getString("statustext", ""); if (presence_tag.equals("auto")) { if (screenOn) { presence_tag = "chat"; } else { presence_tag = "away"; } } Log.i(TAG, "push out presence; " + presence_tag); actionRefreshPresence(presence_tag, presence_nick, presence_text); Editor edit = preferences.edit(); edit.putLong("lastpresenceupdate", (new Date().getTime())); edit.commit(); } // create a task to check for messages else if (de.tubs.ibr.dtn.Intent.RECEIVE.equals(action)) { // wait until connected try { while (_session.queryNext()) ; } catch (SessionDestroyedException e) { Log.e(TAG, "Can not query for bundle", e); } } else if (MARK_DELIVERED_INTENT.equals(action)) { BundleID bundleid = intent.getParcelableExtra("bundleid"); if (bundleid == null) { Log.e(TAG, "Intent to mark a bundle as delivered, but no bundle ID given"); return; } try { _session.delivered(bundleid); } catch (Exception e) { Log.e(TAG, "Can not mark bundle as delivered.", e); } } else if (REPORT_DELIVERED_INTENT.equals(action)) { SingletonEndpoint source = intent.getParcelableExtra("source"); BundleID bundleid = intent.getParcelableExtra("bundleid"); if (bundleid == null) { Log.e(TAG, "Intent to mark a bundle as delivered, but no bundle ID given"); return; } synchronized (this.roster) { // report delivery to the roster getRoster().reportDelivery(source, bundleid); } } else if (ACTION_SEND_MESSAGE.equals(action)) { Long buddyId = intent.getLongExtra(ChatService.EXTRA_BUDDY_ID, -1); String text = intent.getStringExtra(ChatService.EXTRA_TEXT_BODY); // abort if there is no buddyId if (buddyId < 0) return; actionSendMessage(buddyId, text); } else if (ACTION_REFRESH_PRESENCE.equals(action)) { String presence = intent.getStringExtra(ChatService.EXTRA_PRESENCE); String nickname = intent.getStringExtra(ChatService.EXTRA_DISPLAY_NAME); String status = intent.getStringExtra(ChatService.EXTRA_STATUS); actionRefreshPresence(presence, nickname, status); } else if (ACTION_NEW_MESSAGE.equals(action)) { showNotification(intent); } }
From source file:com.android.leanlauncher.LauncherTransitionable.java
boolean startActivity(View v, Intent intent, Object tag) { intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK); try {/*w w w . j a v a 2 s . c o m*/ // Only launch using the new animation if the shortcut has not opted out (this is a // private contract between launcher and may be ignored in the future). boolean useLaunchAnimation = (v != null) && !intent.hasExtra(INTENT_EXTRA_IGNORE_LAUNCH_ANIMATION); LauncherAppsCompat launcherApps = LauncherAppsCompat.getInstance(this); UserManagerCompat userManager = UserManagerCompat.getInstance(this); UserHandleCompat user = null; if (intent.hasExtra(AppInfo.EXTRA_PROFILE)) { long serialNumber = intent.getLongExtra(AppInfo.EXTRA_PROFILE, -1); user = userManager.getUserForSerialNumber(serialNumber); } Bundle optsBundle = null; if (useLaunchAnimation) { ActivityOptions opts = Utilities.isLmpOrAbove() ? ActivityOptions.makeCustomAnimation(this, R.anim.task_open_enter, R.anim.no_anim) : ActivityOptions.makeScaleUpAnimation(v, 0, 0, v.getMeasuredWidth(), v.getMeasuredHeight()); optsBundle = opts.toBundle(); } if (user == null || user.equals(UserHandleCompat.myUserHandle())) { // Could be launching some bookkeeping activity startActivity(intent, optsBundle); } else { // TODO Component can be null when shortcuts are supported for secondary user launcherApps.startActivityForProfile(intent.getComponent(), user, intent.getSourceBounds(), optsBundle); } return true; } catch (SecurityException e) { Toast.makeText(this, R.string.activity_not_found, Toast.LENGTH_SHORT).show(); Log.e(TAG, "Launcher does not have the permission to launch " + intent + ". Make sure to create a MAIN intent-filter for the corresponding activity " + "or use the exported attribute for this activity. " + "tag=" + tag + " intent=" + intent, e); } return false; }
From source file:com.microsoft.aad.adal.AuthenticationContext.java
/** * This method wraps the implementation for onActivityResult at the related * Activity class. This method is called at UI thread. * //from ww w .j av a 2s . c o m * @param requestCode Request code provided at the start of the activity. * @param resultCode Result code set from the activity. * @param data {@link Intent} */ public void onActivityResult(int requestCode, int resultCode, Intent data) { // This is called at UI thread when Activity sets result back. // ResultCode is set back from AuthenticationActivity. RequestCode is // set when we start the activity for result. if (requestCode == AuthenticationConstants.UIRequest.BROWSER_FLOW) { if (data == null) { // If data is null, RequestId is unknown. It could not find // callback to respond to this request. Logger.e(TAG, "onActivityResult BROWSER_FLOW data is null.", "", ADALError.ON_ACTIVITY_RESULT_INTENT_NULL); } else { Bundle extras = data.getExtras(); final int requestId = extras.getInt(AuthenticationConstants.Browser.REQUEST_ID); final AuthenticationRequestState waitingRequest = getWaitingRequest(requestId); if (waitingRequest != null) { Logger.v(TAG, "onActivityResult RequestId:" + requestId); } else { Logger.e(TAG, "onActivityResult did not find waiting request for RequestId:" + requestId, "", ADALError.ON_ACTIVITY_RESULT_INTENT_NULL); // There is no matching callback to send error return; } // Cancel or browser error can use recorded request to figure // out original correlationId send with request. String correlationInfo = getCorrelationInfoFromWaitingRequest(waitingRequest); if (resultCode == AuthenticationConstants.UIResponse.TOKEN_BROKER_RESPONSE) { String accessToken = data.getStringExtra(AuthenticationConstants.Broker.ACCOUNT_ACCESS_TOKEN); String accountName = data.getStringExtra(AuthenticationConstants.Broker.ACCOUNT_NAME); mBrokerProxy.saveAccount(accountName); long expireTime = data.getLongExtra(AuthenticationConstants.Broker.ACCOUNT_EXPIREDATE, 0); Date expire = new Date(expireTime); UserInfo userinfo = UserInfo.getUserInfoFromBrokerResult(data.getExtras()); AuthenticationResult brokerResult = new AuthenticationResult(accessToken, null, expire, false, userinfo, "", ""); if (brokerResult != null && brokerResult.getAccessToken() != null) { waitingRequest.mDelagete.onSuccess(brokerResult); return; } } else if (resultCode == AuthenticationConstants.UIResponse.BROWSER_CODE_CANCEL) { // User cancelled the flow by clicking back button or // activating another activity Logger.v(TAG, "User cancelled the flow RequestId:" + requestId + correlationInfo); waitingRequestOnError(waitingRequest, requestId, new AuthenticationCancelError( "User cancelled the flow RequestId:" + requestId + correlationInfo)); } else if (resultCode == AuthenticationConstants.UIResponse.BROWSER_CODE_AUTHENTICATION_EXCEPTION) { Serializable authException = extras .getSerializable(AuthenticationConstants.Browser.RESPONSE_AUTHENTICATION_EXCEPTION); if (authException != null && authException instanceof AuthenticationException) { AuthenticationException exception = (AuthenticationException) authException; Logger.w(TAG, "Webview returned exception", exception.getMessage(), ADALError.WEBVIEW_RETURNED_AUTHENTICATION_EXCEPTION); waitingRequestOnError(waitingRequest, requestId, exception); } else { waitingRequestOnError(waitingRequest, requestId, new AuthenticationException( ADALError.WEBVIEW_RETURNED_INVALID_AUTHENTICATION_EXCEPTION)); } } else if (resultCode == AuthenticationConstants.UIResponse.BROWSER_CODE_ERROR) { String errCode = extras.getString(AuthenticationConstants.Browser.RESPONSE_ERROR_CODE); String errMessage = extras.getString(AuthenticationConstants.Browser.RESPONSE_ERROR_MESSAGE); Logger.v(TAG, "Error info:" + errCode + " " + errMessage + " for requestId: " + requestId + correlationInfo); waitingRequestOnError(waitingRequest, requestId, new AuthenticationException( ADALError.SERVER_INVALID_REQUEST, errCode + " " + errMessage)); } else if (resultCode == AuthenticationConstants.UIResponse.BROWSER_CODE_COMPLETE) { final AuthenticationRequest authenticationRequest = (AuthenticationRequest) extras .getSerializable(AuthenticationConstants.Browser.RESPONSE_REQUEST_INFO); final String endingUrl = extras.getString(AuthenticationConstants.Browser.RESPONSE_FINAL_URL); if (endingUrl.isEmpty()) { AuthenticationException e = new AuthenticationException( ADALError.WEBVIEW_RETURNED_EMPTY_REDIRECT_URL, "Webview did not reach the redirectUrl. " + authenticationRequest.getLogInfo()); Logger.e(TAG, e.getMessage(), "", e.getCode()); waitingRequestOnError(waitingRequest, requestId, e); } else { // Browser has the url and it will exchange auth code // for token final CallbackHandler callbackHandle = new CallbackHandler(mHandler, waitingRequest.mDelagete); // Executes all the calls inside the Runnable to return // immediately to // UI thread. All UI // related actions will be performed using the Handler. sThreadExecutor.submit(new Runnable() { @Override public void run() { Logger.v(TAG, "Processing url for token. " + authenticationRequest.getLogInfo()); Oauth2 oauthRequest = new Oauth2(authenticationRequest, mWebRequest); AuthenticationResult result = null; try { result = oauthRequest.getToken(endingUrl); Logger.v(TAG, "OnActivityResult processed the result. " + authenticationRequest.getLogInfo()); } catch (Exception exc) { String msg = "Error in processing code to get token. " + authenticationRequest.getLogInfo(); Logger.e(TAG, msg, ExceptionExtensions.getExceptionMessage(exc), ADALError.AUTHORIZATION_CODE_NOT_EXCHANGED_FOR_TOKEN, exc); // Call error at UI thread waitingRequestOnError(callbackHandle, waitingRequest, requestId, new AuthenticationException( ADALError.AUTHORIZATION_CODE_NOT_EXCHANGED_FOR_TOKEN, msg, exc)); return; } try { if (result != null) { Logger.v(TAG, "OnActivityResult is setting the token to cache. " + authenticationRequest.getLogInfo()); if (!StringExtensions.IsNullOrBlank(result.getAccessToken())) { setItemToCache(authenticationRequest, result, true); } if (waitingRequest != null && waitingRequest.mDelagete != null) { Logger.v(TAG, "Sending result to callback. " + authenticationRequest.getLogInfo()); callbackHandle.onSuccess(result); } } else { callbackHandle.onError(new AuthenticationException( ADALError.AUTHORIZATION_CODE_NOT_EXCHANGED_FOR_TOKEN)); } } finally { removeWaitingRequest(requestId); } } }); } } } } }
From source file:de.vanita5.twittnuker.activity.support.ComposeActivity.java
@Override protected void onCreate(final Bundle savedInstanceState) { // requestWindowFeature(Window.FEATURE_INDETERMINATE_PROGRESS); super.onCreate(savedInstanceState); mLocationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE); mPreferences = SharedPreferencesWrapper.getInstance(this, SHARED_PREFERENCES_NAME, Context.MODE_PRIVATE); mBottomSendButton = mPreferences.getBoolean(KEY_BOTTOM_SEND_BUTTON, false); mTwitterWrapper = getTwittnukerApplication().getTwitterWrapper(); mResolver = getContentResolver();//from w w w .j a va 2 s . c o m mValidator = new TwidereValidator(this); setContentView(getLayoutInflater().inflate(R.layout.activity_compose, null)); setProgressBarIndeterminateVisibility(false); setFinishOnTouchOutside(false); mAccountIds = getAccountIds(this); if (mAccountIds.length <= 0) { final Intent intent = new Intent(INTENT_ACTION_TWITTER_LOGIN); intent.setClass(this, SignInActivity.class); startActivity(intent); finish(); return; } mBottomMenuBar.setIsBottomBar(true); mBottomMenuBar.setOnMenuItemClickListener(this); mActionMenuBar.setOnMenuItemClickListener(this); mEditText.setOnEditorActionListener(mPreferences.getBoolean(KEY_QUICK_SEND, false) ? this : null); mEditText.addTextChangedListener(this); mAccountSelectorAdapter = new AccountSelectorAdapter(this); mAccountSelector.setAdapter(mAccountSelectorAdapter); mAccountSelector.setOnItemClickListener(this); mAccountSelector.setOnItemLongClickListener(this); mAccountSelector.setScrollAfterItemClickEnabled(false); mAccountSelector.setScrollRightSpacingEnabled(false); mMediaPreviewAdapter = new MediaPreviewAdapter(this); mMediasPreviewGrid.setAdapter(mMediaPreviewAdapter); final Intent intent = getIntent(); if (savedInstanceState != null) { // Restore from previous saved state mSendAccountIds = savedInstanceState.getLongArray(EXTRA_ACCOUNT_IDS); mIsPossiblySensitive = savedInstanceState.getBoolean(EXTRA_IS_POSSIBLY_SENSITIVE); final ArrayList<ParcelableMediaUpdate> mediasList = savedInstanceState .getParcelableArrayList(EXTRA_MEDIAS); if (mediasList != null) { addMedias(mediasList); } mInReplyToStatus = savedInstanceState.getParcelable(EXTRA_STATUS); mInReplyToStatusId = savedInstanceState.getLong(EXTRA_STATUS_ID); mMentionUser = savedInstanceState.getParcelable(EXTRA_USER); mDraftItem = savedInstanceState.getParcelable(EXTRA_DRAFT); mShouldSaveAccounts = savedInstanceState.getBoolean(EXTRA_SHOULD_SAVE_ACCOUNTS); mOriginalText = savedInstanceState.getString(EXTRA_ORIGINAL_TEXT); mTempPhotoUri = savedInstanceState.getParcelable(EXTRA_TEMP_URI); } else { // The activity was first created final int notificationId = intent.getIntExtra(EXTRA_NOTIFICATION_ID, -1); final long notificationAccount = intent.getLongExtra(EXTRA_NOTIFICATION_ACCOUNT, -1); if (notificationId != -1) { mTwitterWrapper.clearNotificationAsync(notificationId, notificationAccount); } if (!handleIntent(intent)) { handleDefaultIntent(intent); } if (mSendAccountIds == null || mSendAccountIds.length == 0) { final long[] ids_in_prefs = ArrayUtils .parseLongArray(mPreferences.getString(KEY_COMPOSE_ACCOUNTS, null), ','); final long[] intersection = ArrayUtils.intersection(ids_in_prefs, mAccountIds); mSendAccountIds = intersection.length > 0 ? intersection : mAccountIds; } mOriginalText = ParseUtils.parseString(mEditText.getText()); } if (!setComposeTitle(intent)) { setTitle(R.string.compose); } final boolean useBottomMenu = isSingleAccount() || !mBottomSendButton; if (useBottomMenu) { mBottomMenuBar.inflate(R.menu.menu_compose); } else { mActionMenuBar.inflate(R.menu.menu_compose); } mBottomMenuBar.setVisibility(useBottomMenu ? View.VISIBLE : View.GONE); mActionMenuBar.setVisibility(useBottomMenu ? View.GONE : View.VISIBLE); mSendView.setVisibility(mBottomSendButton ? View.GONE : View.VISIBLE); mBottomSendDivider.setVisibility(mBottomSendButton ? View.VISIBLE : View.GONE); mBottomSendView.setVisibility(mBottomSendButton ? View.VISIBLE : View.GONE); mSendView.setOnClickListener(this); mBottomSendView.setOnClickListener(this); mSendView.setOnLongClickListener(this); mBottomSendView.setOnLongClickListener(this); final LinearLayout.LayoutParams bottomMenuContainerParams = (LinearLayout.LayoutParams) mBottomMenuContainer .getLayoutParams(); final LinearLayout.LayoutParams accountSelectorParams = (LinearLayout.LayoutParams) mAccountSelector .getLayoutParams(); final int maxItemsShown; final Resources res = getResources(); if (isSingleAccount()) { accountSelectorParams.weight = 0; accountSelectorParams.width = ViewGroup.LayoutParams.WRAP_CONTENT; bottomMenuContainerParams.weight = 1; bottomMenuContainerParams.width = ViewGroup.LayoutParams.MATCH_PARENT; maxItemsShown = res.getInteger(R.integer.max_compose_menu_buttons_bottom_singleaccount); mAccountSelectorDivider.setVisibility(View.VISIBLE); } else { accountSelectorParams.weight = 1; accountSelectorParams.width = ViewGroup.LayoutParams.MATCH_PARENT; bottomMenuContainerParams.weight = 0; bottomMenuContainerParams.width = ViewGroup.LayoutParams.WRAP_CONTENT; maxItemsShown = res.getInteger(R.integer.max_compose_menu_buttons_bottom); mAccountSelectorDivider.setVisibility(mBottomSendButton ? View.GONE : View.VISIBLE); } mBottomMenuContainer.setLayoutParams(bottomMenuContainerParams); mBottomMenuBar.setMaxItemsShown(maxItemsShown); setMenu(); updateAccountSelection(); updateMediasPreview(); }
From source file:com.nachiket.titan.LibraryActivity.java
@Override public boolean onContextItemSelected(MenuItem item) { if (item.getGroupId() != 0) return super.onContextItemSelected(item); Intent intent = item.getIntent(); switch (item.getItemId()) { case MENU_EXPAND: expand(intent);/*from ww w . j av a2s .c o m*/ if (mDefaultAction == ACTION_LAST_USED && mLastAction != ACTION_EXPAND) { mLastAction = ACTION_EXPAND; updateHeaders(); } break; case MENU_ENQUEUE: pickSongs(intent, ACTION_ENQUEUE); break; case MENU_PLAY: pickSongs(intent, ACTION_PLAY); break; case MENU_PLAY_ALL: pickSongs(intent, ACTION_PLAY_ALL); break; case MENU_ENQUEUE_ALL: pickSongs(intent, ACTION_ENQUEUE_ALL); break; case MENU_NEW_PLAYLIST: { NewPlaylistDialog dialog = new NewPlaylistDialog(this, null, R.string.create, intent); dialog.setDismissMessage(mHandler.obtainMessage(MSG_NEW_PLAYLIST, dialog)); dialog.show(); break; } case MENU_RENAME_PLAYLIST: { NewPlaylistDialog dialog = new NewPlaylistDialog(this, intent.getStringExtra("title"), R.string.rename, intent); dialog.setDismissMessage(mHandler.obtainMessage(MSG_RENAME_PLAYLIST, dialog)); dialog.show(); break; } case MENU_DELETE: mHandler.sendMessage(mHandler.obtainMessage(MSG_DELETE, intent)); break; case MENU_ADD_TO_PLAYLIST: { SubMenu playlistMenu = item.getSubMenu(); playlistMenu.add(0, MENU_NEW_PLAYLIST, 0, R.string.new_playlist).setIntent(intent); Cursor cursor = Playlist.queryPlaylists(getContentResolver()); if (cursor != null) { for (int i = 0, count = cursor.getCount(); i != count; ++i) { cursor.moveToPosition(i); long id = cursor.getLong(0); String name = cursor.getString(1); Intent copy = new Intent(intent); copy.putExtra("playlist", id); copy.putExtra("playlistName", name); playlistMenu.add(0, MENU_SELECT_PLAYLIST, 0, name).setIntent(copy); } cursor.close(); } break; } case MENU_SELECT_PLAYLIST: mHandler.sendMessage(mHandler.obtainMessage(MSG_ADD_TO_PLAYLIST, intent)); break; case MENU_MORE_FROM_ARTIST: { String selection; if (intent.getIntExtra(LibraryAdapter.DATA_TYPE, -1) == MediaUtils.TYPE_ALBUM) { selection = "album_id="; } else { selection = "_id="; } selection += intent.getLongExtra(LibraryAdapter.DATA_ID, LibraryAdapter.INVALID_ID); setLimiter(MediaUtils.TYPE_ARTIST, selection); updateLimiterViews(); break; } case MENU_MORE_FROM_ALBUM: setLimiter(MediaUtils.TYPE_ALBUM, "_id=" + intent.getLongExtra(LibraryAdapter.DATA_ID, LibraryAdapter.INVALID_ID)); updateLimiterViews(); break; } return true; }