Example usage for android.os Handler post

List of usage examples for android.os Handler post

Introduction

In this page you can find the example usage for android.os Handler post.

Prototype

public final boolean post(Runnable r) 

Source Link

Document

Causes the Runnable r to be added to the message queue.

Usage

From source file:com.syncedsynapse.kore2.jsonrpc.HostConnection.java

/**
 * Sends the JSON RPC request through HTTP
 *///from   w w w .ja  v  a2 s. c  o  m
private <T> void executeThroughHTTP(final ApiMethod<T> method, final ApiCallback<T> callback,
        final Handler handler) {
    String jsonRequest = method.toJsonString();
    try {
        HttpURLConnection connection = openHttpConnection(hostInfo);
        sendHttpRequest(connection, jsonRequest);
        // Read response and convert it
        final T result = method.resultFromJson(parseJsonResponse(readHttpResponse(connection)));

        if ((handler != null) && (callback != null)) {
            handler.post(new Runnable() {
                @Override
                public void run() {
                    callback.onSucess(result);
                }
            });
        }
    } catch (final ApiException e) {
        // Got an error, call error handler

        if ((handler != null) && (callback != null)) {
            handler.post(new Runnable() {
                @Override
                public void run() {
                    callback.onError(e.getCode(), e.getMessage());
                }
            });
        }
    }
}

From source file:com.echopf.ECHOTreeMap.java

/**
 * Does Fetch data from the remote server in a background thread.
 *
 * @param sync if set TRUE, then the main (UI) thread is waited for complete the fetching in a background thread. 
 *         (a synchronous communication)
 * @param callback invoked after the fetching is completed
 * @throws ECHOException /* www .  j  a v  a  2  s .  c o m*/
 */
protected void doFetch(final boolean sync, final FetchCallback<S> callback) throws ECHOException {
    final Handler handler = new Handler();

    // Get ready a background thread
    ExecutorService executor = Executors.newSingleThreadExecutor();
    Callable<Object> communictor = new Callable<Object>() {

        @Override
        public Object call() throws ECHOException {

            ECHOException exception = null;
            JSONObject data = null;

            try {

                synchronized (lock) {
                    data = ECHOQuery.getRequest(getRequestURLPath());
                    copyData(data);
                }

            } catch (ECHOException e) {
                exception = e;
            } catch (Exception e) {
                exception = new ECHOException(e);
            }

            if (sync == false) {

                // Execute a callback method in the main (UI) thread.
                if (callback != null) {
                    final ECHOException fException = exception;
                    handler.post(new Runnable() {
                        @Override
                        @SuppressWarnings("unchecked")
                        public void run() {
                            callback.done((S) ECHOTreeMap.this, fException);
                        }
                    });
                }

            } else {

                if (exception != null)
                    throw exception;
            }

            return null;
        }
    };

    Future<Object> future = executor.submit(communictor);

    if (sync) {
        try {
            future.get();
        } catch (InterruptedException e) {
            Thread.currentThread().interrupt(); // ignore/reset
        } catch (ExecutionException e) {
            Throwable e2 = e.getCause();

            if (e2 instanceof ECHOException) {
                throw (ECHOException) e2;
            }

            throw new RuntimeException(e2);
        }
    }
}

From source file:com.facebook.GraphRequest.java

static void runCallbacks(final GraphRequestBatch requests, List<GraphResponse> responses) {
    int numRequests = requests.size();

    // Compile the list of callbacks to call and then run them either on this thread or via the
    // Handler we received
    final ArrayList<Pair<Callback, GraphResponse>> callbacks = new ArrayList<Pair<Callback, GraphResponse>>();
    for (int i = 0; i < numRequests; ++i) {
        GraphRequest request = requests.get(i);
        if (request.callback != null) {
            callbacks.add(new Pair<Callback, GraphResponse>(request.callback, responses.get(i)));
        }//ww  w  . j  av a 2s  .  com
    }

    if (callbacks.size() > 0) {
        Runnable runnable = new Runnable() {
            public void run() {
                for (Pair<Callback, GraphResponse> pair : callbacks) {
                    pair.first.onCompleted(pair.second);
                }

                List<GraphRequestBatch.Callback> batchCallbacks = requests.getCallbacks();
                for (GraphRequestBatch.Callback batchCallback : batchCallbacks) {
                    batchCallback.onBatchCompleted(requests);
                }
            }
        };

        Handler callbackHandler = requests.getCallbackHandler();
        if (callbackHandler == null) {
            // Run on this thread.
            runnable.run();
        } else {
            // Post to the handler.
            callbackHandler.post(runnable);
        }
    }
}

