List of usage examples for android.os Handler post
public final boolean post(Runnable r)
From source file:org.xbmc.kore.jsonrpc.HostConnection.java
private <T> void handleTcpResponse(ObjectNode jsonResponse) { if (!jsonResponse.has(ApiMethod.ID_NODE)) { // It's a notification, notify observers String notificationName = jsonResponse.get(ApiNotification.METHOD_NODE).asText(); ObjectNode params = (ObjectNode) jsonResponse.get(ApiNotification.PARAMS_NODE); if (notificationName.equals(Player.OnPause.NOTIFICATION_NAME)) { final Player.OnPause apiNotification = new Player.OnPause(params); for (final PlayerNotificationsObserver observer : playerNotificationsObservers.keySet()) { Handler handler = playerNotificationsObservers.get(observer); handler.post(new Runnable() { @Override//from w w w . jav a2 s. co m public void run() { observer.onPause(apiNotification); } }); } } else if (notificationName.equals(Player.OnPlay.NOTIFICATION_NAME)) { final Player.OnPlay apiNotification = new Player.OnPlay(params); for (final PlayerNotificationsObserver observer : playerNotificationsObservers.keySet()) { Handler handler = playerNotificationsObservers.get(observer); handler.post(new Runnable() { @Override public void run() { observer.onPlay(apiNotification); } }); } } else if (notificationName.equals(Player.OnSeek.NOTIFICATION_NAME)) { final Player.OnSeek apiNotification = new Player.OnSeek(params); for (final PlayerNotificationsObserver observer : playerNotificationsObservers.keySet()) { Handler handler = playerNotificationsObservers.get(observer); handler.post(new Runnable() { @Override public void run() { observer.onSeek(apiNotification); } }); } } else if (notificationName.equals(Player.OnSpeedChanged.NOTIFICATION_NAME)) { final Player.OnSpeedChanged apiNotification = new Player.OnSpeedChanged(params); for (final PlayerNotificationsObserver observer : playerNotificationsObservers.keySet()) { Handler handler = playerNotificationsObservers.get(observer); handler.post(new Runnable() { @Override public void run() { observer.onSpeedChanged(apiNotification); } }); } } else if (notificationName.equals(Player.OnStop.NOTIFICATION_NAME)) { final Player.OnStop apiNotification = new Player.OnStop(params); for (final PlayerNotificationsObserver observer : playerNotificationsObservers.keySet()) { Handler handler = playerNotificationsObservers.get(observer); handler.post(new Runnable() { @Override public void run() { observer.onStop(apiNotification); } }); } } else if (notificationName.equals(System.OnQuit.NOTIFICATION_NAME)) { final System.OnQuit apiNotification = new System.OnQuit(params); for (final SystemNotificationsObserver observer : systemNotificationsObservers.keySet()) { Handler handler = systemNotificationsObservers.get(observer); handler.post(new Runnable() { @Override public void run() { observer.onQuit(apiNotification); } }); } } else if (notificationName.equals(System.OnRestart.NOTIFICATION_NAME)) { final System.OnRestart apiNotification = new System.OnRestart(params); for (final SystemNotificationsObserver observer : systemNotificationsObservers.keySet()) { Handler handler = systemNotificationsObservers.get(observer); handler.post(new Runnable() { @Override public void run() { observer.onRestart(apiNotification); } }); } } else if (notificationName.equals(System.OnSleep.NOTIFICATION_NAME)) { final System.OnSleep apiNotification = new System.OnSleep(params); for (final SystemNotificationsObserver observer : systemNotificationsObservers.keySet()) { Handler handler = systemNotificationsObservers.get(observer); handler.post(new Runnable() { @Override public void run() { observer.onSleep(apiNotification); } }); } } else if (notificationName.equals(Input.OnInputRequested.NOTIFICATION_NAME)) { final Input.OnInputRequested apiNotification = new Input.OnInputRequested(params); for (final InputNotificationsObserver observer : inputNotificationsObservers.keySet()) { Handler handler = inputNotificationsObservers.get(observer); handler.post(new Runnable() { @Override public void run() { observer.onInputRequested(apiNotification); } }); } } LogUtils.LOGD(TAG, "Got a notification: " + jsonResponse.get("method").textValue()); } else { String methodId = jsonResponse.get(ApiMethod.ID_NODE).asText(); if (jsonResponse.has(ApiMethod.ERROR_NODE)) { // Error response callErrorCallback(methodId, new ApiException(ApiException.API_ERROR, jsonResponse)); } else { // Sucess response final MethodCallInfo<?> methodCallInfo = clientCallbacks.get(methodId); // LogUtils.LOGD(TAG, "Sending response to method: " + methodCallInfo.method.getMethodName()); if (methodCallInfo != null) { try { @SuppressWarnings("unchecked") final T result = (T) methodCallInfo.method.resultFromJson(jsonResponse); @SuppressWarnings("unchecked") final ApiCallback<T> callback = (ApiCallback<T>) methodCallInfo.callback; if ((methodCallInfo.handler != null) && (callback != null)) { methodCallInfo.handler.post(new Runnable() { @Override public void run() { callback.onSuccess(result); } }); } // We've replied, remove the client from the list synchronized (clientCallbacks) { clientCallbacks.remove(methodId); } } catch (ApiException e) { callErrorCallback(methodId, e); } } } } }
From source file:com.att.ads.sample.SpeechAuth.java
/** * Posts request data, gets bytes of response, and calls client when done. * Performs blocking I/O, so it must be called from its own thread. **///from ww w.j a v a 2s .co m private void performFetch(Handler callingThread) { try { // Post the credentials. connection.setDoOutput(true); OutputStream out = connection.getOutputStream(); out.write(postData); out.close(); // Wait for the response. // Note that getInputStream will throw exception for non-200 status. InputStream response = connection.getInputStream(); byte[] data; try { data = readAllBytes(response); } finally { try { response.close(); } catch (IOException ex) { /* ignore */} } // Extract the token from JSON. String body = new String(data, "UTF8"); JSONObject json = new JSONObject(body); final String token = json.getString("access_token"); // Give it back to the client. callingThread.post(new Runnable() { public void run() { if (client != null) client.handleResponse(token, null); } }); } catch (final Exception ex) { callingThread.post(new Runnable() { public void run() { if (client != null) client.handleResponse(null, ex); } }); } // XXX: Should we close the connection? // finally { connection.close(); } }
From source file:piuk.blockchain.android.ui.NewAccountFragment.java
@Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { final View view = inflater.inflate(R.layout.new_account_dialog, null); final Button createButton = (Button) view.findViewById(R.id.create_button); final TextView password = (TextView) view.findViewById(R.id.password); final TextView password2 = (TextView) view.findViewById(R.id.password2); final TextView captcha = (TextView) view.findViewById(R.id.captcha); refreshCaptcha(view);/* ww w . java2 s . co m*/ createButton.setOnClickListener(new OnClickListener() { public void onClick(View v) { final WalletApplication application = (WalletApplication) getActivity().getApplication(); if (password.getText().length() < 10 || password.getText().length() > 255) { Toast.makeText(application, R.string.new_account_password_length_error, Toast.LENGTH_LONG) .show(); return; } if (!password.getText().toString().equals(password2.getText().toString())) { Toast.makeText(application, R.string.new_account_password_mismatch_error, Toast.LENGTH_LONG) .show(); return; } if (captcha.getText().length() == 0) { Toast.makeText(application, R.string.new_account_no_kaptcha_error, Toast.LENGTH_LONG).show(); return; } final ProgressDialog progressDialog = ProgressDialog.show(getActivity(), "", getString(R.string.creating_account), true); progressDialog.show(); final Handler handler = new Handler(); new Thread() { @Override public void run() { try { if (!application.getRemoteWallet().isNew()) return; application.getRemoteWallet().setTemporyPassword(password.getText().toString()); if (!application.getRemoteWallet().remoteSave(captcha.getText().toString())) { throw new Exception("Unknown Error inserting wallet"); } EventListeners.invokeWalletDidChange(); application.hasDecryptionError = false; handler.post(new Runnable() { public void run() { progressDialog.dismiss(); dismiss(); Toast.makeText(getActivity().getApplication(), R.string.new_account_success, Toast.LENGTH_LONG).show(); Editor edit = PreferenceManager .getDefaultSharedPreferences(application.getApplicationContext()) .edit(); edit.putString("guid", application.getRemoteWallet().getGUID()); edit.putString("sharedKey", application.getRemoteWallet().getSharedKey()); edit.putString("password", password.getText().toString()); if (edit.commit()) { application.checkIfWalletHasUpdatedAndFetchTransactions(); } else { Activity activity = (Activity) getActivity(); final Builder dialog = new AlertDialog.Builder(activity); dialog.setTitle(R.string.error_pairing_wallet); dialog.setMessage("Error saving preferences"); dialog.setNeutralButton(R.string.button_dismiss, null); dialog.show(); } } }); } catch (final Exception e) { e.printStackTrace(); handler.post(new Runnable() { public void run() { progressDialog.dismiss(); refreshCaptcha(view); captcha.setText(null); Toast.makeText(getActivity().getApplication(), e.getLocalizedMessage(), Toast.LENGTH_LONG).show(); } }); } } }.start(); } }); return view; }
From source file:com.jackpan.TaiwanpetadoptionApp.HeadpageActivity.java
protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN, WindowManager.LayoutParams.FLAG_FULLSCREEN);// requestWindowFeature(Window.FEATURE_NO_TITLE);// ?APP setContentView(R.layout.activity_headpage); ConnectivityManager conManager = (ConnectivityManager) getSystemService(CONNECTIVITY_SERVICE); NetworkInfo networInfo = conManager.getActiveNetworkInfo(); if (networInfo == null || !networInfo.isAvailable()) { new AlertDialog.Builder(HeadpageActivity.this).setTitle(getString(R.string.Network_status)) .setMessage(getString(R.string.no_network)).setCancelable(false) .setPositiveButton(getString(R.string.setting), new DialogInterface.OnClickListener() { @Override/* ww w .ja va2 s .c o m*/ public void onClick(DialogInterface dialog, int which) { // TODO Auto-generated method stub Intent settintIntent = new Intent(android.provider.Settings.ACTION_SETTINGS); startActivity(settintIntent); } }).setNegativeButton(getString(R.string.cancel), new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { // TODO Auto-generated method stub HeadpageActivity.this.finish(); } }).show(); } else { final ProgressDialog progressDialog = ProgressDialog.show(HeadpageActivity.this, getString(R.string.Network_in), getString(R.string.waitting)); final Handler handler = new Handler(); final Runnable runnable = new Runnable() { @Override public void run() { // TODO Auto-generated method stub new AlertDialog.Builder(HeadpageActivity.this); progressDialog.dismiss(); } }; Thread thread = new Thread() { @Override public void run() { try { Thread.sleep(1500); } catch (InterruptedException e) { // TODO Auto-generated catch block e.printStackTrace(); } handler.post(runnable); } }; thread.start(); } final TextView test = (TextView) findViewById(R.id.textView1); Timer timer = new Timer(); TimerTask task = new TimerTask() { public void run() { runOnUiThread(new Runnable() { public void run() { if (change) { change = false; test.setTextColor(Color.TRANSPARENT); // ? } else { change = true; test.setTextColor(Color.DKGRAY); } } }); } }; timer.schedule(task, 1, 800); // ?(timer???) mHelper = new IabHelper(this, getString(R.string.my_license_key)); mHelper.startSetup(new IabHelper.OnIabSetupFinishedListener() { public void onIabSetupFinished(IabResult result) { if (!result.isSuccess()) { MySharedPrefernces.saveIsBuyed(HeadpageActivity.this, false); } else { MySharedPrefernces.saveIsBuyed(HeadpageActivity.this, false); mHelper.queryInventoryAsync(mGotInventoryListener); } } }); GetButtonView(); setButtonEvent(); buildGoogleApiClient(); }
From source file:com.door43.translationstudio.ui.dialogs.BackupDialog.java
/** * restore the dialogs that were displayed before rotation *//* ww w .j a v a 2s. c o m*/ private void restoreDialogs() { Handler hand = new Handler(Looper.getMainLooper()); hand.post(new Runnable() { // wait for backup dialog to be drawn before showing popups @Override public void run() { switch (mDialogShown) { case PUSH_REJECTED: showPushRejection(targetTranslation); break; case AUTH_FAILURE: showAuthFailure(); break; case BACKUP_FAILED: showUploadFailedDialog(targetTranslation); break; case NO_INTERNET: showNoInternetDialog(); break; case SHOW_BACKUP_RESULTS: showBackupResults(mDialogMessage); break; case SHOW_PUSH_SUCCESS: showPushSuccess(mDialogMessage); break; case MERGE_CONFLICT: showMergeConflict(targetTranslation); break; case EXPORT_TO_USFM_PROMPT: showExportToUsfmPrompt(); break; case EXPORT_PROJECT_PROMPT: showExportProjectPrompt(); break; case EXPORT_TO_USFM_RESULTS: showUsfmExportResults(mDialogMessage); break; case EXPORT_PROJECT_OVERWRITE: showExportProjectOverwrite(mDialogMessage); break; case EXPORT_USFM_OVERWRITE: showExportUsfmOverwrite(mDialogMessage); break; case NONE: break; default: Logger.e(TAG, "Unsupported restore dialog: " + mDialogShown.toString()); break; } } }); }
From source file:cl.droid.transantiago.activity.TransChooseServiceActivity.java
private Bitmap loadImage(final String URL, final BitmapFactory.Options options) { final Handler handler = new Handler() { // @Override // public void handleMessage(Message msg) { // ads.setImageBitmap(bm); // } };/*from ww w.j a v a 2s .com*/ new Thread(new Runnable() { public void run() { InputStream in = null; try { in = OpenHttpConnection(URL); final Bitmap bitmap = BitmapFactory.decodeStream(in, null, options); in.close(); handler.post(new Runnable() { public void run() { if (ads != null && bitmap != null) { ads.setImageBitmap(bitmap); } } }); } catch (IOException e1) { handler.sendEmptyMessage(0); } catch (Exception e1) { handler.sendEmptyMessage(0); } //return bitmap; } }).start(); return null; }
From source file:net.ben.subsonic.androidapp.util.Util.java
public static void showErrorNotification(final Context context, Handler handler, String title, Exception error) {//from w w w. j a v a2 s . c o m final NotificationManager notificationManager = (NotificationManager) context .getSystemService(Context.NOTIFICATION_SERVICE); StringBuilder text = new StringBuilder(); if (error.getMessage() != null) { text.append(error.getMessage()).append(" ("); } text.append(error.getClass().getSimpleName()); if (error.getMessage() != null) { text.append(")"); } // Set the icon, scrolling text and timestamp final Notification notification = new Notification(android.R.drawable.stat_sys_warning, title, System.currentTimeMillis()); notification.flags |= Notification.FLAG_AUTO_CANCEL; // The PendingIntent to launch our activity if the user selects this notification Intent intent = new Intent(context, ErrorActivity.class); intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK); intent.putExtra(Constants.INTENT_EXTRA_NAME_ERROR, title + ".\n\n" + text); PendingIntent contentIntent = PendingIntent.getActivity(context, 0, intent, PendingIntent.FLAG_UPDATE_CURRENT); notification.setLatestEventInfo(context, title, text, contentIntent); // Send the notification. handler.post(new Runnable() { @Override public void run() { notificationManager.cancel(Constants.NOTIFICATION_ID_ERROR); notificationManager.notify(Constants.NOTIFICATION_ID_ERROR, notification); } }); }
From source file:io.lqd.sdk.Liquid.java
private void notifyListeners(final boolean received) { Handler mainHandler = new Handler(mContext.getMainLooper()); mainHandler.post(new Runnable() { @Override/*from w ww. j a v a 2 s . c om*/ public void run() { if (mListeners.size() == 0) { mNeedCallbackCall = true; return; } else { mNeedCallbackCall = false; } for (LiquidOnEventListener listener : mListeners.values()) { if (received) { listener.onValuesReceived(); } else { listener.onValuesLoaded(); } } } }); }
From source file:ru.orangesoftware.financisto.export.flowzr.FlowzrSyncEngine.java
public static String create(Context p_context, DatabaseAdapter p_dba, DefaultHttpClient p_http) { startTimestamp = System.currentTimeMillis(); if (isRunning == true) { isCanceled = true;/* ww w . ja v a 2 s. co m*/ isRunning = false; } isRunning = true; boolean recordSyncTime = true; dba = p_dba; db = dba.db(); em = dba.em(); http_client = p_http; context = p_context; last_sync_ts = MyPreferences.getFlowzrLastSync(context); FLOWZR_BASE_URL = "https://" + MyPreferences.getSyncApiUrl(context); FLOWZR_API_URL = FLOWZR_BASE_URL + "/financisto3/"; nsString = MyPreferences.getFlowzrAccount(context).replace("@", "_"); //urlsafe Log.i(TAG, "init sync engine, last sync was " + new Date(last_sync_ts).toLocaleString()); //if (true) { if (!checkSubscriptionFromWeb()) { Intent notificationIntent = new Intent(context, FlowzrSyncActivity.class); PendingIntent pendingIntent = PendingIntent.getActivity(context, 0, notificationIntent, 0); NotificationManager notificationManager = (NotificationManager) context .getSystemService(Context.NOTIFICATION_SERVICE); Notification notification = new NotificationCompat.Builder(context).setSmallIcon(R.drawable.icon) .setTicker(context.getString(R.string.flowzr_subscription_required)) .setContentTitle(context.getString(R.string.flowzr_sync_error)) .setContentText(context.getString(R.string.flowzr_subscription_required, MyPreferences.getFlowzrAccount(context))) .setContentIntent(pendingIntent).setAutoCancel(true).build(); notificationManager.notify(0, notification); Log.w("flowzr", "subscription rejected from web"); isCanceled = true; MyPreferences.unsetAutoSync(context); return null; } else { mNotificationManager = (NotificationManager) context.getSystemService(Context.NOTIFICATION_SERVICE); // Sets an ID for the notification, so it can be updated mNotifyBuilder = new NotificationCompat.Builder(context).setAutoCancel(true) .setContentTitle(context.getString(R.string.flowzr_sync)) .setContentText(context.getString(R.string.flowzr_sync_inprogress)) .setSmallIcon(R.drawable.icon); } if (!isCanceled) { notifyUser("fix created entities", 5); fixCreatedEntities(); } /** * pull delete */ if (!isCanceled) { notifyUser(context.getString(R.string.flowzr_sync_receiving) + " ...", 10); try { pullDelete(last_sync_ts); } catch (Exception e) { sendBackTrace(e); recordSyncTime = false; } } /** * push delete */ if (!isCanceled) { notifyUser(context.getString(R.string.flowzr_sync_sending) + " ...", 15); try { pushDelete(); } catch (Exception e) { sendBackTrace(e); recordSyncTime = false; } } /** * pull update */ if (!isCanceled && last_sync_ts == 0) { notifyUser(context.getString(R.string.flowzr_sync_receiving) + " ...", 20); try { pullUpdate(); } catch (IOException e) { sendBackTrace(e); recordSyncTime = false; } catch (JSONException e) { sendBackTrace(e); recordSyncTime = false; } catch (Exception e) { sendBackTrace(e); recordSyncTime = false; } } /** * push update */ if (!isCanceled) { notifyUser(context.getString(R.string.flowzr_sync_sending) + " ...", 35); try { pushUpdate(); } catch (ClientProtocolException e) { e.printStackTrace(); sendBackTrace(e); recordSyncTime = false; } catch (IOException e) { e.printStackTrace(); sendBackTrace(e); recordSyncTime = false; } catch (JSONException e) { e.printStackTrace(); sendBackTrace(e); recordSyncTime = false; } catch (Exception e) { e.printStackTrace(); recordSyncTime = false; } } /** * pull update */ if (!isCanceled && last_sync_ts > 0) { notifyUser(context.getString(R.string.flowzr_sync_receiving) + " ...", 20); try { pullUpdate(); } catch (IOException e) { sendBackTrace(e); recordSyncTime = false; } catch (JSONException e) { sendBackTrace(e); recordSyncTime = false; } catch (Exception e) { sendBackTrace(e); recordSyncTime = false; } } /** * send account balances boundaries */ if (!isCanceled) { //if (true) { //will generate a Cloud Messaging request if prev. aborted notifyUser(context.getString(R.string.flowzr_sync_sending) + "...", 80); //nm.notify(NOTIFICATION_ID, mNotifyBuilder.build()); ArrayList<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(); nameValuePairs.add(new BasicNameValuePair("action", "balancesRecalc")); nameValuePairs.add(new BasicNameValuePair("last_sync_ts", String.valueOf(last_sync_ts))); try { httpPush(nameValuePairs, "balances"); } catch (Exception e) { sendBackTrace(e); } } notifyUser(context.getString(R.string.integrity_fix), 85); new IntegrityFix(dba).fix(); notifyUser("Widgets ...", 90); AccountWidget.updateWidgets(context); Handler refresh = new Handler(Looper.getMainLooper()); refresh.post(new Runnable() { public void run() { if (currentActivity != null) { //currentActivity.refreshCurrentTab(); } } }); if (!isCanceled && MyPreferences.doGoogleDriveUpload(context)) { notifyUser(context.getString(R.string.flowzr_sync_sending) + " Google Drive", 95); pushAllBlobs(); } else { Log.i("flowzr", "picture upload desactivated in prefs"); } notifyUser(context.getString(R.string.flowzr_sync_success), 100); if (isCanceled == false) { if (recordSyncTime == true) { last_sync_ts = System.currentTimeMillis(); SharedPreferences.Editor editor = PreferenceManager.getDefaultSharedPreferences(context).edit(); editor.putLong("PROPERTY_LAST_SYNC_TIMESTAMP", last_sync_ts); editor.commit(); } } // mNotificationManager.cancel(NOTIFICATION_ID); isRunning = false; isCanceled = false; if (context instanceof FlowzrSyncActivity) { ((FlowzrSyncActivity) context).setIsFinished(); } return FLOWZR_BASE_URL; }