List of usage examples for android.app Activity runOnUiThread
public final void runOnUiThread(Runnable action)
From source file:com.vuze.android.remote.AndroidUtils.java
/** * Same as {@link Activity#runOnUiThread(Runnable)}, except ensures * activity still exists while in UI Thread, before executing runnable *//*from www .j a va 2 s. com*/ public static void runOnUIThread(final android.support.v4.app.Fragment fragment, final Runnable runnable) { Activity activity = fragment.getActivity(); if (activity == null) { return; } activity.runOnUiThread(new Runnable() { @Override public void run() { Activity activity = fragment.getActivity(); if (activity == null) { return; } if (runnable instanceof RunnableWithActivity) { ((RunnableWithActivity) runnable).activity = activity; } runnable.run(); } }); }
From source file:com.juick.android.Utils.java
public static RESTResponse getJSON(final Context context, final String url, final Notification progressNotification, final int timeout, final boolean forceAttachCredentials) { final URLAuth authorizer = getAuthorizer(url); final RESTResponse[] ret = new RESTResponse[] { null }; final URLAuth finalAuthorizer = authorizer; final boolean[] cookieCleared = { false }; authorizer.authorize(context, false, forceAttachCredentials, url, new Function<Void, String>() { @Override/*from w w w. jav a 2s . c o m*/ public Void apply(String myCookie) { final boolean noAuthRequested = myCookie != null && myCookie.equals(URLAuth.REFUSED_AUTH); if (noAuthRequested) myCookie = null; final DefaultHttpClient client = getNewHttpClient(); try { final Function<Void, String> thiz = this; final SharedPreferences sp = PreferenceManager.getDefaultSharedPreferences(context); boolean compression = sp.getBoolean("http_compression", false); long l = System.currentTimeMillis(); if (compression) initCompressionSupport(client); HttpGet httpGet = new HttpGet(authorizer.authorizeURL(url, myCookie)); Integer timeoutForConnection = timeout > 0 ? timeout : (sp.getBoolean("use_timeouts_json", false) ? 10000 : 2222000); client.getParams().setParameter("http.connection.timeout", timeoutForConnection); httpGet.getParams().setParameter("http.socket.timeout", timeoutForConnection); httpGet.getParams().setParameter("http.protocol.head-body-timeout", timeoutForConnection); finalAuthorizer.authorizeRequest(httpGet, myCookie); client.execute(httpGet, new ResponseHandler<Object>() { @Override public Object handleResponse(HttpResponse o) throws ClientProtocolException, IOException { URLAuth.ReplyCode authReplyCode = o.getStatusLine().getStatusCode() == 200 ? URLAuth.ReplyCode.NORMAL : authorizer.validateNon200Reply(o, url, forceAttachCredentials); boolean simulateError = false; if (o.getStatusLine().getStatusCode() == 200 && !simulateError) { reloginTried = 0; HttpEntity e = o.getEntity(); if (progressNotification instanceof DownloadProgressNotification) { ((DownloadProgressNotification) progressNotification).notifyDownloadProgress(0); } InputStream content = e.getContent(); RESTResponse retval = streamToString(content, progressNotification); content.close(); if (authorizer.isNoAuthInResponse(retval) && !cookieCleared[0]) { cookieCleared[0] = true; // don't enter loop authorizer.clearCookie(context, new Runnable() { @Override public void run() { authorizer.authorize(context, true, false, url, thiz); } }); return null; } ret[0] = retval; } else { if (authReplyCode == URLAuth.ReplyCode.FORBIDDEN && noAuthRequested) { ret[0] = new RESTResponse(NO_AUTH, false, null); return o; } if (authReplyCode == URLAuth.ReplyCode.FORBIDDEN && !forceAttachCredentials) { ret[0] = getJSON(context, url, progressNotification, timeout, true); return o; } else if (authReplyCode == URLAuth.ReplyCode.FORBIDDEN && !cookieCleared[0]) { cookieCleared[0] = true; // don't enter loop authorizer.clearCookie(context, new Runnable() { @Override public void run() { authorizer.authorize(context, true, false, url, thiz); } }); return null; } else if (o.getStatusLine().getStatusCode() / 100 == 4) { if (context instanceof Activity) { final Activity activity = (Activity) context; reloginTried++; if (reloginTried == 3) { activity.runOnUiThread(new Runnable() { @Override public void run() { sp.edit().remove("web_cookie").commit(); reloginTried = 0; } }); } } // fall through } if (progressNotification instanceof DownloadErrorNotification) { ((DownloadErrorNotification) progressNotification).notifyDownloadError( "HTTP response code: " + o.getStatusLine().getStatusCode()); } ret[0] = new RESTResponse("HTTP: " + o.getStatusLine().getStatusCode() + " " + o.getStatusLine().getReasonPhrase(), false, null); } return o; } }); l = System.currentTimeMillis() - l; if (reportTimes) { Toast.makeText(context, "Load time=" + l + " msec", Toast.LENGTH_LONG).show(); } } catch (Exception e) { if (progressNotification instanceof DownloadErrorNotification) { ((DownloadErrorNotification) progressNotification) .notifyDownloadError("HTTP connect: " + e.toString()); } Log.e("getJSON", e.toString()); ret[0] = new RESTResponse(e.toString(), true, null); } finally { client.getConnectionManager().shutdown(); } return null; //To change body of implemented methods use File | Settings | File Templates. } }); while (ret[0] == null) { // bad, but true try { Thread.sleep(100); } catch (InterruptedException e) { e.printStackTrace(); //To change body of catch statement use File | Settings | File Templates. } } return ret[0]; }
From source file:Main.java
/** * @see "http://blog.peterkuterna.net/2011/09/simple-crossfade-on-imageview.html" * with modifications by Thomas Suarez./*from w w w .ja v a2s . c om*/ */ public static void setImageDrawableWithFade(final Activity context, final ImageView imageView, final String drawableName, final int durationMillis) { int resId = getDrawableId(context, drawableName); // get new drawable resource Drawable drawable; if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.LOLLIPOP) { drawable = context.getResources().getDrawable(resId, context.getTheme()); } else { drawable = context.getResources().getDrawable(resId); // this is deprecated starting in Android 5.0 Lollipop } final Drawable currentDrawable = imageView.getDrawable(); final Drawable newDrawable = drawable; Runnable r = new Runnable() { @Override public void run() { if (currentDrawable != null) { Drawable[] arrayDrawable = new Drawable[2]; arrayDrawable[0] = currentDrawable; arrayDrawable[1] = newDrawable; TransitionDrawable transitionDrawable = new TransitionDrawable(arrayDrawable); transitionDrawable.setCrossFadeEnabled(true); imageView.setImageDrawable(transitionDrawable); transitionDrawable.startTransition(durationMillis); } else { imageView.setImageDrawable(newDrawable); } } }; context.runOnUiThread(r); }
From source file:nya.miku.wishmaster.http.cloudflare.CloudflareUIHandler.java
/** * ?-? Cloudflare.//w w w . j ava2 s .c om * * @param e ? {@link CloudflareException} * @param chan * @param activity ?, ? ( ? ? ), * ? ? WebView ? Anti DDOS ? javascript. * ??? ? UI ({@link Activity#runOnUiThread(Runnable)}) * @param cfTask ?? * @param callback ? {@link Callback} */ static void handleCloudflare(final CloudflareException e, final HttpChanModule chan, final Activity activity, final CancellableTask cfTask, final InteractiveException.Callback callback) { if (cfTask.isCancelled()) return; if (!e.isRecaptcha()) { // ? anti DDOS if (!CloudflareChecker.getInstance().isAvaibleAntiDDOS()) { //? ? ?? , ? ? ? // ?, ? ChanModule, // ? ? () cloudflare ? ? // ? ? ? ? ? CloudflareChecker while (!CloudflareChecker.getInstance().isAvaibleAntiDDOS()) Thread.yield(); if (!cfTask.isCancelled()) activity.runOnUiThread(new Runnable() { @Override public void run() { callback.onSuccess(); } }); return; } Cookie cfCookie = CloudflareChecker.getInstance().checkAntiDDOS(e, chan.getHttpClient(), cfTask, activity); if (cfCookie != null) { chan.saveCookie(cfCookie); if (!cfTask.isCancelled()) { activity.runOnUiThread(new Runnable() { @Override public void run() { callback.onSuccess(); } }); } } else if (!cfTask.isCancelled()) { activity.runOnUiThread(new Runnable() { @Override public void run() { callback.onError(activity.getString(R.string.error_cloudflare_antiddos)); } }); } } else { // ? final Recaptcha recaptcha; try { recaptcha = CloudflareChecker.getInstance().getRecaptcha(e, chan.getHttpClient(), cfTask); } catch (RecaptchaException recaptchaException) { if (!cfTask.isCancelled()) activity.runOnUiThread(new Runnable() { @Override public void run() { callback.onError(activity.getString(R.string.error_cloudflare_get_captcha)); } }); return; } if (!cfTask.isCancelled()) activity.runOnUiThread(new Runnable() { @SuppressLint("InflateParams") @Override public void run() { Context dialogContext = Build.VERSION.SDK_INT < Build.VERSION_CODES.HONEYCOMB ? new ContextThemeWrapper(activity, R.style.Neutron_Medium) : activity; View view = LayoutInflater.from(dialogContext).inflate(R.layout.dialog_cloudflare_captcha, null); ImageView captchaView = (ImageView) view.findViewById(R.id.dialog_captcha_view); final EditText captchaField = (EditText) view.findViewById(R.id.dialog_captcha_field); captchaView.setImageBitmap(recaptcha.bitmap); DialogInterface.OnClickListener process = new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { if (cfTask.isCancelled()) return; PriorityThreadFactory.LOW_PRIORITY_FACTORY.newThread(new Runnable() { @Override public void run() { String answer = captchaField.getText().toString(); Cookie cfCookie = CloudflareChecker.getInstance().checkRecaptcha(e, (ExtendedHttpClient) chan.getHttpClient(), cfTask, recaptcha.challenge, answer); if (cfCookie != null) { chan.saveCookie(cfCookie); if (!cfTask.isCancelled()) { activity.runOnUiThread(new Runnable() { @Override public void run() { callback.onSuccess(); } }); } } else { // (?, , ) handleCloudflare(e, chan, activity, cfTask, callback); } } }).start(); } }; DialogInterface.OnCancelListener onCancel = new DialogInterface.OnCancelListener() { @Override public void onCancel(DialogInterface dialog) { callback.onError(activity.getString(R.string.error_cloudflare_cancelled)); } }; if (cfTask.isCancelled()) return; final AlertDialog recaptchaDialog = new AlertDialog.Builder(dialogContext).setView(view) .setPositiveButton(R.string.dialog_cloudflare_captcha_check, process) .setOnCancelListener(onCancel).create(); recaptchaDialog.getWindow() .setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_ALWAYS_VISIBLE); recaptchaDialog.setCanceledOnTouchOutside(false); recaptchaDialog.show(); captchaView.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { recaptchaDialog.dismiss(); if (cfTask.isCancelled()) return; PriorityThreadFactory.LOW_PRIORITY_FACTORY.newThread(new Runnable() { @Override public void run() { handleCloudflare(e, chan, activity, cfTask, callback); } }).start(); } }); } }); } }
From source file:com.vuze.android.remote.AndroidUtils.java
public static void invalidateOptionsMenuHC(final Activity activity, final ActionMode mActionMode) { if (activity == null) { return;//from w w w.j a v a 2 s . co m } activity.runOnUiThread(new Runnable() { @Override public void run() { if (activity instanceof FragmentActivity) { FragmentActivity aba = (FragmentActivity) activity; aba.supportInvalidateOptionsMenu(); } else { ActivityCompat.invalidateOptionsMenu(activity); } invalidateActionMode(); } @TargetApi(Build.VERSION_CODES.HONEYCOMB) private void invalidateActionMode() { if (mActionMode != null) { mActionMode.invalidate(); } } }); }
From source file:com.microsoft.band.sdksample.SensorsFragment.java
private synchronized void scheduleSensorHandler() { if (mIsHandlerScheduled) { return;/*from w ww .j a v a2 s .c o m*/ } Activity activity = getActivity(); if (activity != null) { mIsHandlerScheduled = true; activity.runOnUiThread(new Runnable() { @Override public void run() { handlePendingSensorReports(); } }); } }
From source file:at.flack.FacebookMainActivity.java
public void showErrorMessage(Activity ac, final boolean b) { if (cantloadContacts != null) ac.runOnUiThread(new Runnable() { @Override//from ww w . j av a 2 s . com public void run() { try { cantloadContacts.setVisibility(b ? View.VISIBLE : View.INVISIBLE); } catch (Exception e) { } } }); }
From source file:com.fatelon.partyphotobooth.setup.fragments.EventInfoSetupFragment.java
/** * Posts a toast to indicate that the selected logo failed to load. *///from w w w .java2 s. c o m private void postLogoError() { if (isActivityAlive()) { final Activity activity = getActivity(); activity.runOnUiThread(new Runnable() { @Override public void run() { if (isActivityAlive()) { Toast.makeText(getActivity(), getString(R.string.event_info_setup__error_logo), Toast.LENGTH_SHORT).show(); } } }); } }
From source file:com.vuze.android.remote.AndroidUtils.java
public static void invalidateOptionsMenuHC(final Activity activity, final android.support.v7.view.ActionMode mActionMode) { if (activity == null) { return;//w w w .j av a2s .co m } activity.runOnUiThread(new Runnable() { @Override public void run() { if (activity.isFinishing()) { return; } if (mActionMode != null) { mActionMode.invalidate(); return; } if (activity instanceof FragmentActivity) { FragmentActivity aba = (FragmentActivity) activity; aba.supportInvalidateOptionsMenu(); } else { ActivityCompat.invalidateOptionsMenu(activity); } } }); }
From source file:ru.valle.btc.MainActivityTest.java
private void performGenerationTest(SharedPreferences preferences, String privateKeyType) { preferences.edit().putString(PreferencesActivity.PREF_PRIVATE_KEY, privateKeyType).commit(); getActivity().finish();// w ww. j a va 2s . c om setActivity(null); assertFalse(getActivity().isFinishing()); preferences = PreferenceManager.getDefaultSharedPreferences(getActivity()); assertEquals(privateKeyType, preferences.getString(PreferencesActivity.PREF_PRIVATE_KEY, PreferencesActivity.PREF_PRIVATE_KEY_WIF_COMPRESSED)); checkIfGeneratedKeyIsValid(privateKeyType); final Activity activity = getActivity(); activity.runOnUiThread(new Runnable() { public void run() { assertTrue(activity.findViewById(R.id.spend_tx_description).getVisibility() == View.GONE); assertTrue(activity.findViewById(R.id.spend_tx).getVisibility() == View.GONE); } }); }