From source file:com.bellman.bible.android.view.activity.base.ProgressActivityBase.java

private void initialiseView() {
    // prepare to show no tasks msg
    noTasksMessageView = (TextView) findViewById(R.id.noTasksRunning);
    taskKillWarningView = (TextView) findViewById(R.id.progressStatusMessage);

    Iterator<Progress> jobsIterator = JobManager.iterator();
    while (jobsIterator.hasNext()) {
        Progress job = jobsIterator.next();
        findOrCreateUIControl(job);// w w w  .  j  av a 2  s  .c o m
    }

    // allow call back and continuation in the ui thread after JSword has been initialised
    final Handler uiHandler = new Handler();
    final Runnable uiUpdaterRunnable = new Runnable() {
        @Override
        public void run() {
            Progress prog = progressNotificationQueue.poll();
            if (prog != null) {
                updateProgress(prog);
            }
        }
    };

    // listen for Progress changes and call the above Runnable to update the ui
    workListener = new WorkListener() {
        @Override
        public void workProgressed(WorkEvent ev) {
            callUiThreadUpdateHandler(ev);
        }

        @Override
        public void workStateChanged(WorkEvent ev) {
            callUiThreadUpdateHandler(ev);
        }

        private void callUiThreadUpdateHandler(WorkEvent ev) {
            Progress prog = ev.getJob();
            progressNotificationQueue.offer(prog);
            // switch back to ui thread to continue
            uiHandler.post(uiUpdaterRunnable);
        }
    };
    JobManager.addWorkListener(workListener);

    // give new jobs a chance to start then show 'No Job' msg if nothing running
    uiHandler.postDelayed(new Runnable() {
        @Override
        public void run() {
            if (!JobManager.iterator().hasNext()) {
                showNoTaskMsg(true);
            }
        }
    }, 4000);
}

From source file:com.syncedsynapse.kore2.jsonrpc.HostConnection.java

/**
 * Sends the JSON RPC request through TCP
 * Keeps a background thread running, listening on a socket
 *///from ww  w.  j a v a 2  s .  c  om
private <T> void executeThroughTcp(final ApiMethod<T> method, final ApiCallback<T> callback,
        final Handler handler) {
    String methodId = String.valueOf(method.getId());
    try {
        // Save this method/callback for later response
        // Check if a method with this id is already running and raise an error if so
        synchronized (clientCallbacks) {
            if (clientCallbacks.containsKey(methodId)) {
                if ((handler != null) && (callback != null)) {
                    handler.post(new Runnable() {
                        @Override
                        public void run() {
                            callback.onError(ApiException.API_METHOD_WITH_SAME_ID_ALREADY_EXECUTING,
                                    "A method with the same Id is already executing");
                        }
                    });
                }
                return;
            }
            clientCallbacks.put(methodId, new MethodCallInfo<T>(method, callback, handler));
        }

        // TODO: Validate if this shouldn't be enclosed by a synchronized.
        if (socket == null) {
            // Open connection to the server and setup reader thread
            socket = openTcpConnection(hostInfo);
            listenerThread = newListenerThread(socket);
            listenerThread.start();
        }

        // Write request
        sendTcpRequest(socket, method.toJsonString());
    } catch (final ApiException e) {
        callErrorCallback(methodId, e);
    }
}

From source file:github.daneren2005.dsub.util.Notifications.java

