List of usage examples for android.os Handler postDelayed
public final boolean postDelayed(Runnable r, long delayMillis)
From source file:com.ludoscity.findmybikes.activities.NearbyActivity.java
private void setupBTabSelection(final String _selectedStationId, final boolean _silent) { dismissOnboardingHint();/*from w w w. ja v a 2 s . c om*/ //Remove any previous selection getListPagerAdapter().removeStationHighlightForPage(StationListPagerAdapter.DOCK_STATIONS); if (mTripDetailsWidget.getVisibility() == View.INVISIBLE) { mStationMapFragment .setMapPaddingLeft((int) getResources().getDimension(R.dimen.trip_details_widget_width)); setupTripDetailsWidget(); showTripDetailsWidget(); } else { hideSetupShowTripDetailsWidget(); } final StationItem selectedStation = getStation(_selectedStationId); getListPagerAdapter().hideStationRecap(); mStationMapFragment.setPinOnStation(false, _selectedStationId); getListPagerAdapter().setClickResponsivenessForPage(StationListPagerAdapter.BIKE_STATIONS, true); if (!mFavoritePicked) mStationMapFragment.clearMarkerPickedFavorite(); if (mStationMapFragment.isPickedPlaceMarkerVisible() || mStationMapFragment.isPickedFavoriteMarkerVisible()) { LatLng locationToShow; if (mStationMapFragment.isPickedPlaceMarkerVisible()) locationToShow = mStationMapFragment.getMarkerPickedPlaceVisibleLatLng(); else locationToShow = mStationMapFragment.getMarkerPickedFavoriteVisibleLatLng(); if (!_silent) { if (locationToShow.latitude != selectedStation.getLocation().latitude || locationToShow.longitude != selectedStation.getLocation().longitude) { mStationMapFragment .setMapPaddingRight((int) getResources().getDimension(R.dimen.map_infowindow_padding)); animateCameraToShow((int) getResources().getDimension(R.dimen.camera_search_infowindow_padding), selectedStation.getLocation(), //getLatLngForStation(_selectedStationId), locationToShow, null); } else { mStationMapFragment .animateCamera(CameraUpdateFactory.newLatLngZoom(selectedStation.getLocation(), 15)); } } getListPagerAdapter().highlightStationForPage(_selectedStationId, StationListPagerAdapter.DOCK_STATIONS); getListPagerAdapter().smoothScrollHighlightedInViewForPage(StationListPagerAdapter.DOCK_STATIONS, isAppBarExpanded()); } else { //it's just an A-B trip getListPagerAdapter().setupUI(StationListPagerAdapter.DOCK_STATIONS, RootApplication.getBikeNetworkStationList(), false, null, null, "", new StationRecyclerViewAdapter.TotalTripTimeComparator(Utils.getAverageWalkingSpeedKmh(this), Utils.getAverageBikingSpeedKmh(this), mCurrentUserLatLng, mStationMapFragment.getMarkerALatLng(), selectedStation.getLocation())); if (!mFavoritePicked) { FavoriteItemBase fav = DBHelper.getFavoriteItemForId(this, _selectedStationId); if (fav != null) mStationMapFragment.setPinForPickedFavorite(fav.getDisplayName(), getLatLngForStation(_selectedStationId), null); } if (!_silent) { mStationMapFragment.setMapPaddingRight((int) getResources().getDimension(R.dimen.map_fab_padding)); mClearFAB.show(); mFavoritesSheetFab.hideSheetThenFab(); mSearchFAB.hide(); } final Handler handler = new Handler(); handler.postDelayed(new Runnable() { @Override public void run() { if (getListPagerAdapter() .isRecyclerViewReadyForItemSelection(StationListPagerAdapter.DOCK_STATIONS)) { //highlight B station in list getListPagerAdapter().highlightStationForPage(_selectedStationId, StationListPagerAdapter.DOCK_STATIONS); if (!_silent && mStationMapFragment.getMarkerBVisibleLatLng() != null) mStationMapFragment.animateCamera(CameraUpdateFactory .newLatLngZoom(mStationMapFragment.getMarkerBVisibleLatLng(), 15)); getListPagerAdapter().smoothScrollHighlightedInViewForPage( StationListPagerAdapter.DOCK_STATIONS, isAppBarExpanded()); } else { //This is a repost if RecyclerView is not ready for selection //hackfix. On some devices timing issues led to infinite loop with isRecyclerViewReadyForItemSelection always returning false //so, retry stting up the UI before repost //Replace recyclerview content getListPagerAdapter().setupUI(StationListPagerAdapter.DOCK_STATIONS, RootApplication.getBikeNetworkStationList(), false, null, null, "", new StationRecyclerViewAdapter.TotalTripTimeComparator( Utils.getAverageWalkingSpeedKmh(NearbyActivity.this), Utils.getAverageBikingSpeedKmh(NearbyActivity.this), mCurrentUserLatLng, mStationMapFragment.getMarkerALatLng(), selectedStation.getLocation())); //end hackfix handler.postDelayed(this, 10); } } }, 10); } }
From source file:com.ludoscity.findmybikes.activities.NearbyActivity.java
@Override protected void onActivityResult(int requestCode, int resultCode, Intent data) { if (requestCode == PLACE_AUTOCOMPLETE_REQUEST_CODE) { mPlaceAutocompleteLoadingProgressBar.setVisibility(View.GONE); mSearchFAB.setBackgroundTintList( ContextCompat.getColorStateList(NearbyActivity.this, R.color.theme_primary_dark)); if (resultCode == RESULT_OK) { final Place place = PlaceAutocomplete.getPlace(this, data); mSearchFAB.hide();/*from w w w . j a va 2s .c o m*/ //IDs are not guaranteed stable over long periods of time //but searching for a place already in favorites is not a typical use case //TODO: implement best practice of updating favorite places IDs once per month FavoriteItemPlace newFavForPlace = new FavoriteItemPlace(place.getId(), place.getName().toString(), place.getLatLng(), place.getAttributions()); final FavoriteItemBase existingFavForPlace = DBHelper.getFavoriteItemForId(this, newFavForPlace.getId()); if (existingFavForPlace == null) { if (setupAddFavoriteFab(newFavForPlace)) mAddFavoriteFAB.show(); else mAddFavoriteFAB.hide(); //User selected a search result, onboarding showcases total trip time and favorite action button if (checkOnboarding(eONBOARDING_LEVEL.ONBOARDING_LEVEL_LIGHT, eONBOARDING_STEP.ONBOARDING_STEP_TRIP_TOTAL_SHOWCASE)) //Because destination name is available here and can't be passed down checkOnboarding { mOnboardingShowcaseView.setContentText( String.format(getString(R.string.onboarding_showcase_total_time_text), DBHelper.getBikeNetworkName(this), place.getName())); mOnboardingShowcaseView.setTag(place.getName()); } final Handler handler = new Handler(); handler.postDelayed(new Runnable() { @Override public void run() { if (NearbyActivity.this.getListPagerAdapter().isViewPagerReady()) { setupBTabSelectionClosestDock(place); } else handler.postDelayed(this, 10); } }, 50); } else { //Place was already a favorite final Handler handler = new Handler(); handler.postDelayed(new Runnable() { @Override public void run() { if (NearbyActivity.this.getListPagerAdapter().isViewPagerReady()) { setupBTabSelectionClosestDock(existingFavForPlace.getId()); } else handler.postDelayed(this, 10); } }, 50); } } else { //user pressed back, there's no search result available mFavoritesSheetFab.showFab(); mAddFavoriteFAB.hide(); mSearchFAB.show(); getListPagerAdapter().showStationRecap(); //in case of full onboarding, setup search showcase (user cancelled previous showcased search) //... check if full onboarding should happen if (!checkOnboarding(eONBOARDING_LEVEL.ONBOARDING_LEVEL_FULL, eONBOARDING_STEP.ONBOARDING_STEP_SEARCH_SHOWCASE)) { //... if it doesn't, display hint if required checkOnboarding(eONBOARDING_LEVEL.ONBOARDING_LEVEL_LIGHT, eONBOARDING_STEP.ONBOARDING_STEP_MAIN_CHOICE_HINT); } } } else if (requestCode == SETTINGS_ACTIVITY_REQUEST_CODE) { DBHelper.resumeAutoUpdate(); //Does NOT start it if user didn't activated it in Setting activity mClosestBikeAutoSelected = false; mRefreshMarkers = true; refreshMap(); } else if (requestCode == CHECK_PERMISSION_REQUEST_CODE) { if (ContextCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) == PackageManager.PERMISSION_GRANTED) { // permission was granted, yay! Do the thing mSplashScreenTextTop.setText(R.string.auto_bike_select_finding); mStationMapFragment.enableMyLocationCheckingPermission(); } else checkAndAskLocationPermission(); } else if (requestCode == CHECK_GPS_REQUEST_CODE) { //getting here when GPS been activated through system settings dialog if (resultCode != RESULT_OK) { if (mSplashScreen.isShown()) { mSplashScreenTextTop.setText(R.string.sad_emoji); mSplashScreenTextBottom.setText(""); Utils.Snackbar .makeStyled(mSplashScreen, R.string.location_turn_on, Snackbar.LENGTH_INDEFINITE, ContextCompat.getColor(NearbyActivity.this, R.color.theme_primary_dark)) .setAction(R.string.retry, new View.OnClickListener() { @Override public void onClick(View view) { setupLocationRequest(); } }).show(); } } else { mSplashScreenTextTop.setText(R.string.auto_bike_select_finding); } } }
From source file:com.ludoscity.findmybikes.activities.NearbyActivity.java
private void setupTripDetailsWidget() { final Handler handler = new Handler(); //Need to wait for list selection handler.postDelayed(new Runnable() { @Override/* ww w . j ava 2 s .c om*/ public void run() { if (getListPagerAdapter() .getHighlightedStationForPage(StationListPagerAdapter.DOCK_STATIONS) != null && getListPagerAdapter() .getHighlightedStationForPage(StationListPagerAdapter.BIKE_STATIONS) != null) { int locToAMinutes = 0; int AToBMinutes = 0; int BToSearchMinutes = 0; StationItem selectedStation = getListPagerAdapter() .getHighlightedStationForPage(StationListPagerAdapter.BIKE_STATIONS); String formattedProximityString = Utils.getWalkingProximityString(selectedStation.getLocation(), mCurrentUserLatLng, true, null, NearbyActivity.this); if (formattedProximityString.startsWith(">")) locToAMinutes = 61; else if (!formattedProximityString.startsWith("<")) locToAMinutes = Integer.valueOf(formattedProximityString.substring(1, 3)); mTripDetailsProximityA.setText(formattedProximityString); selectedStation = getListPagerAdapter() .getHighlightedStationForPage(StationListPagerAdapter.DOCK_STATIONS); formattedProximityString = Utils.getBikingProximityString(selectedStation.getLocation(), getListPagerAdapter() .getHighlightedStationForPage(StationListPagerAdapter.BIKE_STATIONS) .getLocation(), true, null, NearbyActivity.this); if (formattedProximityString.startsWith(">")) AToBMinutes = 61; else if (!formattedProximityString.startsWith("<")) AToBMinutes = Integer.valueOf(formattedProximityString.substring(1, 3)); mTripDetailsProximityB.setText(formattedProximityString); //TODO: this string of if...elseif...elseif...else needs refactoring. // Explore extract methods or create some kind of tripdetailswidget configurator if (mStationMapFragment.getMarkerPickedPlaceVisibleLatLng() == null && mStationMapFragment.getMarkerPickedFavoriteVisibleLatLng() == null) { //no marker is showed mTripDetailsBToDestinationRow.setVisibility(View.GONE); ViewGroup.LayoutParams param = mTripDetailsSumSeparator.getLayoutParams(); ((RelativeLayout.LayoutParams) param).addRule(RelativeLayout.BELOW, R.id.trip_details_a_to_b); } else if (mStationMapFragment.getMarkerPickedPlaceVisibleLatLng() != null) { //Place marker is showed formattedProximityString = Utils.getWalkingProximityString(selectedStation.getLocation(), mStationMapFragment.getMarkerPickedPlaceVisibleLatLng(), true, null, NearbyActivity.this); if (formattedProximityString.startsWith(">")) BToSearchMinutes = 61; else if (!formattedProximityString.startsWith("<")) BToSearchMinutes = Integer.valueOf(formattedProximityString.substring(1, 3)); mTripDetailsProximitySearch.setText(formattedProximityString); mTripDetailsPinSearch.setVisibility(View.VISIBLE); mTripDetailsPinFavorite.setVisibility(View.INVISIBLE); mTripDetailsBToDestinationRow.setVisibility(View.VISIBLE); ViewGroup.LayoutParams param = mTripDetailsSumSeparator.getLayoutParams(); ((RelativeLayout.LayoutParams) param).addRule(RelativeLayout.BELOW, R.id.trip_details_b_to_search); } else if (mStationMapFragment .getMarkerPickedFavoriteVisibleLatLng().latitude != mStationMapFragment .getMarkerBVisibleLatLng().latitude || mStationMapFragment .getMarkerPickedFavoriteVisibleLatLng().longitude != mStationMapFragment .getMarkerBVisibleLatLng().longitude) { //Favorite marker is showed and not on B station formattedProximityString = Utils.getWalkingProximityString(selectedStation.getLocation(), mStationMapFragment.getMarkerPickedFavoriteVisibleLatLng(), true, null, NearbyActivity.this); if (formattedProximityString.startsWith(">")) BToSearchMinutes = 61; else if (!formattedProximityString.startsWith("<")) BToSearchMinutes = Integer.valueOf(formattedProximityString.substring(1, 3)); mTripDetailsProximitySearch.setText(formattedProximityString); mTripDetailsPinSearch.setVisibility(View.INVISIBLE); mTripDetailsPinFavorite.setVisibility(View.VISIBLE); mTripDetailsBToDestinationRow.setVisibility(View.VISIBLE); ViewGroup.LayoutParams param = mTripDetailsSumSeparator.getLayoutParams(); ((RelativeLayout.LayoutParams) param).addRule(RelativeLayout.BELOW, R.id.trip_details_b_to_search); } else { //Favorite marker is showed and on B station mTripDetailsBToDestinationRow.setVisibility(View.GONE); ViewGroup.LayoutParams param = mTripDetailsSumSeparator.getLayoutParams(); ((RelativeLayout.LayoutParams) param).addRule(RelativeLayout.BELOW, R.id.trip_details_a_to_b); } int total = locToAMinutes + AToBMinutes + BToSearchMinutes; mTripDetailsProximityTotal .setText(Utils.durationToProximityString(total, false, null, NearbyActivity.this)); } else handler.postDelayed(this, 10); } }, 10); }
From source file:com.ludoscity.findmybikes.activities.NearbyActivity.java
@Override public void onPageSelected(final int position) { StationItem stationA = getListPagerAdapter() .getHighlightedStationForPage(StationListPagerAdapter.BIKE_STATIONS); if (stationA != null) { if (!getListPagerAdapter().setupBTabStationARecap(stationA, mDataOutdated)) mClosestBikeAutoSelected = false; //to handle rapid multiple screen orientation change }//from w w w. j a v a2 s . c o m //Happens on screen orientation change if (mStationMapFragment == null || (mStationMapFragment.getMarkerBVisibleLatLng() != null && getListPagerAdapter().getHighlightedStationForPage(position) == null) || !mStationMapFragment.isMapReady()) { Handler handler = new Handler(); handler.postDelayed(new Runnable() { @Override public void run() { onPageSelected(position); } }, 1000); //second long delay gives a nice UX with camera animation } else { StationItem highlightedStation = getListPagerAdapter().getHighlightedStationForPage(position); //A TAB if (position == StationListPagerAdapter.BIKE_STATIONS) { dismissOnboardingHint(); mStationMapFragment.setScrollGesturesEnabled(false); if (mStationMapFragment.getMarkerBVisibleLatLng() == null) { mStationMapFragment.setMapPaddingLeft(0); hideTripDetailsWidget(); mDirectionsLocToAFab.show(); } mAppBarLayout.setExpanded(false, true); getListPagerAdapter().smoothScrollHighlightedInViewForPage(position, true); mSearchFAB.hide(); mAddFavoriteFAB.hide(); mFavoritesSheetFab.hideSheetThenFab(); mClearFAB.hide(); mStationMapFragment.setMapPaddingRight(0); if (!isStationAClosestBike()) { mStationMapFragment .setMapPaddingRight((int) getResources().getDimension(R.dimen.map_fab_padding)); mAutoSelectBikeFab.show(); } //just to be on the safe side if (highlightedStation != null) { mStationMapFragment.setPinOnStation(true, highlightedStation.getId()); animateCameraToShowUserAndStation(highlightedStation); //if mDataOutdated is true, a Download task will be launched if auto update is also true and a connection is available //That's because autoupdate max interval is SMALLER than outdating one if (!(mDataOutdated && DBHelper.getAutoUpdate(this) && Utils.Connectivity.isConnected(this))) mStationMapFragment.lookingForBikes(mDataOutdated, true); } } else { //B TAB mAutoSelectBikeFab.hide(); mStationMapFragment.setMapPaddingRight(0); //TODO: Should I lock that for regular users ? mStationMapFragment.setScrollGesturesEnabled(true); mAppBarLayout.setExpanded(true, true); if (mStationMapFragment.getMarkerBVisibleLatLng() == null) { //check if showcasing should happen, if not check if hint should happen if (!checkOnboarding(eONBOARDING_LEVEL.ONBOARDING_LEVEL_FULL, eONBOARDING_STEP.ONBOARDING_STEP_SEARCH_SHOWCASE)) checkOnboarding(eONBOARDING_LEVEL.ONBOARDING_LEVEL_LIGHT, eONBOARDING_STEP.ONBOARDING_STEP_MAIN_CHOICE_HINT); mStationMapFragment.animateCamera( CameraUpdateFactory.newLatLngZoom(mStationMapFragment.getMarkerALatLng(), 13.75f)); if (mPlaceAutocompleteLoadingProgressBar.getVisibility() != View.GONE) { mSearchFAB.show(); mSearchFAB.setBackgroundTintList(ContextCompat.getColorStateList(this, R.color.light_gray)); } else { mDirectionsLocToAFab.hide(); mFavoritesSheetFab.showFab(); if (Utils.Connectivity.isConnected(NearbyActivity.this)) mSearchFAB.show(); } mStationMapFragment .setMapPaddingRight((int) getResources().getDimension(R.dimen.map_fab_padding)); } else { getListPagerAdapter().smoothScrollHighlightedInViewForPage(position, false); mStationMapFragment.setMapPaddingLeft( (int) getResources().getDimension(R.dimen.trip_details_widget_width)); if (mTripDetailsWidget.getVisibility() == View.INVISIBLE) { showTripDetailsWidget(); } mStationMapFragment .setMapPaddingRight((int) getResources().getDimension(R.dimen.map_fab_padding)); mClearFAB.show(); LatLng locationToShow = null; if (mStationMapFragment.isPickedPlaceMarkerVisible()) { locationToShow = mStationMapFragment.getMarkerPickedPlaceVisibleLatLng(); mAddFavoriteFAB.show(); } else if (mStationMapFragment.isPickedFavoriteMarkerVisible() && (mStationMapFragment .getMarkerBVisibleLatLng().latitude != mStationMapFragment .getMarkerPickedFavoriteVisibleLatLng().latitude || mStationMapFragment.getMarkerBVisibleLatLng().longitude != mStationMapFragment .getMarkerPickedFavoriteVisibleLatLng().longitude)) locationToShow = mStationMapFragment.getMarkerPickedFavoriteVisibleLatLng(); else if (!mStationMapFragment.isPickedFavoriteMarkerVisible() && DBHelper.getFavoriteItemForId(this, highlightedStation.getId()) == null) mAddFavoriteFAB.show(); if (locationToShow != null) { mStationMapFragment.setMapPaddingRight( (int) getResources().getDimension(R.dimen.map_infowindow_padding)); animateCameraToShow( (int) getResources().getDimension(R.dimen.camera_search_infowindow_padding), mStationMapFragment.getMarkerBVisibleLatLng(), locationToShow, null); } else mStationMapFragment.animateCamera(CameraUpdateFactory .newLatLngZoom(mStationMapFragment.getMarkerBVisibleLatLng(), 15)); } //Log.d("NearbyActivity", "onPageSelected - about to update markers with mDataOutdated : " + mDataOutdated, new Exception()); //if mDataOutdated is true, a Download task will be launched if auto update is also true and a connection is available //That's because autoupdate max interval is SMALLER than outdating one if (!(mDataOutdated && DBHelper.getAutoUpdate(this) && Utils.Connectivity.isConnected(this))) mStationMapFragment.lookingForBikes(mDataOutdated, false); } } }
From source file:com.aimfire.demo.CamcorderActivity.java
/** * Opens a camera, and attempts to establish preview mode at the specified width * and height.// ww w .j ava 2 s . c om * <p> * Sets mCameraPreviewWidth and mCameraPreviewHeight to the actual width/height * of the preview. */ private boolean openCamera(int desiredFacing, int videoQuality) { if (mCamera != null) { if (BuildConfig.DEBUG) Log.e(TAG, "openCamera: camera already initialized"); FirebaseCrash.report(new Exception("CamcorderActivity openCamera: camera already initialized")); return false; } final Camera.CameraInfo info = new Camera.CameraInfo(); /* * Try to find camera with desired facing */ int numCameras = Camera.getNumberOfCameras(); if (numCameras == 0) { if (BuildConfig.DEBUG) Log.e(TAG, "openCamera: No camera found, exiting"); FirebaseCrash.report(new Exception("openCamera: No camera found, exiting")); return false; } mCameraId = -1; for (int i = 0; i < numCameras; i++) { Camera.getCameraInfo(i, info); if (info.facing == desiredFacing) { mCameraId = i; break; } } if (mCameraId == -1) { if (BuildConfig.DEBUG) Log.d(TAG, "openCamera: No camera with desired facing found; opening default"); FirebaseCrash.report(new Exception("openCamera: No camera with desired facing found; opening default")); mCameraId = 0; } try { mCamera = Camera.open(mCameraId); } catch (RuntimeException e) { if (BuildConfig.DEBUG) Log.e(TAG, "openCamera: cannot open camera!"); FirebaseCrash.report(e); return false; } mCameraOrientation = info.orientation; mCameraFacing = info.facing; mCameraParams = mCamera.getParameters(); CameraUtils.setCamParams(mCameraParams); /* * if we can find a supported video/preview size that's the same as our desired size, * use it. otherwise, use the best quality supported by the camera. */ mSupportedVideoQualities = CameraUtils.getSupportedVideoQualities(); if ((mSupportedVideoQualities & (1 << mQualityPref)) == 0) { if (BuildConfig.DEBUG) Log.d(TAG, "openCamera: desired quality " + mQualityPref + " not supported"); mQualityPref = CameraUtils.getMaxVideoQuality(); /* * since this device doesn't support whatever quality preference we had before, * we save the best quality that it does support */ updateQualityPref(mQualityPref); } mCameraParams.setPreviewSize(MainConsts.VIDEO_DIMENSIONS[mQualityPref][0], MainConsts.VIDEO_DIMENSIONS[mQualityPref][1]); AspectFrameLayout afl = (AspectFrameLayout) findViewById(R.id.cameraPreview_frame); afl.setAspectRatio((float) MainConsts.VIDEO_DIMENSIONS[mQualityPref][0] / (float) MainConsts.VIDEO_DIMENSIONS[mQualityPref][1]); /* * give the camera a hint that we're recording video. this can have a big * impact on frame rate. */ mCameraParams.setRecordingHint(true); /* * disable all the automatic settings, in the hope that frame rate will * be less variable * * TODO: if any of the default modes are not available then we need to * sync it with the remote device */ List<String> modes; modes = mCameraParams.getSupportedFocusModes(); if (modes != null) { for (String mode : modes) { if (mode.contains(Camera.Parameters.FOCUS_MODE_INFINITY)) { mCameraParams.setFocusMode(Camera.Parameters.FOCUS_MODE_INFINITY); break; } } } modes = mCameraParams.getSupportedFlashModes(); if (modes != null) { for (String mode : modes) { if (mode.contains(Camera.Parameters.FLASH_MODE_OFF)) { mCameraParams.setFlashMode(Camera.Parameters.FLASH_MODE_OFF); break; } } } /* modes = mCameraParams.getSupportedWhiteBalance(); if(modes != null) { for(String mode : modes) { if(mode.contains(Camera.Parameters.WHITE_BALANCE_FLUORESCENT)) { mCameraParams.setWhiteBalance(Camera.Parameters.WHITE_BALANCE_FLUORESCENT); break; } } } modes = mCameraParams.getSupportedSceneModes(); if(modes != null) { for(String mode : modes) { if(mode.contains(Camera.Parameters.SCENE_MODE_PORTRAIT)) { mCameraParams.setSceneMode(Camera.Parameters.SCENE_MODE_PORTRAIT); break; } } } */ /* * zoom can impact view angle. we should set it to 0 if it's not */ if (mCameraParams.isZoomSupported()) { int zoom = mCameraParams.getZoom(); if (zoom != 0) { if (BuildConfig.DEBUG) Log.d(TAG, "getViewAngle: camera zoom = " + zoom + ", forcing to zero"); mCameraParams.setZoom(0); } } /* * leave the frame rate set to default */ mCamera.setParameters(mCameraParams); /* int[] fpsRange = new int[2]; mCameraParams.getPreviewFpsRange(fpsRange); String previewFacts = VIDEO_DIMENSIONS[mQualityPref][0] + "x" + VIDEO_DIMENSIONS[mQualityPref][1]; if (fpsRange[0] == fpsRange[1]) { previewFacts += " @" + (fpsRange[0] / 1000.0) + "fps"; } else { previewFacts += " @[" + (fpsRange[0] / 1000.0) + " - " + (fpsRange[1] / 1000.0) + "] fps"; } TextView text = (TextView) findViewById(R.id.cameraParams_text); text.setText(previewFacts); */ if (mNaturalOrientation == Configuration.ORIENTATION_PORTRAIT) { if (((info.facing == Camera.CameraInfo.CAMERA_FACING_BACK) && (mLandscapeOrientation == mCameraOrientation)) || ((info.facing == Camera.CameraInfo.CAMERA_FACING_FRONT) && (mLandscapeOrientation != mCameraOrientation))) { mCamera.setDisplayOrientation(180); mCameraOrientation = (mCameraOrientation + 180) % 360; } } if (mOrientationEventListener == null) { mOrientationEventListener = new OrientationEventListener(this, SensorManager.SENSOR_DELAY_NORMAL) { @Override public void onOrientationChanged(int deviceOrientation) { if (deviceOrientation == ORIENTATION_UNKNOWN) return; handleOrientationChanged(deviceOrientation); } }; if (mOrientationEventListener.canDetectOrientation()) { mOrientationEventListener.enable(); } } Runnable forceOrientationCalcRunnable = new Runnable() { public void run() { final Handler handler = new Handler(); handler.postDelayed(new Runnable() { public void run() { int deviceOrientation = mCurrDeviceOrientation; mCurrDeviceOrientation = -1; handleOrientationChanged(deviceOrientation); } }, 100); } }; runOnUiThread(forceOrientationCalcRunnable); return true; }
From source file:au.com.infiniterecursion.vidiom.utils.PublishingUtils.java
public Thread videoUploadToFTPserver(final Activity activity, final Handler handler, final String latestVideoFile_filename, final String latestVideoFile_absolutepath, final String emailAddress, final long sdrecord_id) { Log.d(TAG, "doVideoFTP starting"); // Make the progress bar view visible. ((VidiomActivity) activity).startedUploading(PublishingUtils.TYPE_FTP); final Resources res = activity.getResources(); Thread t = new Thread(new Runnable() { public void run() { // Do background task. // FTP; connect preferences here! ////from w ww. j av a2s . c om SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(activity.getBaseContext()); String ftpHostName = prefs.getString("defaultFTPhostPreference", null); String ftpUsername = prefs.getString("defaultFTPusernamePreference", null); String ftpPassword = prefs.getString("defaultFTPpasswordPreference", null); // use name of local file. String ftpRemoteFtpFilename = latestVideoFile_filename; // FTP FTPClient ftpClient = new FTPClient(); InetAddress uploadhost = null; try { uploadhost = InetAddress.getByName(ftpHostName); } catch (UnknownHostException e1) { // If DNS resolution fails then abort immediately - show // dialog to // inform user first. e1.printStackTrace(); Log.e(TAG, " got exception resolving " + ftpHostName + " - video uploading failed."); uploadhost = null; } if (uploadhost == null) { // Use the handler to execute a Runnable on the // main thread in order to have access to the // UI elements. mainapp.removeSDFileRecordIDfromUploadingTrack(sdrecord_id, TYPE_FTP); handler.postDelayed(new Runnable() { public void run() { // Update UI // Hide the progress bar ((VidiomActivity) activity).finishedUploading(false); ((VidiomActivity) activity) .createNotification(res.getString(R.string.upload_to_ftp_host_failed_)); new AlertDialog.Builder(activity).setMessage(R.string.cant_find_upload_host) .setPositiveButton(R.string.yes, new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int whichButton) { } }).show(); } }, 0); return; } boolean connected = false; try { ftpClient.connect(uploadhost); connected = true; } catch (SocketException e) { e.printStackTrace(); connected = false; } catch (UnknownHostException e) { // e.printStackTrace(); connected = false; } catch (IOException e) { // e.printStackTrace(); connected = false; } if (!connected) { // Use the handler to execute a Runnable on the // main thread in order to have access to the // UI elements. mainapp.removeSDFileRecordIDfromUploadingTrack(sdrecord_id, TYPE_FTP); handler.postDelayed(new Runnable() { public void run() { // Update UI // Hide the progress bar ((VidiomActivity) activity).finishedUploading(false); ((VidiomActivity) activity) .createNotification(res.getString(R.string.upload_to_ftp_host_failed_)); new AlertDialog.Builder(activity).setMessage(R.string.cant_login_upload_host) .setPositiveButton(R.string.yes, new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int whichButton) { } }).show(); } }, 0); return; } boolean reply = false; try { reply = ftpClient.login(ftpUsername, ftpPassword); } catch (IOException e) { // e.printStackTrace(); Log.e(TAG, " got exception on ftp.login - video uploading failed."); } // check the reply code here // If we cant login, abort after showing user a dialog. if (!reply) { try { ftpClient.disconnect(); } catch (IOException e) { // e.printStackTrace(); } // Use the handler to execute a Runnable on the // main thread in order to have access to the // UI elements. mainapp.removeSDFileRecordIDfromUploadingTrack(sdrecord_id, TYPE_FTP); handler.postDelayed(new Runnable() { public void run() { // Update UI // Hide the progress bar ((VidiomActivity) activity).finishedUploading(false); ((VidiomActivity) activity) .createNotification(res.getString(R.string.upload_to_ftp_host_failed_)); new AlertDialog.Builder(activity).setMessage(R.string.cant_login_upload_host) .setPositiveButton(R.string.yes, new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int whichButton) { } }).show(); } }, 0); return; } // Set File type to binary try { ftpClient.setFileType(FTP.BINARY_FILE_TYPE); } catch (IOException e) { // e.printStackTrace(); // keep going?! } // BEYOND HERE DONT USE DIALOGS! // Construct the input stream to send to Ftp server, from the // local // video file on the sd card BufferedInputStream buffIn = null; File file = new File(latestVideoFile_absolutepath); try { buffIn = new BufferedInputStream(new FileInputStream(file)); } catch (FileNotFoundException e) { // e.printStackTrace(); Log.e(TAG, " got exception on local video file - video uploading failed."); // Use the handler to execute a Runnable on the // main thread in order to have access to the // UI elements. mainapp.removeSDFileRecordIDfromUploadingTrack(sdrecord_id, TYPE_FTP); handler.postDelayed(new Runnable() { public void run() { // Update UI // Hide the progress bar ((VidiomActivity) activity).finishedUploading(false); ((VidiomActivity) activity) .createNotification(res.getString(R.string.upload_to_ftp_host_failed_)); } }, 0); // This is a bad error, lets abort. // user dialog ?! shouldnt happen, but still... return; } ftpClient.enterLocalPassiveMode(); try { // UPLOAD THE LOCAL VIDEO FILE. ftpClient.storeFile(ftpRemoteFtpFilename, buffIn); } catch (IOException e) { // e.printStackTrace(); Log.e(TAG, " got exception on storeFile - video uploading failed."); // This is a bad error, lets abort. // user dialog ?! shouldnt happen, but still... // Use the handler to execute a Runnable on the // main thread in order to have access to the // UI elements. mainapp.removeSDFileRecordIDfromUploadingTrack(sdrecord_id, TYPE_FTP); handler.postDelayed(new Runnable() { public void run() { // Update UI // Hide the progress bar ((VidiomActivity) activity).finishedUploading(false); ((VidiomActivity) activity) .createNotification(res.getString(R.string.upload_to_ftp_host_failed_)); } }, 0); return; } try { buffIn.close(); } catch (IOException e) { // e.printStackTrace(); Log.e(TAG, " got exception on buff.close - video uploading failed."); // Use the handler to execute a Runnable on the // main thread in order to have access to the // UI elements. mainapp.removeSDFileRecordIDfromUploadingTrack(sdrecord_id, TYPE_FTP); handler.postDelayed(new Runnable() { public void run() { // Update UI // Hide the progress bar ((VidiomActivity) activity).finishedUploading(false); ((VidiomActivity) activity) .createNotification(res.getString(R.string.upload_to_ftp_host_failed_)); } }, 0); return; } try { ftpClient.logout(); } catch (IOException e) { // e.printStackTrace(); Log.e(TAG, " got exception on ftp logout - video uploading failed."); // Use the handler to execute a Runnable on the // main thread in order to have access to the // UI elements. mainapp.removeSDFileRecordIDfromUploadingTrack(sdrecord_id, TYPE_FTP); handler.postDelayed(new Runnable() { public void run() { // Update UI // Hide the progress bar ((VidiomActivity) activity).finishedUploading(false); ((VidiomActivity) activity) .createNotification(res.getString(R.string.upload_to_ftp_host_failed_)); } }, 0); return; } try { ftpClient.disconnect(); } catch (IOException e) { // e.printStackTrace(); Log.e(TAG, " got exception on ftp disconnect - video uploading failed."); // Use the handler to execute a Runnable on the // main thread in order to have access to the // UI elements. mainapp.removeSDFileRecordIDfromUploadingTrack(sdrecord_id, TYPE_FTP); handler.postDelayed(new Runnable() { public void run() { // Update UI // Hide the progress bar ((VidiomActivity) activity).finishedUploading(false); ((VidiomActivity) activity) .createNotification(res.getString(R.string.upload_to_ftp_host_failed_)); } }, 0); return; } if (emailAddress != null && ftpHostName != null) { // EmailSender through IR controlled gmail system. SSLEmailSender sender = new SSLEmailSender( activity.getString(R.string.automatic_email_username), activity.getString(R.string.automatic_email_password)); // consider // this // public // knowledge. try { sender.sendMail(activity.getString(R.string.vidiom_automatic_email), // subject.getText().toString(), activity.getString(R.string.url_of_hosted_video_is_) + " " + ftpHostName, // body.getText().toString(), activity.getString(R.string.automatic_email_from), // from.getText().toString(), emailAddress // to.getText().toString() ); } catch (Exception e) { Log.e(TAG, e.getMessage(), e); } } // Log record of this URL in POSTs table dbutils.creatHostDetailRecordwithNewVideoUploaded(sdrecord_id, ftpHostName, ftpHostName, ""); mainapp.removeSDFileRecordIDfromUploadingTrack(sdrecord_id, TYPE_FTP); // Use the handler to execute a Runnable on the // main thread in order to have access to the // UI elements. handler.postDelayed(new Runnable() { public void run() { // Update UI // Indicate back to calling activity the result! // update uploadInProgress state also. ((VidiomActivity) activity).finishedUploading(true); ((VidiomActivity) activity) .createNotification(res.getString(R.string.upload_to_ftp_host_succeeded_)); } }, 0); } }); t.start(); return t; }
From source file:com.ludoscity.findmybikes.activities.NearbyActivity.java
private Runnable createUpdateRefreshRunnableCode() { return new Runnable() { private boolean mPagerReady = false; private NumberFormat mNumberFormat = NumberFormat.getInstance(); /*private final long startTime = System.currentTimeMillis(); private long lastRunTime;/*from ww w . j a v a 2 s .c om*/ private long lastUpdateTime = System.currentTimeMillis(); //Update should be run automatically ? */ @Override public void run() { long now = System.currentTimeMillis(); if (mRedrawMarkersTask == null && getListPagerAdapter().isViewPagerReady() && (!mPagerReady || mRefreshTabs)) { //When restoring, we don't need to setup everything from here if (!mStationMapFragment.isRestoring()) { //TODO figure out how to properly determine restoration setupTabPages(); if (isLookingForBike()) //onPageSelected is called by framework on B tab restoration onPageSelected(StationListPagerAdapter.BIKE_STATIONS); } mPagerReady = true; } //Update not already in progress if (mPagerReady && mDownloadWebTask == null && mRedrawMarkersTask == null && mFindNetworkTask == null) { long runnableLastRefreshTimestamp = DBHelper.getLastUpdateTimestamp(getApplicationContext()); long difference = now - runnableLastRefreshTimestamp; StringBuilder pastStringBuilder = new StringBuilder(); StringBuilder futureStringBuilder = new StringBuilder(); if (DBHelper.isBikeNetworkIdAvailable(getApplicationContext())) { //First taking care of past time... if (difference < DateUtils.MINUTE_IN_MILLIS) pastStringBuilder.append(getString(R.string.moments)); else pastStringBuilder.append(getString(R.string.il_y_a)) .append(mNumberFormat.format(difference / DateUtils.MINUTE_IN_MILLIS)) .append(" ").append(getString(R.string.min_abbreviated)); } //mStatusTextView.setText(Long.toString(difference / DateUtils.MINUTE_IN_MILLIS) +" "+ getString(R.string.minsAgo) + " " + getString(R.string.fromCitibik_es) ); //long differenceInMinutes = difference / DateUtils.MINUTE_IN_MILLIS; //from : http://stackoverflow.com/questions/25355611/how-to-get-time-difference-between-two-dates-in-android-app //long differenceInSeconds = difference / DateUtils.SECOND_IN_MILLIS; // formatted will be HH:MM:SS or MM:SS //String formatted = DateUtils.formatElapsedTime(differenceInSeconds); //... then about next update if (Utils.Connectivity.isConnected(getApplicationContext())) { getListPagerAdapter().setRefreshEnableAll(true); if (!mSearchFAB.isEnabled()) { mSearchFAB.show(); mSearchFAB.setEnabled(true); if (mOnboardingSnackBar != null && mOnboardingSnackBar.getView().getTag() != null) if (!checkOnboarding(eONBOARDING_LEVEL.ONBOARDING_LEVEL_FULL, eONBOARDING_STEP.ONBOARDING_STEP_SEARCH_SHOWCASE)) checkOnboarding(eONBOARDING_LEVEL.ONBOARDING_LEVEL_LIGHT, eONBOARDING_STEP.ONBOARDING_STEP_MAIN_CHOICE_HINT); mStatusBar.setBackgroundColor( ContextCompat.getColor(NearbyActivity.this, R.color.theme_primary_dark)); } if (DBHelper.isBikeNetworkIdAvailable(getApplicationContext())) { if (!DBHelper.getAutoUpdate(getApplicationContext())) { futureStringBuilder.append(getString(R.string.pull_to_refresh)); } else { //Should come from something keeping tabs on time, maybe this runnable itself long wishedUpdateTime = runnableLastRefreshTimestamp + NearbyActivity.this.getApplicationContext().getResources() .getInteger(R.integer.update_auto_interval_minute) * 1000 * 60; //comes from Prefs //Debug //long wishedUpdateTime = runnableLastRefreshTimestamp + 15 * 1000; //comes from Prefs if (now >= wishedUpdateTime) { mDownloadWebTask = new DownloadWebTask(); mDownloadWebTask.execute(); } else { futureStringBuilder.append(getString(R.string.nextUpdate)).append(" "); long differenceSecond = (wishedUpdateTime - now) / DateUtils.SECOND_IN_MILLIS; // formatted will be HH:MM:SS or MM:SS futureStringBuilder.append(DateUtils.formatElapsedTime(differenceSecond)); } } if (difference >= NearbyActivity.this.getApplicationContext().getResources() .getInteger(R.integer.outdated_data_time_minute) * 60 * 1000 && !mDataOutdated) { mDataOutdated = true; if (mDownloadWebTask == null) { //Auto update didn't kick in. If task cancels it will execute same code then mRefreshMarkers = true; refreshMap(); mStatusBar.setBackgroundColor( ContextCompat.getColor(NearbyActivity.this, R.color.theme_accent)); getListPagerAdapter().setOutdatedDataAll(true); } } } } else { futureStringBuilder.append(getString(R.string.no_connectivity)); getListPagerAdapter().setRefreshEnableAll(false); mSearchFAB.setEnabled(false); mSearchFAB.hide(); if (getListPagerAdapter() .getHighlightedStationForPage(StationListPagerAdapter.BIKE_STATIONS) != null && mOnboardingSnackBar != null && mOnboardingSnackBar.getView().getTag() != null && !((String) mOnboardingSnackBar.getView().getTag()) .equalsIgnoreCase("NO_CONNECTIVITY")) checkOnboarding(eONBOARDING_LEVEL.ONBOARDING_LEVEL_LIGHT, eONBOARDING_STEP.ONBOARDING_STEP_MAIN_CHOICE_HINT); mStatusBar.setBackgroundColor( ContextCompat.getColor(NearbyActivity.this, R.color.theme_accent)); } if (mDownloadWebTask == null) mStatusTextView.setText(String.format(getString(R.string.status_string), pastStringBuilder.toString(), futureStringBuilder.toString())); //pulling the trigger on auto select if (mDownloadWebTask == null && mRedrawMarkersTask == null && mFindNetworkTask == null && !mClosestBikeAutoSelected && getListPagerAdapter() .isRecyclerViewReadyForItemSelection(StationListPagerAdapter.BIKE_STATIONS) && mStationMapFragment.isMapReady()) { //Requesting raw string with availability String rawClosest = getListPagerAdapter().retrieveClosestRawIdAndAvailability(true); getListPagerAdapter().highlightStationforId(true, Utils.extractClosestAvailableStationIdFromProcessedString(rawClosest)); getListPagerAdapter().smoothScrollHighlightedInViewForPage( StationListPagerAdapter.BIKE_STATIONS, isAppBarExpanded()); final StationItem closestBikeStation = getListPagerAdapter() .getHighlightedStationForPage(StationListPagerAdapter.BIKE_STATIONS); mStationMapFragment.setPinOnStation(true, closestBikeStation.getId()); getListPagerAdapter().notifyStationAUpdate(closestBikeStation.getLocation(), mCurrentUserLatLng); hideSetupShowTripDetailsWidget(); getListPagerAdapter().setupBTabStationARecap(closestBikeStation, mDataOutdated); if (isLookingForBike()) { if (mTripDetailsWidget.getVisibility() == View.INVISIBLE) { mDirectionsLocToAFab.show(); } mAutoSelectBikeFab.hide(); mStationMapFragment.setMapPaddingRight(0); if (mStationMapFragment.getMarkerBVisibleLatLng() == null) { mStationListViewPager.setCurrentItem(StationListPagerAdapter.DOCK_STATIONS, true); mFavoritesSheetFab.showFab(); //if onboarding not happening... if (!checkOnboarding(eONBOARDING_LEVEL.ONBOARDING_LEVEL_FULL, eONBOARDING_STEP.ONBOARDING_STEP_SEARCH_SHOWCASE) && !checkOnboarding(eONBOARDING_LEVEL.ONBOARDING_LEVEL_LIGHT, eONBOARDING_STEP.ONBOARDING_STEP_MAIN_CHOICE_HINT)) { //...open favorites sheet final Handler handler = new Handler(); handler.postDelayed(new Runnable() { @Override public void run() { if (!mFavoritePickerFAB.isShowRunning()) { mFavoritesSheetFab.showSheet(); } else handler.postDelayed(this, 10); } }, 50); } } else { animateCameraToShowUserAndStation(closestBikeStation); } } //Bug on older API levels. Dismissing by hand fixes it. // First biggest bug happened here. Putting defensive code //TODO: investigate how state is maintained, Snackbar is destroyed by framework on screen orientation change //TODO: Refactor this spgathetti is **TOP** priosity //and probably long background state. if (mFindBikesSnackbar != null) { mFindBikesSnackbar.dismiss(); } Handler handler = new Handler(); handler.postDelayed(new Runnable() { @Override public void run() { if (mDataOutdated) { mFindBikesSnackbar = Utils.Snackbar.makeStyled(mCoordinatorLayout, R.string.auto_bike_select_outdated, Snackbar.LENGTH_LONG, ContextCompat.getColor(NearbyActivity.this, R.color.theme_accent)); } else if (!closestBikeStation.isLocked() && closestBikeStation.getFree_bikes() > DBHelper .getCriticalAvailabilityMax(NearbyActivity.this)) { mFindBikesSnackbar = Utils.Snackbar.makeStyled(mCoordinatorLayout, R.string.auto_bike_select_found, Snackbar.LENGTH_LONG, ContextCompat.getColor(NearbyActivity.this, R.color.snackbar_green)); } else { mFindBikesSnackbar = Utils.Snackbar.makeStyled(mCoordinatorLayout, R.string.auto_bike_select_none, Snackbar.LENGTH_LONG, ContextCompat.getColor(NearbyActivity.this, R.color.theme_accent)); } if (mOnboardingSnackBar == null) mFindBikesSnackbar.show(); } }, 500); mClosestBikeAutoSelected = true; //launch twitter task if not already running, pass it the raw String if (Utils.Connectivity.isConnected(getApplicationContext()) && //data network available mUpdateTwitterTask == null && //not already tweeting rawClosest.length() > 32 + StationRecyclerViewAdapter.AOK_AVAILABILITY_POSTFIX.length() && //validate format - 32 is station ID length (rawClosest.contains(StationRecyclerViewAdapter.AOK_AVAILABILITY_POSTFIX) || rawClosest.contains(StationRecyclerViewAdapter.BAD_AVAILABILITY_POSTFIX)) && //validate content !mDataOutdated) { mUpdateTwitterTask = new UpdateTwitterStatusTask(); mUpdateTwitterTask.execute(rawClosest); } } //Checking if station is closest bike if (mDownloadWebTask == null && mRedrawMarkersTask == null && mFindNetworkTask == null && mStationMapFragment.isMapReady()) { if (!isStationAClosestBike()) { if (mStationMapFragment.getMarkerBVisibleLatLng() == null) { mClosestBikeAutoSelected = false; } else if (isLookingForBike() && !mClosestBikeAutoSelected) { mStationMapFragment.setMapPaddingRight( (int) getResources().getDimension(R.dimen.map_fab_padding)); mAutoSelectBikeFab.show(); animateCameraToShowUserAndStation(getListPagerAdapter() .getHighlightedStationForPage(StationListPagerAdapter.BIKE_STATIONS)); } } } } //UI will be refreshed every second int nextTimeMillis = 1000; if (!mPagerReady) //Except on init nextTimeMillis = 100; mUpdateRefreshHandler.postDelayed(mUpdateRefreshRunnableCode, nextTimeMillis); } }; }
From source file:org.brandroid.openmanager.activities.OpenExplorer.java
public void handleRefreshMedia(final String path, boolean keepChecking, final int retries) { if (!keepChecking || retries <= 0) { refreshBookmarks();/* ww w. j av a 2 s . c o m*/ return; } final Handler handler = new Handler(); handler.postDelayed(new Runnable() { public void run() { Logger.LogDebug("Check " + retries + " for " + path); try { StatFs sf = new StatFs(path); if (sf.getBlockCount() == 0) throw new Exception("No blocks"); showToast(getResources().getString(R.string.s_alert_new_media) + " " + getVolumeName(path) + " @ " + DialogHandler.formatSize((long) sf.getBlockSize() * (long) sf.getAvailableBlocks())); refreshBookmarks(); if (mLastPath.getPath().equals(path)) goHome(); } catch (Throwable e) { Logger.LogWarning("Couldn't read " + path); handleRefreshMedia(path, true, retries - 1); // retry again in 1/2 second } } }, 1000); }
From source file:com.lgallardo.qbittorrentclient.RefreshListener.java
public void refreshWithDelay(final String state, final String label, int seconds) { seconds *= 1000;//ww w . jav a 2 s . co m final Handler handler = new Handler(); handler.postDelayed(new Runnable() { @Override public void run() { // Do something after 5s = 5000ms refresh(state, label); } }, seconds); }
From source file:org.witness.ssc.xfer.utils.PublishingUtils.java
private String uploadMetaData(final Activity activity, final Handler handler, String filePath, String title, String description, boolean retry) throws IOException { String uploadUrl = INITIAL_UPLOAD_URL; HttpURLConnection urlConnection = getGDataUrlConnection(uploadUrl); urlConnection.setRequestMethod("POST"); urlConnection.setDoOutput(true);//w w w .j av a 2 s . co m urlConnection.setRequestProperty("Content-Type", "application/atom+xml"); // urlConnection.setRequestProperty("Content-Length", newValue); urlConnection.setRequestProperty("Slug", filePath); String atomData = null; String category = DEFAULT_VIDEO_CATEGORY; this.tags = DEFAULT_VIDEO_TAGS; String template = readFile(activity, R.raw.gdata).toString(); // Workarounds for corner cases. Youtube doesnt like empty titles if (title == null || title.length() == 0) { title = "Untitled"; } if (description == null || description.length() == 0) { description = "No description"; } atomData = String.format(template, title, description, category, this.tags); OutputStreamWriter outStreamWriter = null; int responseCode = -1; try { outStreamWriter = new OutputStreamWriter(urlConnection.getOutputStream()); outStreamWriter.write(atomData); outStreamWriter.close(); /* * urlConnection.connect(); InputStream is = * urlConnection.getInputStream(); BufferedReader in = new * BufferedReader(new InputStreamReader(is)); String inputLine; * * while ((inputLine = in.readLine()) != null) { * Log.d(TAG,inputLine); } in.close(); */ responseCode = urlConnection.getResponseCode(); // ERROR LOGGING InputStream is = urlConnection.getErrorStream(); if (is != null) { Log.e(TAG, " Error stream from Youtube available!"); BufferedReader in = new BufferedReader(new InputStreamReader(is)); String inputLine; while ((inputLine = in.readLine()) != null) { Log.d(TAG, inputLine); } in.close(); Map<String, List<String>> hfs = urlConnection.getHeaderFields(); for (Entry<String, List<String>> hf : hfs.entrySet()) { Log.d(TAG, " entry : " + hf.getKey()); List<String> vals = hf.getValue(); for (String s : vals) { Log.d(TAG, "vals:" + s); } } } } catch (IOException e) { // // Catch IO Exceptions here, like UnknownHostException, so we can // detect network failures, and send a notification // Log.d(TAG, " Error occured in uploadMetaData! "); e.printStackTrace(); responseCode = -1; outStreamWriter = null; // Use the handler to execute a Runnable on the // main thread in order to have access to the // UI elements. handler.postDelayed(new Runnable() { public void run() { // Update UI // Indicate back to calling activity the result! // update uploadInProgress state also. ((SSCXferActivity) activity).finishedUploading(false); ((SSCXferActivity) activity) .createNotification(res.getString(R.string.upload_to_youtube_host_failed_)); } }, 0); // forward it on! throw e; } if (responseCode < 200 || responseCode >= 300) { // The response code is 40X if ((responseCode + "").startsWith("4") && retry) { Log.d(TAG, "retrying to fetch auth token for " + youTubeName); this.clientLoginToken = authorizer.getFreshAuthToken(youTubeName, clientLoginToken); // Try again with fresh token return uploadMetaData(activity, handler, filePath, title, description, false); } else { // Probably not authorised! // Need to setup a Youtube account. // Use the handler to execute a Runnable on the // main thread in order to have access to the // UI elements. handler.postDelayed(new Runnable() { public void run() { // Update UI // Indicate back to calling activity the result! // update uploadInProgress state also. ((SSCXferActivity) activity).finishedUploading(false); ((SSCXferActivity) activity) .createNotification(res.getString(R.string.upload_to_youtube_host_failed_)); } }, 0); throw new IOException(String.format("response code='%s' (code %d)" + " for %s", urlConnection.getResponseMessage(), responseCode, urlConnection.getURL())); } } return urlConnection.getHeaderField("Location"); }