@Override protected String doInBackground(String... params) { if (filtrarDatos()) { ctx.runOnUiThread( new Runnable() { @Override public void run() { try { new Iniciar(PrincipalActivity.this).execute(); } catch (Exception e) { e.printStackTrace(); } } }); } else { ctx.runOnUiThread( new Runnable() { @Override public void run() { Toast.makeText(ctx, "No tienes oro suficiente", Toast.LENGTH_SHORT).show(); } }); } return null; }
@Override public boolean onConfirmSchedule( final List<Entry<Date, Double>> steps, final double totalAmount) { mStepsConfirmed = null; final Object lock = new Object(); mActivity.runOnUiThread( new Runnable() { @Override public void run() { dlgSteps = new RegularStepsDialog(mActivity, steps, totalAmount); dlgSteps.setConfirmListener( new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface paramDialogInterface, int paramInt) { mStepsConfirmed = true; } }); dlgSteps.setOnCancelListener( new DialogInterface.OnCancelListener() { @Override public void onCancel(DialogInterface paramDialogInterface) { mStepsConfirmed = false; } }); dlgSteps.setOnDismissListener( new OnDismissListener() { @Override public void onDismiss(DialogInterface dialogInterface) { synchronized (lock) { lock.notifyAll(); } } }); dlgSteps.show(); } }); synchronized (lock) { try { lock.wait(30000); } catch (InterruptedException e) { e.printStackTrace(); } } if (mStepsConfirmed == null || mStepsConfirmed == false) { mActivity.runOnUiThread( new Runnable() { @Override public void run() { dlgSteps.dismiss(); PaymentDialog.this.dismiss(); } }); return false; } return mStepsConfirmed.booleanValue(); }
public void run() { HttpClient httpclient = new DefaultHttpClient(); HttpPost httppost = new HttpPost("http://www.sigfood.de/"); try { List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(4); nameValuePairs.add(new BasicNameValuePair("do", "1")); nameValuePairs.add(new BasicNameValuePair("datum", String.format("%tY-%tm-%td", t, t, t))); nameValuePairs.add(new BasicNameValuePair("gerid", Integer.toString(e.id))); nameValuePairs.add(new BasicNameValuePair("wertung", Integer.toString(s))); httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs)); HttpResponse response = httpclient.execute(httppost); if (response.getStatusLine() == null) { act.runOnUiThread( new Runnable() { public void run() { b.setText("Bewertung fehlgeschlagen"); } }); } else { if (response.getStatusLine().getStatusCode() != 200) { act.runOnUiThread( new Runnable() { public void run() { b.setText("Bewertung fehlgeschlagen"); } }); } } } catch (ClientProtocolException e1) { act.runOnUiThread( new Runnable() { public void run() { b.setText("Bewertung fehlgeschlagen"); } }); } catch (IOException e1) { act.runOnUiThread( new Runnable() { public void run() { b.setText("Bewertung fehlgeschlagen"); } }); } act.runOnUiThread( new Runnable() { public void run() { b.setText("Bewertet mit " + s + " Stern" + ((s == 1) ? "" : "en")); } }); }
/** * Selects a route by its id * * @param routeId * @param callbackContext * @return */ public boolean selectRoute(final String routeId, final CallbackContext callbackContext) { if (this.currentSession != null) { callbackContext.success(this.currentSession.createSessionObject()); return true; } this.setLastSessionId(""); final Activity activity = cordova.getActivity(); activity.runOnUiThread( new Runnable() { public void run() { mMediaRouter = MediaRouter.getInstance(activity.getApplicationContext()); final List<RouteInfo> routeList = mMediaRouter.getRoutes(); for (RouteInfo route : routeList) { if (route.getId().equals(routeId)) { Chromecast.this.createSession(route, callbackContext); return; } } callbackContext.error("No route found"); } }); return true; }
private boolean invokeBlinkup( final Activity activity, final BlinkupController controller, JSONArray data) { int timeoutMs; try { mApiKey = data.getString(BLINKUP_ARG_API_KEY); mDeveloperPlanId = data.getString(BLINKUP_ARG_DEVELOPER_PLAN_ID); timeoutMs = data.getInt(BLINKUP_ARG_TIMEOUT_MS); mGeneratePlanId = data.getBoolean(BLINKUP_ARG_GENERATE_PLAN_ID); } catch (JSONException exc) { BlinkUpPluginResult.sendPluginErrorToCallback(ERROR_INVALID_ARGUMENTS); return false; } // if api key not valid, send error message and quit if (!apiKeyFormatValid()) { BlinkUpPluginResult.sendPluginErrorToCallback(ERROR_INVALID_API_KEY); return false; } Intent blinkupCompleteIntent = new Intent(activity, BlinkUpCompleteActivity.class); blinkupCompleteIntent.putExtra(Extras.EXTRA_DEVELOPER_PLAN_ID, mDeveloperPlanId); blinkupCompleteIntent.putExtra(Extras.EXTRA_TIMEOUT_MS, timeoutMs); controller.intentBlinkupComplete = blinkupCompleteIntent; // default is to run on WebCore thread, we have UI so need UI thread activity.runOnUiThread( new Runnable() { @Override public void run() { presentBlinkUp(activity, controller); } }); return true; }
/** * Runs runnable on ui and waits for it to finish. If the current thread is the ui thread, just * runs it */ public static void runOnUiThreadSynchronously(Activity a, final Runnable runnable) { final boolean done[] = new boolean[1]; a.runOnUiThread( new Runnable() { @Override public void run() { runnable.run(); synchronized (done) { done[0] = true; done.notify(); } } }); synchronized (done) { while (!done[0]) { try { done.wait(); } catch (InterruptedException e) { throw new IllegalStateException(e); } } } }
private void runOnUiThread(final Runnable r) { if (parentActivity != null) { parentActivity.runOnUiThread(r); } else { getUiHandler().post(r); } }
private void sendAlertFailure(final String msg) { final Context context = this.getActivity(); ((Activity) context) .runOnUiThread( new Runnable() { @Override public void run() { AlertDialog.Builder alertDialogBuilder = new AlertDialog.Builder(context); // set title alertDialogBuilder.setTitle("Something went wrong"); // set dialog message alertDialogBuilder .setMessage(msg) .setCancelable(false) .setPositiveButton( "Okay", new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int id) {} }); // create alert dialog AlertDialog alertDialog = alertDialogBuilder.create(); // show it alertDialog.show(); } }); }
@Override public void showAds(Hashtable<String, String> adsInfo, int pos) { final String location = adsInfo.get("location"); final int type = Integer.parseInt(adsInfo.get("type")); Activity activity = (Activity) mContext; activity.runOnUiThread( new Runnable() { @Override public void run() { switch (type) { case CB_TYPE_INTERSTITIAL: Chartboost.showInterstitial(location); break; case CB_TYPE_REWARDED_VIDEO: Chartboost.showRewardedVideo(location); break; case CB_TYPE_MORE_APPS: Chartboost.showMoreApps(location); break; default: break; } } }); }
public void deactivate() { if (isRunning) { try { this.stop(); this.reset(); this.release(); this.isRunning = false; } catch (final Exception e) { Runnable runnable = new Runnable() { @Override public void run() { Toast toast1 = (Toast.makeText( callingActivity, "Problem with Recorder2" + e.getMessage(), Toast.LENGTH_LONG)); toast1.show(); e.printStackTrace(); } }; callingActivity.runOnUiThread(runnable); } } }
public void activate() { if (camera.open()) { camera.startPreview(); if (camera.unlock()) { try { this.setCamera(camera.getCamera()); this.setAudioSource(MediaRecorder.AudioSource.MIC); this.setVideoSource(MediaRecorder.VideoSource.CAMERA); this.setProfile(CamcorderProfile.get(CamcorderProfile.QUALITY_HIGH)); this.setOutputFile(FileManager.getOutputMediaFile(MEDIA_TYPE_VIEDO).getAbsolutePath()); this.prepare(); this.start(); isRunning = true; } catch (final Exception e) { Runnable runnable = new Runnable() { @Override public void run() { Toast toast1 = (Toast.makeText( callingActivity, "Problem with Recorder!" + e.getMessage(), Toast.LENGTH_LONG)); toast1.show(); e.printStackTrace(); deactivate(); } }; callingActivity.runOnUiThread(runnable); isRunning = false; } } } }
@Override public void receiveMuseConnectionPacket(MuseConnectionPacket p) { final ConnectionState current = p.getCurrentConnectionState(); final String status = p.getPreviousConnectionState().toString() + " -> " + current; final String full = "Muse " + p.getSource().getMacAddress() + " " + status; Log.i("Muse Headband kt", full); Activity activity = activityRef.get(); // UI thread is used here only because we need to update // TextView values. You don't have to use another thread, unless // you want to run disconnect() or connect() from connection packet // handler. In this case creating another thread is required. if (activity != null) { activity.runOnUiThread( new Runnable() { @Override public void run() { TextView statusText = (TextView) findViewById(R.id.con_status); statusText.setText(status); TextView museVersionText = (TextView) findViewById(R.id.version); if (current == ConnectionState.CONNECTED) { MuseVersion museVersion = muse.getMuseVersion(); String version = museVersion.getFirmwareType() + " - " + museVersion.getFirmwareVersion() + " - " + Integer.toString(museVersion.getProtocolVersion()); museVersionText.setText(version); } else { museVersionText.setText(R.string.undefined); } } }); } }
private void getProfileInformation() { try { if (Plus.PeopleApi.getCurrentPerson(mGoogleApiClient) != null) { Person currentPerson = Plus.PeopleApi.getCurrentPerson(mGoogleApiClient); Log.e("GetInfo", currentPerson.toString()); Gplus_name = currentPerson.getDisplayName(); Gplus_image = currentPerson.getImage().getUrl(); Gplus_email = Plus.AccountApi.getAccountName(mGoogleApiClient); Gplus_id = currentPerson.getId(); Log.e("GetInfoID", Gplus_id); if (Gplus_id != null) { context.runOnUiThread( new Runnable() { @Override public void run() { login_type = "gplus"; GlobalClaass.savePrefrencesfor(context, PreferenceConnector.Gplus_ID, Gplus_id); CallFacebookLogin(login_type, Gplus_id, Gplus_email); } }); } } } catch (Exception e) { e.printStackTrace(); } }
@Override public void run() { // TODO Auto-generated method stub if (imageViwReused(imageview, blur_radius)) { removeTask(this); return; } if (blur_radius < 0) { return; } if (srcBit != null) { float scaleFactor = AsyncImageLoader.BLUR_TAG_SCALEFACTOR; Bitmap overlay = Bitmap.createBitmap( (int) (srcBit.getWidth() / scaleFactor), (int) (srcBit.getHeight() / scaleFactor), Bitmap.Config.ARGB_8888); Canvas canvas = new Canvas(overlay); canvas.scale(1 / scaleFactor, 1 / scaleFactor); Paint paint = new Paint(); paint.setFlags(Paint.FILTER_BITMAP_FLAG); canvas.drawBitmap(srcBit, 0, 0, paint); overlay = FastBlur.doBlur(overlay, (int) blur_radius, true); // Bitmap mDrawable = BlurFilter.blurFilter(srcBit, blur_radius, // blur_radius); if (!imageViwReused(imageview, blur_radius)) { BimapBlurDisplayer bd = new BimapBlurDisplayer(overlay, imageview, blur_radius); Activity a = (Activity) imageview.getContext(); a.runOnUiThread(bd); } removeTask(this); } }
/** * Checks to see how many receivers are available - emits the receiver status down to Javascript */ private void checkReceiverAvailable() { final Activity activity = cordova.getActivity(); activity.runOnUiThread( new Runnable() { public void run() { mMediaRouter = MediaRouter.getInstance(activity.getApplicationContext()); List<RouteInfo> routeList = mMediaRouter.getRoutes(); boolean available = false; for (RouteInfo route : routeList) { if (!route.getName().equals("Phone") && route.getId().indexOf("Cast") > -1) { available = true; break; } } if (available || (Chromecast.this.currentSession != null && Chromecast.this.currentSession.isConnected())) { sendJavascript("chrome.cast._.receiverAvailable()"); } else { sendJavascript("chrome.cast._.receiverUnavailable()"); } } }); }
public void insertItemAt(final String[] params) { if (params != null && params.length == 1) { ((Activity) mContext) .runOnUiThread( new Runnable() { @Override public void run() { try { JSONObject json = new JSONObject(params[0]); int index = Integer.parseInt( json.getString(EUExListViewUtils.LISTVIEW_PARAMS_JSON_KEY_ITEMINDEX)); DateItem item = EUExListViewUtils.parseDataItem( json.getJSONObject( EUExListViewUtils.LISTVIEW_PARAMS_JSON_KEY_LISTITEM)); if (datas == null || index > (datas.getDates().size() - 1)) { return; } datas.getDates().add(index, item); adapter.notifyDataSetChanged(); lv.setSelection(index); } catch (Exception e) { e.printStackTrace(); } } }); } }
/** * Shows a dialog with the given message. Does it on the UI thread. * * @param success if true, displays an info icon/title, otherwise an error icon/title * @param message resource string id */ public void showCloseApp(final String message, final String title, final String button) { myCurrentActivity.runOnUiThread( new Runnable() { public void run() { if (progressCurrentState != null) progressCurrentState.cancel(); AlertDialog dialog = null; AlertDialog.Builder builder = new AlertDialog.Builder(myCurrentActivity); builder.setMessage(message); builder.setTitle(title); builder.setNeutralButton( button, new OnClickListener() { // @Override public void onClick(DialogInterface arg0, int arg1) { // TODO Auto-generated method stub myCurrentActivity.finish(); } }); dialog = builder.create(); dialog.show(); } }); }
/** Hide system UI until user interacts */ protected boolean leanMode() { if (!isSupported()) { context.error("Not supported"); return false; } activity.runOnUiThread( new Runnable() { @Override public void run() { try { resetWindow(); int uiOptions = View.SYSTEM_UI_FLAG_HIDE_NAVIGATION | View.SYSTEM_UI_FLAG_FULLSCREEN; decorView.setOnSystemUiVisibilityChangeListener(null); decorView.setSystemUiVisibility(uiOptions); context.success(); } catch (Exception e) { context.error(e.getMessage()); } } }); return true; }
@Override public void onSyncDone(final MediaSet mediaSet, final int resultCode) { if (resultCode == MediaSet.SYNC_RESULT_ERROR) { Log.d( TAG, "onSyncDone: " + Utils.maskDebugInfo(mediaSet.getName()) + " result=" + resultCode); } ((Activity) mActivity) .runOnUiThread( new Runnable() { @Override public void run() { GLRoot root = mActivity.getGLRoot(); root.lockRenderThread(); try { if (resultCode == MediaSet.SYNC_RESULT_SUCCESS) { mInitialSynced = true; } clearLoadingBit(BIT_LOADING_SYNC); if (resultCode == MediaSet.SYNC_RESULT_ERROR && mIsActive) { Log.w(TAG, "failed to load album set"); } } finally { root.unlockRenderThread(); } } }); }
private void doUpload() { statusMessage = activity.getString(R.string.error_sending_to_docs); success = false; try { // Transmit info via GData feed: // ------------------------------- Log.d(LOG_TAG, "Uploading to spreadsheet"); success = uploadToDocs(); if (success) { statusMessage = activity.getString(R.string.status_have_been_uploaded_to_docs); } else { statusMessage = activity.getString(R.string.error_sending_to_docs); } SettingsActivity.getInstance() .getAndSetProgressValue(100 - SettingsActivity.getInstance().getProgressValue()); Log.d(LOG_TAG, "Done."); } finally { if (onCompletion != null) { activity.runOnUiThread(onCompletion); } } }
@Override protected void setUp() throws Exception { super.setUp(); mActivity = getActivity(); mInstrumentation = getInstrumentation(); mButton = new Button(mActivity); mActivity.runOnUiThread( new Runnable() { public void run() { try { mActivity.addContentView( mButton, new LinearLayout.LayoutParams(WRAP_CONTENT, WRAP_CONTENT)); } catch (Exception e) { mException = e; } } }); mInstrumentation.waitForIdleSync(); if (mException != null) { throw mException; } int right = mButton.getRight(); int bottom = mButton.getBottom(); mXInside = (mButton.getLeft() + right) / 3; mYInside = (mButton.getTop() + bottom) / 3; mRect = new Rect(); mButton.getHitRect(mRect); }
private void setBitmap(final ImageView view, final Bitmap bitmap) { ((Activity) context) .runOnUiThread( new Runnable() { @Override public void run() { view.setImageBitmap(bitmap); AlphaAnimation animation = new AlphaAnimation(0, 1); animation.setDuration(250); animation.setAnimationListener( new Animation.AnimationListener() { @Override public void onAnimationStart(Animation animation) {} @Override public void onAnimationEnd(Animation animation) { view.setVisibility(View.VISIBLE); } @Override public void onAnimationRepeat(Animation animation) {} }); view.startAnimation(animation); } }); }
protected String doInBackground(String... argss) { List<NameValuePair> params = new ArrayList<NameValuePair>(); params.add(new BasicNameValuePair("registration_id", registrationId)); params.add(new BasicNameValuePair("auth_username", u.getUsername())); params.add(new BasicNameValuePair("auth_type", u.getType())); params.add(new BasicNameValuePair("auth_phone", u.getPhone())); JSONObject json = jParser.makeHttpRequest(url_add_gcm_user, "GET", params); try { success = json.getInt(Tags.TAG_SUCCESS); msgAdd = json.getString(Tags.TAG_MESSAGE); // had to pass activity to constructor in order to show toast inside async task parent.runOnUiThread( new Runnable() { public void run() { Toast.makeText(parent.getBaseContext(), msgAdd, Toast.LENGTH_SHORT).show(); } }); } catch (JSONException e) { e.printStackTrace(); } return null; }
/** * run on ui thread * * @param context * @param runnable */ public static void runOnUiThread(final Context context, final Runnable runnable) { if (context instanceof Activity) { ((Activity) context).runOnUiThread(runnable); } else { new Handler(Looper.getMainLooper()).post(runnable); } }
@Test public void shouldRunUiTasksImmediatelyByDefault() throws Exception { TestRunnable runnable = new TestRunnable(); activity = create(DialogLifeCycleActivity.class); activity.runOnUiThread(runnable); assertTrue(runnable.wasRun); }
public void close(String[] params) { ((Activity) mContext) .runOnUiThread( new Runnable() { @Override public void run() { try { if (lv != null) { lv.removeAllViewsInLayout(); adapter = null; lv = null; removeViewFromCurrentWindow(view); } if (datas != null) { if (datas.getDates() != null) { datas.getDates().clear(); } if (datas.getSopLeft() != null && datas.getSopLeft().getBts() != null) { datas.getSopLeft().getBts().clear(); } if (datas.getSopRight() != null && datas.getSopRight().getBts() != null) { datas.getSopRight().getBts().clear(); } } } catch (Exception e) { e.printStackTrace(); } finally { datas = null; isOpen = false; } } }); }
@SuppressWarnings("nls") private void upgrade3To3_3(final Context context) { // if RTM, store RTM to secondary preferences if (Preferences.getStringValue("rmilk_token") != null) { SharedPreferences settings = context.getSharedPreferences("rtm", Context.MODE_WORLD_READABLE); Editor editor = settings.edit(); editor.putString("rmilk_token", Preferences.getStringValue("rmilk_token")); editor.putLong("rmilk_last_sync", Preferences.getLong("rmilk_last_sync", 0)); editor.commit(); final String message = "Hi, it looks like you are a Remember the Milk user! " + "In this version of Astrid, RTM is now a community-supported " + "add-on. Please go to the Android market to install it!"; if (context instanceof Activity) { ((Activity) context) .runOnUiThread( new Runnable() { @Override public void run() { new AlertDialog.Builder(context) .setTitle(com.todoroo.astrid.api.R.string.DLG_information_title) .setMessage(message) .setPositiveButton( "Go To Market", new AddOnService.MarketClickListener(context, "org.weloveastrid.rmilk")) .setNegativeButton("Later", null) .show(); } }); } } }
public void setEditingEnabled(final String[] params) { if (params != null && params.length == 1) { ((Activity) mContext) .runOnUiThread( new Runnable() { @Override public void run() { try { if (lv != null && adapter != null) { boolean isEditable = Boolean.parseBoolean(params[0]); if (isEditable) { lv.closeOpenedItems(); lv.setSwipeMode(BaseListView.SWIPE_MODE_NONE); lv.setMode(Mode.DISABLE); } else { lv.setSwipeMode(swipeMode); lv.setMode(refreshMode); } adapter.setEditable(isEditable); adapter.notifyDataSetInvalidated(); } } catch (Exception e) { e.printStackTrace(); } } }); } }
@Override public void onLeScan( final BluetoothDevice device, final int rssi, final byte[] scanRecord) { // if (true) { if (device.getName().contains("SensorTag") || device.getAddress().contains("D0")) { if (onScanListener != null) { onScanListener.onScan(device, rssi, scanRecord); } System.out.println("scan info:"); System.out.println("rssi=" + rssi); System.out.println("ScanRecord:"); for (byte b : scanRecord) System.out.printf("%02X ", b); System.out.println(""); ((Activity) context) .runOnUiThread( new Runnable() { @Override public void run() { Message msg = new Message(); BluetoothScanInfo info = new BluetoothScanInfo(); info.device = device; info.rssi = rssi; info.scanRecord = scanRecord; msg.obj = info; mHandler.sendMessage(msg); } }); } }
public void reloadItems(String[] params) { if (params != null && params.length == 1) { try { JSONObject json = new JSONObject(params[0]); JSONArray array = json.getJSONArray(EUExListViewUtils.LISTVIEW_PARAMS_JSON_KEY_LISTITEMS); refreshDatas = EUExListViewUtils.parseDataItems(array); ((Activity) mContext) .runOnUiThread( new Runnable() { @Override public void run() { if (refreshDatas != null) { datas.getDates().clear(); adapter.notifyDataSetChanged(); datas.getDates().addAll(refreshDatas); refreshDatas.clear(); } } }); } catch (Exception e) { e.printStackTrace(); } } }