public static void showPlayingNotification(final Context context, final DownloadService downloadService,
        final Handler handler, MusicDirectory.Entry song) {
    // Set the icon, scrolling text and timestamp
    final Notification notification = new Notification(R.drawable.stat_notify_playing, song.getTitle(),
            System.currentTimeMillis());

    final boolean playing = downloadService.getPlayerState() == PlayerState.STARTED;
    if (playing) {
        notification.flags |= Notification.FLAG_NO_CLEAR | Notification.FLAG_ONGOING_EVENT;
    }//from   w w  w.  j  a  v  a2s.co  m
    boolean remote = downloadService.isRemoteEnabled();
    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN) {
        RemoteViews expandedContentView = new RemoteViews(context.getPackageName(),
                R.layout.notification_expanded);
        setupViews(expandedContentView, context, song, true, playing, remote);
        notification.bigContentView = expandedContentView;
        notification.priority = Notification.PRIORITY_HIGH;
    }
    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
        notification.visibility = Notification.VISIBILITY_PUBLIC;
    }

    RemoteViews smallContentView = new RemoteViews(context.getPackageName(), R.layout.notification);
    setupViews(smallContentView, context, song, false, playing, remote);
    notification.contentView = smallContentView;

    Intent notificationIntent = new Intent(context, SubsonicFragmentActivity.class);
    notificationIntent.putExtra(Constants.INTENT_EXTRA_NAME_DOWNLOAD, true);
    notificationIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TOP);
    notification.contentIntent = PendingIntent.getActivity(context, 0, notificationIntent, 0);

    playShowing = true;
    if (downloadForeground && downloadShowing) {
        downloadForeground = false;
        handler.post(new Runnable() {
            @Override
            public void run() {
                downloadService.stopForeground(true);
                showDownloadingNotification(context, downloadService, handler,
                        downloadService.getCurrentDownloading(),
                        downloadService.getBackgroundDownloads().size());
                downloadService.startForeground(NOTIFICATION_ID_PLAYING, notification);
            }
        });
    } else {
        handler.post(new Runnable() {
            @Override
            public void run() {
                if (playing) {
                    downloadService.startForeground(NOTIFICATION_ID_PLAYING, notification);
                } else {
                    playShowing = false;
                    persistentPlayingShowing = true;
                    NotificationManager notificationManager = (NotificationManager) context
                            .getSystemService(Context.NOTIFICATION_SERVICE);
                    downloadService.stopForeground(false);
                    notificationManager.notify(NOTIFICATION_ID_PLAYING, notification);
                }
            }
        });
    }

    // Update widget
    DSubWidgetProvider.notifyInstances(context, downloadService, playing);
}

From source file:com.dmsl.anyplace.tasks.AnyplaceSuggestionsTask.java

@Override
protected String doInBackground(Void... params) {
    try {/* w w w. j av a 2s. c  om*/
        // get the search suggestions
        if (searchType == SearchTypes.INDOOR_MODE) {
            // if we are at a zoom level higher than 19 then we use the
            // AnyPlacePOI API

            // sleep for a while to avoid execution in case another task
            // started and check afterwards if you are cancelled
            Thread.sleep(150);
            if (isCancelled()) {
                return "Cancelled!";
            }

            // use the 2-step method to get out quickly if this task is
            // cancelled
            List<PoisModel> places = queryStaticAnyPlacePOI(query);
            if (isCancelled()) {
                return "Cancelled!";
            }

            // create the cursor for the results
            // cursor = AnyPlaceSeachingHelper.prepareSearchViewCursor(places);
            pois = places;

        } else if (searchType == SearchTypes.OUTDOOR_MODE) {
            // at a lower zoom level we use the Google Places API for search
            // in order to allow the user to search more coarsely for
            // locations

            // sleep for a while to avoid execution in case another task
            // started and check afterwards if you are cancelled
            Thread.sleep(500);
            if (isCancelled()) {
                return "Cancelled!";
            }

            // Get a handler that can be used to post to the main thread
            Handler mainHandler = new Handler(ctx.getMainLooper());

            Runnable myRunnable = new Runnable() {

                @Override
                public void run() {
                    try {
                        List<IPoisClass> places = new ArrayList<IPoisClass>(1);
                        PoisModel pm = new PoisModel();
                        pm.name = "Searching through Google ...";
                        places.add(pm);
                        Cursor cursor = AnyPlaceSeachingHelper.prepareSearchViewCursor(places);
                        mListener.onUpdateStatus("Dummy Result", cursor);
                    } finally {
                        synchronized (sync) {
                            run = true;
                            sync.notifyAll();
                        }
                    }
                }
            };

            mainHandler.post(myRunnable);

            // cursor = AnyplacePOIProvider.queryStatic(query,
            // AnyplacePOIProvider.POI_GOOGLE_PLACES, position);
            PlacesList places = GooglePlaces.queryStaticGoogle(query, position);
            if (isCancelled())
                return "Cancelled!";

            // create the cursor for the results
            // cursor = AnyPlaceSeachingHelper.prepareSearchViewCursor(places.results);
            pois = places.results;

            synchronized (sync) {
                while (run == false) {
                    sync.wait();
                }
            }

        }

        if (isCancelled()) {
            return "Cancelled!";
        }

        return "Success!";

    } catch (ConnectTimeoutException e) {
        exceptionOccured = true;
        return "Connecting to the server is taking too long!";
    } catch (SocketTimeoutException e) {
        exceptionOccured = true;
        return "Communication with the server is taking too long!";
    } catch (IOException e) {
        exceptionOccured = true;
        return "Communication error[ " + e.getMessage() + " ]";
    } catch (InterruptedException e) {
        exceptionOccured = true;
        return "Suggestions task interrupted!";
    }

}

