List of usage examples for android.widget ProgressBar setProgress
@android.view.RemotableViewMethod public synchronized void setProgress(int progress)
From source file:com.mariogrip.octodroid.mainActivity.java
private void Fill() { switch (pos) { case 0:/*from w w w . jav a2 s.c om*/ try { util.logD("Running runner"); TextView oflline = (TextView) findViewById(R.id.textView_offline); if (memory.isServerUp()) { oflline.setText(""); try { if (util_get.isConnected()) { final Spinner spinner = (Spinner) findViewById(R.id.spinner); spinner.setEnabled(false); final Spinner spinner2 = (Spinner) findViewById(R.id.spinner2); spinner2.setEnabled(false); final Button right = (Button) findViewById(R.id.buttonConDis); right.setText("Disconnect"); right.setEnabled(true); } else { final Spinner spinner = (Spinner) findViewById(R.id.spinner); spinner.setEnabled(true); final Spinner spinner2 = (Spinner) findViewById(R.id.spinner2); spinner2.setEnabled(true); final Button right = (Button) findViewById(R.id.buttonConDis); right.setText("Connect"); right.setEnabled(true); } } catch (Exception e) { } ProgressBar progress = (ProgressBar) findViewById(R.id.progressBar); TextView texttime = (TextView) findViewById(R.id.textView11_time); TextView textpri = (TextView) findViewById(R.id.textView16_printed); TextView textest = (TextView) findViewById(R.id.textView13_est); TextView textfile = (TextView) findViewById(R.id.textView11_file); TextView textmaci = (TextView) findViewById(R.id.textView10_maci); TextView texttarT = (TextView) findViewById(R.id.textView18_tar_t); TextView textcurT = (TextView) findViewById(R.id.textView18_cur_T); TextView textBcur = (TextView) findViewById(R.id.textView18_Bcur_T); TextView textBtar = (TextView) findViewById(R.id.textView18_Btar_T); TextView textprinttime = (TextView) findViewById(R.id.textView17_print_time); // TextView texthei = (TextView) findViewById(R.id.textView15_hei); //TextView textfila = (TextView) findViewById(R.id.textView12_fila); //TextView texttimel = (TextView) findViewById(R.id.textView14_timel); textfile.setText(" " + memory.job.file.name); textpri.setText(" " + util.toMBGB(memory.job.progress.filepos).toString() + "/" + util.toMBGB(memory.job.file.size).toString()); texttime.setText(" " + util.toHumanRead(memory.job.progress.PrintTimeLeft)); textest.setText(" " + util.toHumanRead(memory.job.estimatedPrintTime)); textmaci.setText(" " + memory.connection.current.state); texttarT.setText(" " + memory.temp.target.Ext[0] + "C"); textcurT.setText(" " + memory.temp.current.Ext[0] + "C"); textBcur.setText(" " + memory.temp.current.Bed[0] + "C"); textBtar.setText(" " + memory.temp.target.Bed[0] + "C"); textprinttime.setText(" " + util.toHumanRead(memory.job.progress.printTime)); progress.setProgress(util.getProgress()); // textfila.setText(" " + memory.Filament); // texttimel.setText(" " + memory.Timelapse); // texthei.setText(" " + memory.Height); } else { TextView textmaci = (TextView) findViewById(R.id.textView10_maci); textmaci.setText("Cannot connect to\n" + ip); oflline.setText("Offline"); } } catch (Exception v) { v.printStackTrace(); } break; case 2: TextView oflline = (TextView) findViewById(R.id.textView_offline); if (memory.isServerUp()) { try { oflline.setText(""); ProgressBar progress = (ProgressBar) findViewById(R.id.progressBar); TextView texttime = (TextView) findViewById(R.id.textView11_time); texttime.setText(" " + util.toHumanRead(memory.job.progress.PrintTimeLeft)); progress.setProgress(util.getProgress()); } catch (Exception v) { } } else { oflline.setText("Offline"); } break; case 1: TextView oflline2 = (TextView) findViewById(R.id.textView_offline); if (memory.isServerUp()) { try { oflline2.setText(""); ProgressBar progresss = (ProgressBar) findViewById(R.id.progressBar); TextView texttimes = (TextView) findViewById(R.id.textView11_time); texttimes.setText(" " + util.toHumanRead(memory.job.progress.getPrintTimeLeft())); progresss.setProgress(util.getProgress()); TextView textbed = (TextView) findViewById(R.id.textView_CurentTemp_bed_Tempcard); TextView textext = (TextView) findViewById(R.id.textView_CurentTemp_ext_TempCard); textbed.setText(memory.temp.current.getBed()[0] + "C"); textext.setText(memory.temp.current.getExt()[0] + "C"); } catch (Exception v) { } } else { oflline2.setText("Offline"); } break; default: break; } }
From source file:org.camlistore.CamliActivity.java
@Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.main);/*from ww w. j a v a2 s. c o m*/ Looper.myQueue().addIdleHandler(mIdleHandler); final Button buttonToggle = (Button) findViewById(R.id.buttonToggle); final TextView textStatus = (TextView) findViewById(R.id.textStatus); final TextView textStats = (TextView) findViewById(R.id.textStats); final TextView textErrors = (TextView) findViewById(R.id.textErrors); final TextView textBlobsRemain = (TextView) findViewById(R.id.textBlobsRemain); final TextView textUploadStatus = (TextView) findViewById(R.id.textUploadStatus); final TextView textByteStatus = (TextView) findViewById(R.id.textByteStatus); final ProgressBar progressBytes = (ProgressBar) findViewById(R.id.progressByteStatus); final TextView textFileStatus = (TextView) findViewById(R.id.textFileStatus); final ProgressBar progressFile = (ProgressBar) findViewById(R.id.progressFileStatus); buttonToggle.setOnClickListener(new OnClickListener() { @Override public void onClick(View btn) { Log.d(TAG, "button click! text=" + buttonToggle.getText()); if (getString(R.string.pause).equals(buttonToggle.getText())) { try { Log.d(TAG, "Pausing.."); mServiceStub.pause(); } catch (RemoteException e) { } } else if (getString(R.string.resume).equals(buttonToggle.getText())) { try { Log.d(TAG, "Resuming.."); mServiceStub.resume(); } catch (RemoteException e) { } } } }); mCallback = new IStatusCallback.Stub() { private volatile int mLastBlobsUploadRemain = 0; private volatile int mLastBlobsDigestRemain = 0; @Override public void logToClient(String stuff) throws RemoteException { // TODO Auto-generated method stub } @Override public void setUploading(final boolean uploading) throws RemoteException { mHandler.post(new Runnable() { @Override public void run() { if (uploading) { buttonToggle.setText(R.string.pause); textStatus.setText(R.string.uploading); textErrors.setText(""); } else if (mLastBlobsDigestRemain > 0) { buttonToggle.setText(R.string.pause); textStatus.setText(R.string.digesting); } else { buttonToggle.setText(R.string.resume); int stepsRemain = mLastBlobsUploadRemain + mLastBlobsDigestRemain; textStatus.setText(stepsRemain > 0 ? "Paused." : "Idle."); } } }); } @Override public void setFileStatus(final int done, final int inFlight, final int total) throws RemoteException { mHandler.post(new Runnable() { @Override public void run() { boolean finished = (done == total && mLastBlobsDigestRemain == 0); buttonToggle.setEnabled(!finished); progressFile.setMax(total); progressFile.setProgress(done); progressFile.setSecondaryProgress(done + inFlight); if (finished) { buttonToggle.setText(getString(R.string.pause_resume)); } StringBuilder filesUploaded = new StringBuilder(40); if (done < 2) { filesUploaded.append(done).append(" file uploaded"); } else { filesUploaded.append(done).append(" files uploaded"); } textFileStatus.setText(filesUploaded.toString()); StringBuilder sb = new StringBuilder(40); sb.append("Files to upload: ").append(total - done); textBlobsRemain.setText(sb.toString()); } }); } @Override public void setByteStatus(final long done, final int inFlight, final long total) throws RemoteException { mHandler.post(new Runnable() { @Override public void run() { // setMax takes an (signed) int, but 2GB is a totally // reasonable upload size, so use units of 1KB instead. progressBytes.setMax((int) (total / 1024L)); progressBytes.setProgress((int) (done / 1024L)); // TODO: renable once pk-put properly sends inflight information // progressBytes.setSecondaryProgress(progressBytes.getProgress() + inFlight / 1024); StringBuilder bytesUploaded = new StringBuilder(40); if (done < 2) { bytesUploaded.append(done).append(" byte uploaded"); } else { bytesUploaded.append(done).append(" bytes uploaded"); } textByteStatus.setText(bytesUploaded.toString()); } }); } @Override public void setUploadStatusText(final String text) throws RemoteException { mHandler.post(new Runnable() { @Override public void run() { textUploadStatus.setText(text); } }); } @Override public void setUploadStatsText(final String text) throws RemoteException { // We were getting these status updates so quickly that the calls to TextView.setText // were consuming all CPU on the main thread and it was stalling the main thread // for seconds, sometimes even triggering device freezes. Ridiculous. So instead, // only update this every 30 milliseconds, otherwise wait for the looper to be idle // to update it. mHandler.post(new Runnable() { @Override public void run() { mStatusTextWant = text; long now = System.currentTimeMillis(); if (mLastStatusUpdate < now - 30) { mStatusTextCurrent = mStatusTextWant; textStats.setText(mStatusTextWant); mLastStatusUpdate = System.currentTimeMillis(); } } }); } public void setUploadErrorsText(final String text) throws RemoteException { mHandler.post(new Runnable() { @Override public void run() { textErrors.setText(text); } }); } }; }
From source file:com.synox.android.ui.activity.FileActivity.java
/** * Retrieves user quota if available//from w w w. ja v a 2 s. c o m * * @param navigationDrawerLayout */ private void getUserQuota(final NavigationView navigationDrawerLayout, final String user) { // set user space information Thread t = new Thread(new Runnable() { public void run() { try { OwnCloudAccount ocAccount = new OwnCloudAccount(mAccount, MainApp.getAppContext()); OwnCloudClient client = OwnCloudClientManagerFactory.getDefaultSingleton() .getClientFor(ocAccount, MainApp.getAppContext()); GetMethod get = null; final ProgressBar quotaProgress = (ProgressBar) navigationDrawerLayout .findViewById(R.id.usage_progress); final LinearLayout quotaInformation = (LinearLayout) navigationDrawerLayout .findViewById(R.id.quotaInformation); try { get = new GetMethod( client.getBaseUri() + "/ocs/v1.php/cloud/users/" + user + "?format=json"); int status = client.executeMethod(get); if (status == HttpStatus.SC_OK) { JSONObject json = new JSONObject(get.getResponseBodyAsString()); JSONObject ocs = json.getJSONObject("ocs"); JSONObject meta = ocs.getJSONObject("meta"); JSONObject data = ocs.getJSONObject("data"); JSONObject quota = data.getJSONObject("quota"); if (meta.getString("statuscode").equals("100")) { try { final long used = Long.parseLong(quota.getString("used")); final long total = Long.parseLong(quota.getString("total")); final int relative = (int) Math.ceil(quota.getDouble("relative")); runOnUiThread(new Runnable() { @Override public void run() { if (quotaProgress != null) { if (quotaInformation.getVisibility() == View.INVISIBLE) { Animation animation = AnimationUtils.loadAnimation( navigationDrawerLayout.getContext(), R.anim.abc_slide_in_bottom); quotaInformation.setAnimation(animation); } quotaInformation.setVisibility(View.VISIBLE); quotaProgress.setProgress(relative); } else { quotaInformation.setVisibility(View.INVISIBLE); } TextView usageText = (TextView) navigationDrawerLayout .findViewById(R.id.usage_text); usageText.setText(String.format(getString(R.string.usage_text), DisplayUtils.bytesToHumanReadable(used), DisplayUtils.bytesToHumanReadable(total))); } }); } catch (NumberFormatException nfe) { Log_OC.e(this.getClass().getName(), "Error retrieving quota usage from server."); } } } else { client.exhaustResponse(get.getResponseBodyAsStream()); } } catch (final Exception e) { runOnUiThread(new Runnable() { @Override public void run() { quotaInformation.setVisibility(View.INVISIBLE); e.printStackTrace(); } }); } finally { if (get != null) { get.releaseConnection(); } } } catch (com.synox.android.lib.common.accounts.AccountUtils.AccountNotFoundException e) { Log_OC.e(this.getClass().getName(), e.getMessage()); } catch (AuthenticatorException | OperationCanceledException | IOException e) { Log_OC.e(this.getClass().getName(), e.getMessage()); } } }); t.start(); }
From source file:com.cw.litenote.note.Note_adapter.java
private void setWebView(final CustomWebView webView, Object object, int whichView) { final SharedPreferences pref_web_view = act.getSharedPreferences("web_view", 0); final ProgressBar spinner = (ProgressBar) ((View) object).findViewById(R.id.loading); if (whichView == CustomWebView.TEXT_VIEW) { int scale = pref_web_view.getInt("KEY_WEB_VIEW_SCALE", 0); webView.setInitialScale(scale);/* w ww. j av a 2 s. com*/ } else if (whichView == CustomWebView.LINK_VIEW) { bWebViewIsShown = false; webView.setInitialScale(30); } int style = Note.getStyle(); webView.setBackgroundColor(ColorSet.mBG_ColorArray[style]); webView.getSettings().setBuiltInZoomControls(true); webView.getSettings().setSupportZoom(true); webView.getSettings().setUseWideViewPort(true); // customWebView.getSettings().setLoadWithOverviewMode(true); webView.getSettings().setJavaScriptEnabled(true);//warning: Using setJavaScriptEnabled can introduce XSS vulnerabilities // // speed up // if (Build.VERSION.SDK_INT >= 19) { // // chromium, enable hardware acceleration // webView.setLayerType(View.LAYER_TYPE_HARDWARE, null); // } else { // // older android version, disable hardware acceleration // webView.setLayerType(View.LAYER_TYPE_SOFTWARE, null); // } if (whichView == CustomWebView.TEXT_VIEW) { webView.setWebViewClient(new WebViewClient() { @Override public void onScaleChanged(WebView web_view, float oldScale, float newScale) { super.onScaleChanged(web_view, oldScale, newScale); // System.out.println("Note_adapter / onScaleChanged"); // System.out.println(" oldScale = " + oldScale); // System.out.println(" newScale = " + newScale); int newDefaultScale = (int) (newScale * 100); pref_web_view.edit().putInt("KEY_WEB_VIEW_SCALE", newDefaultScale).apply(); //update current position NoteUi.setFocus_notePos(pager.getCurrentItem()); } @Override public void onPageFinished(WebView view, String url) { } }); } if (whichView == CustomWebView.LINK_VIEW) { webView.setWebChromeClient(new WebChromeClient() { public void onProgressChanged(WebView view, int progress) { System.out.println("---------------- spinner progress = " + progress); if (spinner != null) { if (bWebViewIsShown) { if (progress < 100 && (spinner.getVisibility() == ProgressBar.GONE)) { webView.setVisibility(View.GONE); spinner.setVisibility(ProgressBar.VISIBLE); } spinner.setProgress(progress); if (progress > 30) bWebViewIsShown = true; } if (bWebViewIsShown || (progress == 100)) { spinner.setVisibility(ProgressBar.GONE); webView.setVisibility(View.VISIBLE); } } } @Override public void onReceivedTitle(WebView view, String title) { super.onReceivedTitle(view, title); if (!TextUtils.isEmpty(title) && !title.equalsIgnoreCase("about:blank")) { System.out.println("Note_adapter / _onReceivedTitle / title = " + title); int position = NoteUi.getFocus_notePos(); String tag = "current" + position + "textWebView"; CustomWebView textWebView = (CustomWebView) pager.findViewWithTag(tag); String strLink = db_page.getNoteLinkUri(position, true); // show title of http link if ((textWebView != null) && !Util.isYouTubeLink(strLink) && strLink.startsWith("http")) { mWebTitle = title; showTextWebView(position, textWebView); } } } }); } }
From source file:com.nextgis.maplibui.activity.ModifyAttributesActivity.java
protected void createLocationPanelView(final IGISApplication app) { if (null == mGeometry && mFeatureId == NOT_FOUND) { mLatView = (TextView) findViewById(R.id.latitude_view); mLongView = (TextView) findViewById(R.id.longitude_view); mAltView = (TextView) findViewById(R.id.altitude_view); mAccView = (TextView) findViewById(R.id.accuracy_view); final ImageButton refreshLocation = (ImageButton) findViewById(R.id.refresh); mAccurateLocation = (SwitchCompat) findViewById(R.id.accurate_location); mAccurateLocation.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() { @Override/*from www . j a v a 2 s . c om*/ public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) { if (mAccurateLocation.getTag() == null) { refreshLocation.performClick(); mAccurateLocation.setTag(new Object()); } } }); mAccuracyCE = (AppCompatSpinner) findViewById(R.id.accurate_ce); refreshLocation.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { RotateAnimation rotateAnimation = new RotateAnimation(0, 360, Animation.RELATIVE_TO_SELF, 0.5f, Animation.RELATIVE_TO_SELF, 0.5f); rotateAnimation.setDuration(500); rotateAnimation.setRepeatCount(1); refreshLocation.startAnimation(rotateAnimation); if (mAccurateLocation.isChecked()) { AlertDialog.Builder builder = new AlertDialog.Builder(ModifyAttributesActivity.this); View layout = View.inflate(ModifyAttributesActivity.this, R.layout.dialog_progress_accurate_location, null); TextView message = (TextView) layout.findViewById(R.id.message); final ProgressBar progress = (ProgressBar) layout.findViewById(R.id.progress); final TextView progressPercent = (TextView) layout.findViewById(R.id.progress_percent); final TextView progressNumber = (TextView) layout.findViewById(R.id.progress_number); final CheckBox finishBeep = (CheckBox) layout.findViewById(R.id.finish_beep); builder.setView(layout); builder.setTitle(R.string.accurate_location); final AccurateLocationTaker accurateLocation = new AccurateLocationTaker(view.getContext(), 100f, mMaxTakeCount, MAX_TAKE_TIME, PROGRESS_DELAY, (String) mAccuracyCE.getSelectedItem()); progress.setIndeterminate(true); message.setText(R.string.accurate_taking); builder.setNegativeButton(android.R.string.cancel, new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { accurateLocation.cancelTaking(); } }); builder.setOnCancelListener(new DialogInterface.OnCancelListener() { @Override public void onCancel(DialogInterface dialog) { accurateLocation.cancelTaking(); } }); builder.setOnDismissListener(new DialogInterface.OnDismissListener() { @Override public void onDismiss(DialogInterface dialog) { ControlHelper.unlockScreenOrientation(ModifyAttributesActivity.this); } }); final AlertDialog dialog = builder.create(); accurateLocation .setOnProgressUpdateListener(new AccurateLocationTaker.OnProgressUpdateListener() { @SuppressLint("SetTextI18n") @Override public void onProgressUpdate(Long... values) { int value = values[0].intValue(); if (value == 1) { progress.setIndeterminate(false); progress.setMax(mMaxTakeCount); } if (value > 0) progress.setProgress(value); progressPercent.setText(value * 100 / mMaxTakeCount + " %"); progressNumber.setText(value + " / " + mMaxTakeCount); } }); accurateLocation.setOnGetAccurateLocationListener( new AccurateLocationTaker.OnGetAccurateLocationListener() { @Override public void onGetAccurateLocation(Location accurateLocation, Long... values) { dialog.dismiss(); if (finishBeep.isChecked()) playBeep(); setLocationText(accurateLocation); } }); ControlHelper.lockScreenOrientation(ModifyAttributesActivity.this); dialog.setCanceledOnTouchOutside(false); dialog.show(); accurateLocation.startTaking(); } else if (null != app) { GpsEventSource gpsEventSource = app.getGpsEventSource(); Location location = gpsEventSource.getLastKnownLocation(); setLocationText(location); } } }); } else { //hide location panel ViewGroup rootView = (ViewGroup) findViewById(R.id.controls_list); rootView.removeView(findViewById(R.id.location_panel)); } }
From source file:org.quantumbadger.redreader.activities.ImageViewActivity.java
@Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); final SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(this); final boolean solidblack = PrefsUtility.appearance_solidblack(this, sharedPreferences); if (solidblack) getWindow().setBackgroundDrawable(new ColorDrawable(Color.BLACK)); final Intent intent = getIntent(); mUrl = General.uriFromString(intent.getDataString()); final RedditPost src_post = intent.getParcelableExtra("post"); if (mUrl == null) { General.quickToast(this, "Invalid URL. Trying web browser."); revertToWeb();//from w w w .ja va2 s .c o m return; } Log.i("ImageViewActivity", "Loading URL " + mUrl.toString()); final ProgressBar progressBar = new ProgressBar(this, null, android.R.attr.progressBarStyleHorizontal); final LinearLayout layout = new LinearLayout(this); layout.setOrientation(LinearLayout.VERTICAL); layout.addView(progressBar); CacheManager.getInstance(this) .makeRequest(mRequest = new CacheRequest(mUrl, RedditAccountManager.getAnon(), null, Constants.Priority.IMAGE_VIEW, 0, CacheRequest.DownloadType.IF_NECESSARY, Constants.FileType.IMAGE, false, false, false, this) { private void setContentView(View v) { layout.removeAllViews(); layout.addView(v); v.getLayoutParams().width = ViewGroup.LayoutParams.MATCH_PARENT; v.getLayoutParams().height = ViewGroup.LayoutParams.MATCH_PARENT; } @Override protected void onCallbackException(Throwable t) { BugReportActivity.handleGlobalError(context.getApplicationContext(), new RRError(null, null, t)); } @Override protected void onDownloadNecessary() { AndroidApi.UI_THREAD_HANDLER.post(new Runnable() { @Override public void run() { progressBar.setVisibility(View.VISIBLE); progressBar.setIndeterminate(true); } }); } @Override protected void onDownloadStarted() { } @Override protected void onFailure(final RequestFailureType type, Throwable t, StatusLine status, final String readableMessage) { final RRError error = General.getGeneralErrorForFailure(context, type, t, status, url.toString()); AndroidApi.UI_THREAD_HANDLER.post(new Runnable() { public void run() { // TODO handle properly mRequest = null; progressBar.setVisibility(View.GONE); layout.addView(new ErrorView(ImageViewActivity.this, error)); } }); } @Override protected void onProgress(final boolean authorizationInProgress, final long bytesRead, final long totalBytes) { AndroidApi.UI_THREAD_HANDLER.post(new Runnable() { @Override public void run() { progressBar.setVisibility(View.VISIBLE); progressBar.setIndeterminate(authorizationInProgress); progressBar.setProgress((int) ((100 * bytesRead) / totalBytes)); } }); } @Override protected void onSuccess(final CacheManager.ReadableCacheFile cacheFile, long timestamp, UUID session, boolean fromCache, final String mimetype) { if (mimetype == null || (!Constants.Mime.isImage(mimetype) && !Constants.Mime.isVideo(mimetype))) { revertToWeb(); return; } final InputStream cacheFileInputStream; try { cacheFileInputStream = cacheFile.getInputStream(); } catch (IOException e) { notifyFailure(RequestFailureType.PARSE, e, null, "Could not read existing cached image."); return; } if (cacheFileInputStream == null) { notifyFailure(RequestFailureType.CACHE_MISS, null, null, "Could not find cached image"); return; } if (Constants.Mime.isVideo(mimetype)) { AndroidApi.UI_THREAD_HANDLER.post(new Runnable() { public void run() { if (mIsDestroyed) return; mRequest = null; try { final RelativeLayout layout = new RelativeLayout(context); layout.setGravity(Gravity.CENTER); final VideoView videoView = new VideoView(ImageViewActivity.this); videoView.setVideoURI(cacheFile.getUri()); layout.addView(videoView); setContentView(layout); layout.getLayoutParams().width = ViewGroup.LayoutParams.MATCH_PARENT; layout.getLayoutParams().height = ViewGroup.LayoutParams.MATCH_PARENT; videoView.setLayoutParams( new RelativeLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT)); videoView.setOnPreparedListener(new MediaPlayer.OnPreparedListener() { @Override public void onPrepared(MediaPlayer mp) { mp.setLooping(true); videoView.start(); } }); videoView.setOnErrorListener(new MediaPlayer.OnErrorListener() { @Override public boolean onError(final MediaPlayer mediaPlayer, final int i, final int i1) { revertToWeb(); return true; } }); videoView.setOnTouchListener(new View.OnTouchListener() { @Override public boolean onTouch(final View view, final MotionEvent motionEvent) { finish(); return true; } }); } catch (OutOfMemoryError e) { General.quickToast(context, R.string.imageview_oom); revertToWeb(); } catch (Throwable e) { General.quickToast(context, R.string.imageview_invalid_video); revertToWeb(); } } }); } else if (Constants.Mime.isImageGif(mimetype)) { final PrefsUtility.GifViewMode gifViewMode = PrefsUtility .pref_behaviour_gifview_mode(context, sharedPreferences); if (gifViewMode == PrefsUtility.GifViewMode.INTERNAL_BROWSER) { revertToWeb(); return; } else if (gifViewMode == PrefsUtility.GifViewMode.EXTERNAL_BROWSER) { AndroidApi.UI_THREAD_HANDLER.post(new Runnable() { @Override public void run() { LinkHandler.openWebBrowser(ImageViewActivity.this, Uri.parse(mUrl.toString())); finish(); } }); return; } if (AndroidApi.isIceCreamSandwichOrLater() && gifViewMode == PrefsUtility.GifViewMode.INTERNAL_MOVIE) { AndroidApi.UI_THREAD_HANDLER.post(new Runnable() { public void run() { if (mIsDestroyed) return; mRequest = null; try { final GIFView gifView = new GIFView(ImageViewActivity.this, cacheFileInputStream); setContentView(gifView); gifView.setOnClickListener(new View.OnClickListener() { public void onClick(View v) { finish(); } }); } catch (OutOfMemoryError e) { General.quickToast(context, R.string.imageview_oom); revertToWeb(); } catch (Throwable e) { General.quickToast(context, R.string.imageview_invalid_gif); revertToWeb(); } } }); } else { gifThread = new GifDecoderThread(cacheFileInputStream, new GifDecoderThread.OnGifLoadedListener() { public void onGifLoaded() { AndroidApi.UI_THREAD_HANDLER.post(new Runnable() { public void run() { if (mIsDestroyed) return; mRequest = null; imageView = new ImageView(context); imageView.setScaleType(ImageView.ScaleType.FIT_CENTER); setContentView(imageView); gifThread.setView(imageView); imageView.setOnClickListener(new View.OnClickListener() { public void onClick(View v) { finish(); } }); } }); } public void onOutOfMemory() { General.quickToast(context, R.string.imageview_oom); revertToWeb(); } public void onGifInvalid() { General.quickToast(context, R.string.imageview_invalid_gif); revertToWeb(); } }); gifThread.start(); } } else { final ImageTileSource imageTileSource; try { final long bytes = cacheFile.getSize(); final byte[] buf = new byte[(int) bytes]; try { new DataInputStream(cacheFileInputStream).readFully(buf); } catch (IOException e) { throw new RuntimeException(e); } try { imageTileSource = new ImageTileSourceWholeBitmap(buf); } catch (Throwable t) { Log.e("ImageViewActivity", "Exception when creating ImageTileSource", t); General.quickToast(context, R.string.imageview_decode_failed); revertToWeb(); return; } } catch (OutOfMemoryError e) { General.quickToast(context, R.string.imageview_oom); revertToWeb(); return; } AndroidApi.UI_THREAD_HANDLER.post(new Runnable() { public void run() { if (mIsDestroyed) return; mRequest = null; mImageViewDisplayerManager = new ImageViewDisplayListManager(imageTileSource, ImageViewActivity.this); surfaceView = new RRGLSurfaceView(ImageViewActivity.this, mImageViewDisplayerManager); setContentView(surfaceView); surfaceView.setOnClickListener(new View.OnClickListener() { public void onClick(View v) { finish(); } }); if (mIsPaused) { surfaceView.onPause(); } else { surfaceView.onResume(); } } }); } } }); final RedditPreparedPost post = src_post == null ? null : new RedditPreparedPost(this, CacheManager.getInstance(this), 0, src_post, -1, false, false, false, false, RedditAccountManager.getInstance(this).getDefaultAccount(), false); final FrameLayout outerFrame = new FrameLayout(this); outerFrame.addView(layout); if (post != null) { final SideToolbarOverlay toolbarOverlay = new SideToolbarOverlay(this); final BezelSwipeOverlay bezelOverlay = new BezelSwipeOverlay(this, new BezelSwipeOverlay.BezelSwipeListener() { public boolean onSwipe(BezelSwipeOverlay.SwipeEdge edge) { toolbarOverlay.setContents( post.generateToolbar(ImageViewActivity.this, false, toolbarOverlay)); toolbarOverlay.show(edge == BezelSwipeOverlay.SwipeEdge.LEFT ? SideToolbarOverlay.SideToolbarPosition.LEFT : SideToolbarOverlay.SideToolbarPosition.RIGHT); return true; } public boolean onTap() { if (toolbarOverlay.isShown()) { toolbarOverlay.hide(); return true; } return false; } }); outerFrame.addView(bezelOverlay); outerFrame.addView(toolbarOverlay); bezelOverlay.getLayoutParams().width = android.widget.FrameLayout.LayoutParams.MATCH_PARENT; bezelOverlay.getLayoutParams().height = android.widget.FrameLayout.LayoutParams.MATCH_PARENT; toolbarOverlay.getLayoutParams().width = android.widget.FrameLayout.LayoutParams.MATCH_PARENT; toolbarOverlay.getLayoutParams().height = android.widget.FrameLayout.LayoutParams.MATCH_PARENT; } setContentView(outerFrame); }
From source file:com.sentaroh.android.SMBSync.SMBSyncMain.java
private void autoTimer(final ThreadCtrl threadCtl, final NotifyEvent at_ne, final String msg) { setUiDisabled();/* ww w. j a va 2 s . c o m*/ final Handler handler = new Handler(); new Thread(new Runnable() { @Override public void run() {//non UI thread ProgressBar pb = (ProgressBar) findViewById(R.id.profile_progress_bar_progress); pb.setMax(ATERM_WAIT_TIME); final TextView pm = (TextView) findViewById(R.id.profile_progress_bar_msg); for (int i = 0; i < ATERM_WAIT_TIME; i++) { try { if (threadCtl.isEnabled()) { final int ix = i; handler.post(new Runnable() { //UI thread @Override public void run() { String t_msg = String.format(msg, (ATERM_WAIT_TIME - ix)); pm.setText(t_msg); showNotificationMsg(t_msg); } }); // non UI thread pb.setProgress(i); } else { break; } Thread.sleep(1000); } catch (InterruptedException e) { e.printStackTrace(); } } // dismiss progress bar dialog handler.post(new Runnable() {// UI thread @Override public void run() { LinearLayout ll_bar = (LinearLayout) findViewById(R.id.profile_progress_bar); ll_bar.setVisibility(LinearLayout.GONE); setUiEnabled(); if (mRequestAutoTimerExpired) {//Immediate process requested at_ne.notifyToListener(true, null); } else { if (threadCtl.isEnabled()) at_ne.notifyToListener(true, null); else at_ne.notifyToListener(false, null); } } }); } }).start(); }
From source file:org.telegram.ui.ChatActivity.java
@SuppressWarnings("unchecked") @Override/*from ww w . j a v a 2 s . c o m*/ public void didReceivedNotification(int id, final Object... args) { if (id == MessagesController.messagesDidLoaded) { long did = (Long) args[0]; if (did == dialog_id) { int offset = (Integer) args[1]; int count = (Integer) args[2]; boolean isCache = (Boolean) args[4]; int fnid = (Integer) args[5]; int last_unread_date = (Integer) args[8]; boolean forwardLoad = (Boolean) args[9]; boolean wasUnread = false; boolean positionToUnread = false; if (fnid != 0) { first_unread_id = (Integer) args[5]; last_unread_id = (Integer) args[6]; unread_to_load = (Integer) args[7]; positionToUnread = true; } ArrayList<MessageObject> messArr = (ArrayList<MessageObject>) args[3]; int newRowsCount = 0; unread_end_reached = last_unread_id == 0; for (int a = 0; a < messArr.size(); a++) { MessageObject obj = messArr.get(a); if (messagesDict.containsKey(obj.messageOwner.id)) { continue; } if (obj.messageOwner.id > 0) { maxMessageId = Math.min(obj.messageOwner.id, maxMessageId); minMessageId = Math.max(obj.messageOwner.id, minMessageId); } else if (currentEncryptedChat != null) { minMessageId = Math.min(obj.messageOwner.id, minMessageId); } maxDate = Math.max(maxDate, obj.messageOwner.date); if (minDate == 0 || obj.messageOwner.date < minDate) { minDate = obj.messageOwner.date; } if (!obj.messageOwner.out && obj.messageOwner.unread) { wasUnread = true; } messagesDict.put(obj.messageOwner.id, obj); ArrayList<MessageObject> dayArray = messagesByDays.get(obj.dateKey); if (dayArray == null) { dayArray = new ArrayList<MessageObject>(); messagesByDays.put(obj.dateKey, dayArray); TLRPC.Message dateMsg = new TLRPC.Message(); dateMsg.message = Utilities.formatDateChat(obj.messageOwner.date); dateMsg.id = 0; MessageObject dateObj = new MessageObject(dateMsg, null); dateObj.type = 10; if (forwardLoad) { messages.add(0, dateObj); } else { messages.add(dateObj); } newRowsCount++; } newRowsCount++; dayArray.add(obj); if (forwardLoad) { messages.add(0, obj); } else { messages.add(messages.size() - 1, obj); } if (!forwardLoad) { if (obj.messageOwner.id == first_unread_id) { TLRPC.Message dateMsg = new TLRPC.Message(); dateMsg.message = ""; dateMsg.id = 0; MessageObject dateObj = new MessageObject(dateMsg, null); dateObj.type = 15; boolean dateAdded = true; if (a != messArr.size() - 1) { MessageObject next = messArr.get(a + 1); dateAdded = !next.dateKey.equals(obj.dateKey); } messages.add(messages.size() - (dateAdded ? 0 : 1), dateObj); unreadMessageObject = dateObj; newRowsCount++; } if (obj.messageOwner.id == last_unread_id) { unread_end_reached = true; } } } if (unread_end_reached) { first_unread_id = 0; last_unread_id = 0; } if (forwardLoad) { if (messArr.size() != count) { unread_end_reached = true; first_unread_id = 0; last_unread_id = 0; } chatAdapter.notifyDataSetChanged(); loadingForward = false; } else { if (messArr.size() != count) { if (isCache) { cacheEndReaced = true; if (currentEncryptedChat != null) { endReached = true; } } else { cacheEndReaced = true; endReached = true; } } loading = false; if (chatListView != null) { if (first || scrollToTopOnResume) { chatAdapter.notifyDataSetChanged(); if (positionToUnread && unreadMessageObject != null) { if (messages.get(messages.size() - 1) == unreadMessageObject) { chatListView.setSelectionFromTop(0, Utilities.dp(-11)); } else { chatListView.setSelectionFromTop( messages.size() - messages.indexOf(unreadMessageObject), Utilities.dp(-11)); } ViewTreeObserver obs = chatListView.getViewTreeObserver(); obs.addOnPreDrawListener(new ViewTreeObserver.OnPreDrawListener() { @Override public boolean onPreDraw() { if (messages.get(messages.size() - 1) == unreadMessageObject) { chatListView.setSelectionFromTop(0, Utilities.dp(-11)); } else { chatListView.setSelectionFromTop( messages.size() - messages.indexOf(unreadMessageObject), Utilities.dp(-11)); } chatListView.getViewTreeObserver().removeOnPreDrawListener(this); return false; } }); chatListView.invalidate(); showPagedownButton(true, true); } else { chatListView.post(new Runnable() { @Override public void run() { chatListView.setSelectionFromTop(messages.size() - 1, -10000 - chatListView.getPaddingTop()); } }); } } else { int firstVisPos = chatListView.getLastVisiblePosition(); View firstVisView = chatListView.getChildAt(chatListView.getChildCount() - 1); int top = ((firstVisView == null) ? 0 : firstVisView.getTop()) - chatListView.getPaddingTop(); chatAdapter.notifyDataSetChanged(); chatListView.setSelectionFromTop(firstVisPos + newRowsCount, top); } if (paused) { scrollToTopOnResume = true; if (positionToUnread && unreadMessageObject != null) { scrollToTopUnReadOnResume = true; } } if (first) { if (chatListView.getEmptyView() == null) { if (currentEncryptedChat == null) { chatListView.setEmptyView(emptyView); } else { chatListView.setEmptyView(secretChatPlaceholder); } } } } else { scrollToTopOnResume = true; if (positionToUnread && unreadMessageObject != null) { scrollToTopUnReadOnResume = true; } } } if (first && messages.size() > 0) { if (last_unread_id != 0) { MessagesController.Instance.markDialogAsRead(dialog_id, messages.get(0).messageOwner.id, last_unread_id, 0, last_unread_date, wasUnread); } else { MessagesController.Instance.markDialogAsRead(dialog_id, messages.get(0).messageOwner.id, minMessageId, 0, maxDate, wasUnread); } first = false; } if (progressView != null) { progressView.setVisibility(View.GONE); } } } else if (id == 999) { if (animationInProgress) { invalidateAfterAnimation = true; } else { if (chatListView != null) { chatListView.invalidateViews(); } } if (emojiView != null) { emojiView.invalidateViews(); } } else if (id == MessagesController.updateInterfaces) { int updateMask = (Integer) args[0]; if ((updateMask & MessagesController.UPDATE_MASK_NAME) != 0 || (updateMask & MessagesController.UPDATE_MASK_STATUS) != 0 || (updateMask & MessagesController.UPDATE_MASK_CHAT_NAME) != 0 || (updateMask & MessagesController.UPDATE_MASK_CHAT_MEMBERS) != 0) { updateSubtitle(); updateOnlineCount(); } if ((updateMask & MessagesController.UPDATE_MASK_AVATAR) != 0 || (updateMask & MessagesController.UPDATE_MASK_CHAT_AVATAR) != 0 || (updateMask & MessagesController.UPDATE_MASK_NAME) != 0) { checkAndUpdateAvatar(); if (animationInProgress) { invalidateAfterAnimation = true; } else { if (chatListView != null) { updateVisibleRows(); } } } if ((updateMask & MessagesController.UPDATE_MASK_USER_PRINT) != 0) { CharSequence printString = MessagesController.Instance.printingStrings.get(dialog_id); if (lastPrintString != null && printString == null || lastPrintString == null && printString != null || lastPrintString != null && printString != null && !lastPrintString.equals(printString)) { updateSubtitle(); } } if ((updateMask & MessagesController.UPDATE_MASK_USER_PHONE) != 0) { updateContactStatus(); } } else if (id == MessagesController.didReceivedNewMessages) { long did = (Long) args[0]; if (did == dialog_id) { boolean updateChat = false; ArrayList<MessageObject> arr = (ArrayList<MessageObject>) args[1]; if (!unread_end_reached) { int currentMaxDate = Integer.MIN_VALUE; int currentMinMsgId = Integer.MIN_VALUE; if (currentEncryptedChat != null) { currentMinMsgId = Integer.MAX_VALUE; } boolean currentMarkAsRead = false; for (MessageObject obj : arr) { if (messagesDict.containsKey(obj.messageOwner.id)) { continue; } currentMaxDate = Math.max(currentMaxDate, obj.messageOwner.date); if (obj.messageOwner.id > 0) { currentMinMsgId = Math.max(obj.messageOwner.id, currentMinMsgId); } else if (currentEncryptedChat != null) { currentMinMsgId = Math.min(obj.messageOwner.id, currentMinMsgId); } if (!obj.messageOwner.out && obj.messageOwner.unread) { unread_to_load++; currentMarkAsRead = true; } if (obj.type == 10 || obj.type == 11) { updateChat = true; } } if (currentMarkAsRead) { if (paused) { readWhenResume = true; readWithDate = currentMaxDate; readWithMid = currentMinMsgId; } else { if (messages.size() > 0) { MessagesController.Instance.markDialogAsRead(dialog_id, messages.get(0).messageOwner.id, currentMinMsgId, 0, currentMaxDate, true); } } } updateVisibleRows(); } else { boolean markAsRead = false; int oldCount = messages.size(); for (MessageObject obj : arr) { if (messagesDict.containsKey(obj.messageOwner.id)) { continue; } if (minDate == 0 || obj.messageOwner.date < minDate) { minDate = obj.messageOwner.date; } if (obj.messageOwner.attachPath != null && obj.messageOwner.attachPath.length() != 0) { progressBarMap.put(obj.messageOwner.attachPath, null); } if (obj.messageOwner.out) { removeUnreadPlane(false); } if (!obj.messageOwner.out && unreadMessageObject != null) { unread_to_load++; } if (obj.messageOwner.id > 0) { maxMessageId = Math.min(obj.messageOwner.id, maxMessageId); minMessageId = Math.max(obj.messageOwner.id, minMessageId); } else if (currentEncryptedChat != null) { minMessageId = Math.min(obj.messageOwner.id, minMessageId); } maxDate = Math.max(maxDate, obj.messageOwner.date); messagesDict.put(obj.messageOwner.id, obj); ArrayList<MessageObject> dayArray = messagesByDays.get(obj.dateKey); if (dayArray == null) { dayArray = new ArrayList<MessageObject>(); messagesByDays.put(obj.dateKey, dayArray); TLRPC.Message dateMsg = new TLRPC.Message(); dateMsg.message = Utilities.formatDateChat(obj.messageOwner.date); dateMsg.id = 0; MessageObject dateObj = new MessageObject(dateMsg, null); dateObj.type = 10; messages.add(0, dateObj); } if (!obj.messageOwner.out && obj.messageOwner.unread) { obj.messageOwner.unread = false; markAsRead = true; } dayArray.add(0, obj); messages.add(0, obj); if (obj.type == 10 || obj.type == 11) { updateChat = true; } } if (progressView != null) { progressView.setVisibility(View.GONE); } if (chatAdapter != null) { chatAdapter.notifyDataSetChanged(); } else { scrollToTopOnResume = true; } if (chatListView != null && chatAdapter != null) { int lastVisible = chatListView.getLastVisiblePosition(); if (endReached) { lastVisible++; } if (lastVisible == oldCount) { if (paused) { scrollToTopOnResume = true; } else { chatListView.post(new Runnable() { @Override public void run() { chatListView.setSelectionFromTop(messages.size() - 1, -10000 - chatListView.getPaddingTop()); } }); } } else { showPagedownButton(true, true); } } else { scrollToTopOnResume = true; } if (markAsRead) { if (paused) { readWhenResume = true; readWithDate = maxDate; readWithMid = minMessageId; } else { MessagesController.Instance.markDialogAsRead(dialog_id, messages.get(0).messageOwner.id, minMessageId, 0, maxDate, true); } } } if (updateChat) { updateSubtitle(); checkAndUpdateAvatar(); } } } else if (id == MessagesController.closeChats) { if (messsageEditText != null && messsageEditText.isFocused()) { Utilities.hideKeyboard(messsageEditText); } removeSelfFromStack(); } else if (id == MessagesController.messagesReaded) { ArrayList<Integer> markAsReadMessages = (ArrayList<Integer>) args[0]; boolean updated = false; for (Integer ids : markAsReadMessages) { MessageObject obj = messagesDict.get(ids); if (obj != null) { obj.messageOwner.unread = false; updated = true; } } if (updated) { if (animationInProgress) { invalidateAfterAnimation = true; } else { if (chatListView != null) { updateVisibleRows(); } } } } else if (id == MessagesController.messagesDeleted) { ArrayList<Integer> markAsDeletedMessages = (ArrayList<Integer>) args[0]; boolean updated = false; for (Integer ids : markAsDeletedMessages) { MessageObject obj = messagesDict.get(ids); if (obj != null) { int index = messages.indexOf(obj); if (index != -1) { messages.remove(index); messagesDict.remove(ids); ArrayList<MessageObject> dayArr = messagesByDays.get(obj.dateKey); dayArr.remove(obj); if (dayArr.isEmpty()) { messagesByDays.remove(obj.dateKey); if (index != -1) { messages.remove(index); } } updated = true; } } } if (messages.isEmpty()) { if (!endReached && !loading) { progressView.setVisibility(View.VISIBLE); chatListView.setEmptyView(null); maxMessageId = Integer.MAX_VALUE; minMessageId = Integer.MIN_VALUE; maxDate = Integer.MIN_VALUE; minDate = 0; MessagesController.Instance.loadMessages(dialog_id, 0, 30, 0, !cacheEndReaced, minDate, classGuid, false, false); loading = true; } } if (updated && chatAdapter != null) { removeUnreadPlane(false); chatAdapter.notifyDataSetChanged(); } } else if (id == MessagesController.messageReceivedByServer) { Integer msgId = (Integer) args[0]; MessageObject obj = messagesDict.get(msgId); if (obj != null) { Integer newMsgId = (Integer) args[1]; messagesDict.remove(msgId); messagesDict.put(newMsgId, obj); obj.messageOwner.id = newMsgId; obj.messageOwner.send_state = MessagesController.MESSAGE_SEND_STATE_SENT; if (animationInProgress) { invalidateAfterAnimation = true; } else { if (chatListView != null) { updateVisibleRows(); } } if (obj.messageOwner.attachPath != null && obj.messageOwner.attachPath.length() != 0) { progressBarMap.remove(obj.messageOwner.attachPath); } } } else if (id == MessagesController.messageReceivedByAck) { Integer msgId = (Integer) args[0]; MessageObject obj = messagesDict.get(msgId); if (obj != null) { if (obj.messageOwner.attachPath != null && obj.messageOwner.attachPath.length() != 0) { progressBarMap.remove(obj.messageOwner.attachPath); } obj.messageOwner.send_state = MessagesController.MESSAGE_SEND_STATE_SENT; if (animationInProgress) { invalidateAfterAnimation = true; } else { if (chatListView != null) { updateVisibleRows(); } } } } else if (id == MessagesController.messageSendError) { Integer msgId = (Integer) args[0]; MessageObject obj = messagesDict.get(msgId); if (obj != null) { obj.messageOwner.send_state = MessagesController.MESSAGE_SEND_STATE_SEND_ERROR; if (animationInProgress) { invalidateAfterAnimation = true; } else { if (chatListView != null) { updateVisibleRows(); } } if (obj.messageOwner.attachPath != null && obj.messageOwner.attachPath.length() != 0) { progressBarMap.remove(obj.messageOwner.attachPath); } } } else if (id == 997) { MessagesController.Instance.sendMessage((Double) args[0], (Double) args[1], dialog_id); if (chatListView != null) { chatListView.setSelection(messages.size() + 1); scrollToTopOnResume = true; } } else if (id == MessagesController.chatInfoDidLoaded) { int chatId = (Integer) args[0]; if (currentChat != null && chatId == currentChat.id) { info = (TLRPC.ChatParticipants) args[1]; updateOnlineCount(); } } else if (id == FileLoader.FileUploadProgressChanged) { String location = (String) args[0]; ProgressBar bar; if ((bar = progressBarMap.get(location)) != null) { Float progress = (Float) args[1]; bar.setProgress((int) (progress * 100)); } } else if (id == FileLoader.FileDidFailedLoad) { String location = (String) args[0]; if (loadingFile.containsKey(location)) { loadingFile.remove(location); if (animationInProgress) { invalidateAfterAnimation = true; } else { if (chatListView != null) { updateVisibleRows(); } } } } else if (id == FileLoader.FileDidLoaded) { String location = (String) args[0]; if (loadingFile.containsKey(location)) { loadingFile.remove(location); if (animationInProgress) { invalidateAfterAnimation = true; } else { if (chatListView != null) { updateVisibleRows(); } } } } else if (id == FileLoader.FileLoadProgressChanged) { String location = (String) args[0]; ArrayList<ProgressBar> arr = loadingFile.get(location); if (arr != null) { Float progress = (Float) args[1]; for (ProgressBar bar : arr) { bar.setProgress((int) (progress * 100)); } } } else if (id == MessagesController.contactsDidLoaded) { updateContactStatus(); updateSubtitle(); } else if (id == MessagesController.encryptedChatUpdated) { TLRPC.EncryptedChat chat = (TLRPC.EncryptedChat) args[0]; if (currentEncryptedChat != null && chat.id == currentEncryptedChat.id) { currentEncryptedChat = chat; updateContactStatus(); updateSecretStatus(); } } else if (id == MessagesController.messagesReadedEncrypted) { int encId = (Integer) args[0]; if (currentEncryptedChat != null && currentEncryptedChat.id == encId) { int date = (Integer) args[1]; boolean started = false; for (MessageObject obj : messages) { if (!obj.messageOwner.out) { continue; } else if (obj.messageOwner.out && !obj.messageOwner.unread) { break; } if (obj.messageOwner.date <= date) { obj.messageOwner.unread = false; } } if (chatListView != null) { updateVisibleRows(); } } } }
From source file:me.ububble.speakall.fragment.ConversationChatFragment.java
private void uploadAudioToServer(String file, final Message menssage, final JSONObject dataSend, final ProgressBar progressBar, final RelativeLayout progressLayout, final TextView progressText) { try {/*from w w w. j a va 2 s . c o m*/ RequestParams p = new RequestParams(); File archivo = new File(file); p.put("audio", archivo); activity.runOnUiThread(new Runnable() { @Override public void run() { progressText.setText("0%"); } }); SpeakHttp.post("messages/" + SessionCustom.getUserId(activity) + "/upload/audio", p, new JsonHttpResponseHandler() { @Override public void onSuccess(int statusCode, Header[] headers, final JSONObject response) { super.onSuccess(statusCode, headers, response); try { final JSONObject dataResponse = response.getJSONObject("data_response"); Log.e("Respuesta", dataResponse.toString()); JSONArray photoArray = new JSONArray(); photoArray.put(0, dataResponse.getString("file_name")); dataSend.put("audios", photoArray); menssage.fileName = photoArray.toString(); } catch (JSONException e) { e.printStackTrace(); } if (SpeakSocket.mSocket != null) if (SpeakSocket.mSocket.connected()) { menssage.status = 1; SpeakSocket.mSocket.emit("message", dataSend); } else { menssage.status = -1; } menssage.fileUploaded = true; menssage.save(); activity.runOnUiThread(new Runnable() { @Override public void run() { progressLayout.setVisibility(View.GONE); System.gc(); } }); } @Override public void onProgress(final long bytesWritten, final long totalSize) { if (bytesWritten != totalSize) { activity.runOnUiThread(new Runnable() { @Override public void run() { double prog = (100 / (double) totalSize) * (double) bytesWritten; progressBar.setProgress((int) Math.round(prog)); progressText.setText((int) Math.round(prog) + "%"); Log.e("PROGRESO", (int) Math.round(prog) + ""); } }); } } @Override public void onFinish() { System.gc(); } }, activity); } catch (FileNotFoundException e) { e.printStackTrace(); } }
From source file:me.ububble.speakall.fragment.ConversationChatFragment.java
private void uploadPhotoToServer(String file, final Message menssage, final JSONObject dataSend, final ProgressBar progressBar, final RelativeLayout progressLayout, final TextView progressText, final ImageView messageContent) { try {//from www . j a v a 2 s. c om RequestParams p = new RequestParams(); final File archivo = new File(file); p.put("image", archivo); activity.runOnUiThread(new Runnable() { @Override public void run() { progressBar.setIndeterminate(false); progressText.setText("0%"); } }); SpeakHttp.post("messages/" + SessionCustom.getUserId(activity) + "/upload/photo", p, new JsonHttpResponseHandler() { @Override public void onSuccess(int statusCode, Header[] headers, final JSONObject response) { super.onSuccess(statusCode, headers, response); try { JSONObject jsonObject = response.getJSONObject("data_response"); JSONArray photoArray = new JSONArray(); photoArray.put(0, jsonObject.getString("file_name")); dataSend.put("photos", photoArray); menssage.fileName = photoArray.toString(); } catch (JSONException e) { e.printStackTrace(); } if (SpeakSocket.mSocket != null) if (SpeakSocket.mSocket.connected()) { menssage.status = 1; SpeakSocket.mSocket.emit("message", dataSend); } else { menssage.status = -1; } menssage.fileUploaded = true; menssage.save(); activity.runOnUiThread(new Runnable() { @Override public void run() { if (menssage.photo != null) { Bitmap bmp = BitmapFactory.decodeByteArray(menssage.photo, 0, menssage.photo.length); messageContent.setImageBitmap(bmp); progressLayout.setVisibility(View.GONE); System.gc(); } } }); } @Override public void onProgress(final long bytesWritten, final long totalSize) { if (bytesWritten != totalSize) { activity.runOnUiThread(new Runnable() { @Override public void run() { double prog = (100 / (double) totalSize) * (double) bytesWritten; progressBar.setProgress((int) Math.round(prog)); progressText.setText((int) Math.round(prog) + "%"); Log.e("PROGRESO", (int) Math.round(prog) + ""); } }); } } @Override public void onFinish() { System.gc(); } }, activity); } catch (FileNotFoundException e) { e.printStackTrace(); } }