From source file:org.matrix.androidsdk.db.MXMediaDownloadWorkerTask.java

@Override
protected Void doInBackground(Integer... params) {
    try {//  w  w w.jav  a 2 s.  co m
        URL url = new URL(mUrl);
        Log.d(LOG_TAG, "MXMediaDownloadWorkerTask " + this + " starts");

        mDownloadStats = new IMXMediaDownloadListener.DownloadStats();
        // don't known yet
        mDownloadStats.mEstimatedRemainingTime = -1;

        InputStream stream = null;

        int filelen = -1;
        URLConnection connection = null;

        try {
            connection = url.openConnection();

            if (mHsConfig != null && connection instanceof HttpsURLConnection) {
                // Add SSL Socket factory.
                HttpsURLConnection sslConn = (HttpsURLConnection) connection;
                try {
                    Pair<SSLSocketFactory, X509TrustManager> pair = CertUtil
                            .newPinnedSSLSocketFactory(mHsConfig);
                    sslConn.setSSLSocketFactory(pair.first);
                    sslConn.setHostnameVerifier(CertUtil.newHostnameVerifier(mHsConfig));
                } catch (Exception e) {
                    Log.e(LOG_TAG, "doInBackground SSL exception " + e.getLocalizedMessage());
                }
            }

            // add a timeout to avoid infinite loading display.
            connection.setReadTimeout(DOWNLOAD_TIME_OUT);
            filelen = connection.getContentLength();
            stream = connection.getInputStream();
        } catch (Exception e) {
            Log.e(LOG_TAG, "bitmapForURL : fail to open the connection " + e.getMessage());

            InputStream errorStream = ((HttpsURLConnection) connection).getErrorStream();

            if (null != errorStream) {
                try {
                    BufferedReader streamReader = new BufferedReader(
                            new InputStreamReader(errorStream, "UTF-8"));
                    StringBuilder responseStrBuilder = new StringBuilder();

                    String inputStr;

                    while ((inputStr = streamReader.readLine()) != null) {
                        responseStrBuilder.append(inputStr);
                    }

                    mErrorAsJsonElement = new JsonParser().parse(responseStrBuilder.toString());
                } catch (Exception ee) {
                    Log.e(LOG_TAG, "bitmapForURL : Error parsing error " + ee.getLocalizedMessage());
                }
            }

            // privacy
            //Log.d(LOG_TAG, "MediaWorkerTask " + mUrl + " does not exist");
            Log.d(LOG_TAG, "MediaWorkerTask an url does not exist");

            // if some medias are not found
            // do not try to reload them until the next application launch.
            synchronized (mUnreachableUrls) {
                mUnreachableUrls.add(mUrl);
            }
        }

        dispatchDownloadStart();

        // test if the download has not been cancelled
        if (!isDownloadCancelled() && (null == mErrorAsJsonElement)) {

            final long startDownloadTime = System.currentTimeMillis();

            String filename = MXMediaDownloadWorkerTask.buildFileName(mUrl, mMimeType) + ".tmp";
            FileOutputStream fos = new FileOutputStream(new File(mDirectoryFile, filename));

            mDownloadStats.mDownloadId = mUrl;
            mDownloadStats.mProgress = 0;
            mDownloadStats.mDownloadedSize = 0;
            mDownloadStats.mFileSize = filelen;
            mDownloadStats.mElapsedTime = 0;
            mDownloadStats.mEstimatedRemainingTime = -1;
            mDownloadStats.mBitRate = 0;

            final android.os.Handler uiHandler = new android.os.Handler(Looper.getMainLooper());

            final Timer refreshTimer = new Timer();

            uiHandler.post(new Runnable() {
                @Override
                public void run() {
                    refreshTimer.scheduleAtFixedRate(new TimerTask() {
                        @Override
                        public void run() {
                            uiHandler.post(new Runnable() {
                                @Override
                                public void run() {
                                    if (!mIsDone) {
                                        publishProgress(startDownloadTime);
                                    }
                                }
                            });
                        }
                    }, new java.util.Date(), 100);
                }
            });

            try {
                byte[] buf = new byte[DOWNLOAD_BUFFER_READ_SIZE];
                int len;
                while (!isDownloadCancelled() && (len = stream.read(buf)) != -1) {
                    fos.write(buf, 0, len);
                    mDownloadStats.mDownloadedSize += len;
                }

                if (!isDownloadCancelled()) {
                    mDownloadStats.mProgress = 100;
                }
            } catch (OutOfMemoryError outOfMemoryError) {
                Log.e(LOG_TAG, "doInBackground: out of memory");
            } catch (Exception e) {
                Log.e(LOG_TAG, "doInBackground fail to read image " + e.getMessage());
            }

            mIsDone = true;

            close(stream);
            fos.flush();
            fos.close();

            if (null != mEncryptedFileInfo) {
                File file = new File(mDirectoryFile, filename);
                FileInputStream fis = new FileInputStream(file);
                InputStream is = MXEncryptedAttachments.decryptAttachment(fis, mEncryptedFileInfo);
                fis.close();

                // if the decryption succeeds, replace the encrypted file content by the unencrypted one
                if (null != is) {
                    mApplicationContext.deleteFile(filename);

                    fos = new FileOutputStream(file);
                    byte[] buf = new byte[DOWNLOAD_BUFFER_READ_SIZE];
                    int len;
                    while ((len = is.read(buf)) != -1) {
                        fos.write(buf, 0, len);
                    }
                } else {
                    mDownloadStats.mProgress = 0;
                }
            }

            uiHandler.post(new Runnable() {
                @Override
                public void run() {
                    refreshTimer.cancel();
                }
            });

            if ((null != connection) && (connection instanceof HttpsURLConnection)) {
                ((HttpsURLConnection) connection).disconnect();
            }

            // the file has been successfully downloaded
            if (mDownloadStats.mProgress == 100) {
                try {
                    File originalFile = new File(mDirectoryFile, filename);
                    String newFileName = MXMediaDownloadWorkerTask.buildFileName(mUrl, mMimeType);
                    File newFile = new File(mDirectoryFile, newFileName);
                    if (newFile.exists()) {
                        // Or you could throw here.
                        mApplicationContext.deleteFile(newFileName);
                    }
                    originalFile.renameTo(newFile);
                } catch (Exception e) {
                    Log.e(LOG_TAG, "doInBackground : renaming error " + e.getLocalizedMessage());
                }
            }
        }

        if (mDownloadStats.mProgress == 100) {
            Log.d(LOG_TAG, "The download " + this + " is done.");
        } else {
            if (null != mErrorAsJsonElement) {
                Log.d(LOG_TAG, "The download " + this + " failed : mErrorAsJsonElement "
                        + mErrorAsJsonElement.toString());
            } else {
                Log.d(LOG_TAG, "The download " + this + " failed.");
            }
        }
    } catch (Exception e) {
        Log.e(LOG_TAG, "Unable to download media " + this);
    }

    // remove the image from the loading one
    synchronized (mPendingDownloadByUrl) {
        mPendingDownloadByUrl.remove(mUrl);
    }

    return null;
}

From source file:com.flowzr.budget.holo.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;//from w  ww .ja  v  a2s  .c  om
        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;
        }
    }

    notifyUser(context.getString(R.string.integrity_fix), 80);
    new IntegrityFix(dba).fix();
    /**
     * 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) + "...", 85);
        //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)));

        String serialNumber = Build.SERIAL != Build.UNKNOWN ? Build.SERIAL
                : Settings.Secure.getString(context.getContentResolver(), Settings.Secure.ANDROID_ID);
        nameValuePairs.add(new BasicNameValuePair("serialNumber", serialNumber));
        List<Account> accountsList = em.getAllAccountsList();
        for (Account account : accountsList) {
            nameValuePairs.add(new BasicNameValuePair(account.remoteKey, String.valueOf(account.totalAmount)));
            Log.i("flowzr", account.remoteKey + " " + String.valueOf(account.totalAmount));
        }
        try {
            httpPush(nameValuePairs, "balances");
        } catch (Exception e) {
            sendBackTrace(e);
        }
    }

    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;

}

From source file:piuk.blockchain.android.ui.dialogs.NewAccountDialog.java

@Override
public Dialog onCreateDialog(final Bundle savedInstanceState) {
    super.onCreateDialog(savedInstanceState);

    final FragmentActivity activity = getActivity();
    final LayoutInflater inflater = LayoutInflater.from(activity);

    final Builder dialog = new AlertDialog.Builder(new ContextThemeWrapper(activity, R.style.Theme_Dialog))
            .setTitle(R.string.new_account_title);

    final View view = inflater.inflate(R.layout.new_account_dialog, null);

    dialog.setView(view);/*from w w w  .j  a v  a2 s.c o m*/

    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);

    createButton.setOnClickListener(new OnClickListener() {
        public void onClick(View v) {
            final WalletApplication application = (WalletApplication) getActivity().getApplication();

            if (password.getText().length() < 11 || 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 {
                        try {
                            application.generateNewWallet();
                        } catch (Exception e1) {
                            throw new Exception("Error Generating Wallet");
                        }

                        application.getRemoteWallet().setTemporyPassword(password.getText().toString());

                        if (!application.getRemoteWallet().remoteSave(captcha.getText().toString())) {
                            throw new Exception("Unknown Error Inserting wallet");
                        }

                        EventListeners.invokeWalletDidChange();

                        handler.post(new Runnable() {
                            public void run() {
                                try {
                                    progressDialog.dismiss();

                                    dismiss();

                                    Toast.makeText(getActivity().getApplication(), R.string.new_account_success,
                                            Toast.LENGTH_LONG).show();

                                    PinEntryActivity.clearPrefValues(application);

                                    Editor edit = PreferenceManager
                                            .getDefaultSharedPreferences(application.getApplicationContext())
                                            .edit();

                                    edit.putString("guid", application.getRemoteWallet().getGUID());
                                    edit.putString("sharedKey", application.getRemoteWallet().getSharedKey());

                                    AbstractWalletActivity activity = (AbstractWalletActivity) getActivity();

                                    if (edit.commit()) {
                                        application.checkWalletStatus(activity);
                                    } else {
                                        throw new Exception("Error saving preferences");
                                    }
                                } catch (Exception e) {
                                    e.printStackTrace();

                                    application.clearWallet();

                                    Toast.makeText(getActivity().getApplication(), e.getLocalizedMessage(),
                                            Toast.LENGTH_LONG).show();
                                }
                            }
                        });
                    } catch (final Exception e) {
                        e.printStackTrace();

                        application.clearWallet();

                        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();
        }
    });

    Dialog d = dialog.create();

    WindowManager.LayoutParams lp = new WindowManager.LayoutParams();

    lp.dimAmount = 0;
    lp.width = WindowManager.LayoutParams.FILL_PARENT;
    lp.height = WindowManager.LayoutParams.WRAP_CONTENT;

    d.show();

    d.getWindow().setAttributes(lp);

    d.getWindow().setBackgroundDrawable(new ColorDrawable(Color.TRANSPARENT));

    return d;
}