Example usage for android.os Looper loop

List of usage examples for android.os Looper loop

Introduction

In this page you can find the example usage for android.os Looper loop.

Prototype

public static void loop() 

Source Link

Document

Run the message queue in this thread.

Usage

From source file:com.honeywell.printer.net.autobaln_websocket.WebSocketWriter.java

@Override
public void run() {
    OutputStream outputStream = null;
    try {//from w  w w.  j  av  a2 s  .  c o m
        outputStream = mSocket.getOutputStream();
    } catch (IOException e) {
        Log.e(TAG, e.getLocalizedMessage());
    }

    this.mOutputStream = outputStream;

    Looper.prepare();

    this.mHandler = new ThreadHandler(this);

    synchronized (this) {
        Log.d(TAG, "WebSocker writer running.");

        notifyAll();
    }

    Looper.loop();
}

From source file:applab.search.client.SynchronizationManager.java

/**
 * Called by our background or timer thread to perform the actual synchronization tasks from a separate thread.
 * //w  w w. j av a2s  . c  o  m
 * @throws XmlPullParserException
 */
private void performBackgroundSynchronization() throws XmlPullParserException {
    Boolean setupLooper = true;
    if (this.launchedFromTimer) {
        setupLooper = false;
    }

    if (setupLooper) {
        // we may want to associate UI with this task, so create
        // a looper to setup the message pump (by default, background threads
        // don't have a message pump)

        Looper.prepare();
    }

    try {
        sendInternalMessage(GlobalConstants.KEYWORD_DOWNLOAD_STARTING); // We send this so that the dialog shows up
                                                                        // immediately
        SynchronizationManager.singleton.isSynchronizing = true;

        // First submit pending farmer registrations and get latest registration form
        String serverUrl = Settings.getServerUrl();
        FarmerRegistrationController farmerRegController = new FarmerRegistrationController();
        farmerRegController.postFarmerRegistrationData(serverUrl);
        farmerRegController.fetchAndStoreRegistrationForm(serverUrl);

        // Then submit pending usage logs and incomplete searches
        InboxAdapter inboxAdapter = new InboxAdapter(ApplabActivity.getGlobalContext());
        inboxAdapter.open();
        submitPendingUsageLogs(inboxAdapter);

        inboxAdapter.close();

        // Finally update keywords
        updateKeywords();
    } catch (Exception e) {
        e.printStackTrace();
        completeSynchronization();
    }

    if (setupLooper) {
        // TODO: Looper.loop is problematic here. This should be restructured
        Looper.loop();
        Looper looper = Looper.getMainLooper();
        looper.quit();
    }
}

From source file:cvut.fel.mobilevoting.murinrad.communications.Connection.java

/**
 * retrieves the questions and sends them to the view Starts the connection
 *///from w ww .j  av  a  2s . c  om
public void retrieveQuestions() {
    Thread t = new Thread() {
        @Override
        public void run() {
            Looper.prepare();
            try {
                postAndRecieve("GET", "/", null, null, true);
            } catch (Exception ex) {

            }
            Looper.loop();
        }
    };
    t.start();

    // notifyOfProggress();

}

From source file:com.wishlist.Wishlist.java

public void fetchCurrentLocation() {
    new Thread() {
        public void run() {
            Looper.prepare();//from ww  w.  j a v a 2  s . c o m
            mLocationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
            MyLocationListener locationListener = new MyLocationListener();
            Criteria criteria = new Criteria();
            criteria.setAccuracy(Criteria.ACCURACY_COARSE);
            String provider = mLocationManager.getBestProvider(criteria, true);
            if (provider != null && mLocationManager.isProviderEnabled(provider)) {
                mLocationManager.requestLocationUpdates(provider, 1, 0, locationListener,
                        Looper.getMainLooper());
            } else {
                showToast("Please turn on handset's GPS");
            }
            Looper.loop();
        }
    }.start();
}

From source file:net.sf.golly.HelpActivity.java

private String DownloadFile(String urlstring, String filepath) {
    // we cannot do network connections on main thread, so we do the
    // download on a new thread, but we have to wait for it to finish
    final Handler handler = new LooperInterrupter();

    cancelled = false;/*ww  w  .  j a  va2 s. c  o m*/
    progbar.setProgress(0);
    // don't show proglayout immediately
    // proglayout.setVisibility(LinearLayout.VISIBLE);

    dresult = "";
    final String durl = urlstring;
    final String dfile = filepath;
    Thread download_thread = new Thread(new Runnable() {
        public void run() {
            dresult = downloadURL(durl, dfile);
            handler.sendMessage(handler.obtainMessage());
        }
    });

    download_thread.setPriority(Thread.MAX_PRIORITY);
    download_thread.start();

    // wait for thread to finish
    try {
        Looper.loop();
    } catch (RuntimeException re) {
    }

    proglayout.setVisibility(LinearLayout.INVISIBLE);

    if (dresult.length() > 0 && !cancelled) {
        Toast.makeText(this, "Download failed! " + dresult, Toast.LENGTH_SHORT).show();
    }
    return dresult;
}

From source file:cvut.fel.mobilevoting.murinrad.communications.Connection.java

/**
 * Sends a message to the GUI thread to display a connection error
 *//* w  w w  . j ava2  s.c  o  m*/
public void showNoConError() {
    Thread t = new Thread() {
        @Override
        public void run() {
            Looper.prepare();
            try {
                parent.showConnectionError();
            } catch (Exception ex) {

            }
            Looper.loop();
        }
    };
    t.start();

}

From source file:com.facebook.notifications.NotificationsManager.java

/**
 * Present a {@link Notification} to be presented from a GCM push bundle.
 * <p/>/*from www  .j  a v a 2 s  .  com*/
 * This does not present a notification immediately, instead it caches the assets from the
 * notification bundle, and then presents a notification to the user. This allows for a smoother
 * interaction without loading indicators for the user.
 * <p/>
 * Note that only one notification can be created for a specific push bundle, should you attempt
 * to present a new notification with the same payload bundle as an existing notification, it will
 * replace and update the old notification.
 *
 * @param context              The context to send the notification from
 * @param notificationBundle   The content of the push notification
 * @param launcherIntent       The launcher intent that contains your Application's activity.
 *                             This will be modified with the FLAG_ACTIVITY_CLEAR_TOP and
 *                             FLAG_ACTIVITY_SINGLE_TOP flags, in order to properly show the
 *                             notification in an already running application.
 *                             <p/>
 *                             Should you not want this behavior, you may use the notificationExtender
 *                             parameter to customize the contentIntent of the notification before
 *                             presenting it.
 * @param notificationExtender A nullable argument that allows you to customize the notification
 *                             before displaying it. Use this to configure Icons, text, sounds,
 *                             etc. before we pass the notification off to the OS.
 */
public static boolean presentNotification(@NonNull final Context context,
        @NonNull final Bundle notificationBundle, @NonNull final Intent launcherIntent,
        @Nullable final NotificationExtender notificationExtender) {
    final JSONObject alert;
    final int payloadHash;

    try {
        String payload = notificationBundle.getString(CARD_PAYLOAD_KEY);
        if (payload == null) {
            return false;
        }
        payloadHash = payload.hashCode();

        JSONObject payloadObject = new JSONObject(payload);
        alert = payloadObject.optJSONObject("alert") != null ? payloadObject.optJSONObject("alert")
                : new JSONObject();
    } catch (JSONException ex) {
        Log.e(LOG_TAG, "Error while parsing notification bundle JSON", ex);
        return false;
    }

    final boolean[] success = new boolean[1];

    final Thread backgroundThread = new Thread(new Runnable() {
        @Override
        public void run() {
            Looper.prepare();
            prepareCard(context, notificationBundle, new PrepareCallback() {
                @Override
                public void onPrepared(@NonNull Intent presentationIntent) {
                    Intent contentIntent = new Intent(launcherIntent);
                    contentIntent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP | Intent.FLAG_ACTIVITY_SINGLE_TOP);
                    contentIntent.putExtra(EXTRA_PAYLOAD_INTENT, presentationIntent);

                    NotificationManager manager = (NotificationManager) context
                            .getSystemService(Context.NOTIFICATION_SERVICE);
                    Notification.Builder builder = new Notification.Builder(context)
                            .setSmallIcon(android.R.drawable.ic_dialog_alert)
                            .setContentTitle(alert.optString("title")).setContentText(alert.optString("body"))
                            .setAutoCancel(true)
                            .setContentIntent(PendingIntent.getActivity(context.getApplicationContext(),
                                    payloadHash, contentIntent, PendingIntent.FLAG_ONE_SHOT));

                    if (notificationExtender != null) {
                        builder = notificationExtender.extendNotification(builder);
                    }

                    manager.notify(NOTIFICATION_TAG, payloadHash, builder.getNotification());
                    success[0] = true;
                    Looper.myLooper().quit();
                }

                @Override
                public void onError(@NonNull Exception exception) {
                    Log.e(LOG_TAG, "Error while preparing card", exception);
                    Looper.myLooper().quit();
                }
            });

            Looper.loop();
        }
    });

    backgroundThread.start();

    try {
        backgroundThread.join();
    } catch (InterruptedException ex) {
        Log.e(LOG_TAG, "Failed to wait for background thread", ex);
        return false;
    }
    return success[0];
}

From source file:app.axe.imooc.zxing.app.CaptureActivity.java

@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
    super.onActivityResult(requestCode, resultCode, data);
    if (resultCode == RESULT_OK) {
        uri = data.getData();// www .  ja v a2 s  .co  m
        new Thread(new Runnable() {
            @Override
            public void run() {

                Result result = scanningImage(uri);
                if (result == null) {
                    Looper.prepare();
                    Toast.makeText(getApplicationContext(), "?", Toast.LENGTH_SHORT).show();
                    Looper.loop();
                } else {
                    // ???
                    String recode = (result.toString());
                    Intent data = new Intent();
                    data.putExtra("result", recode);
                    setResult(300, data);
                    finish();
                }
            }
        }).start();
    }
}

From source file:com.qa.perf.emmageeplus.service.EmmageeService.java

@Override
public void onDestroy() {
    Log.i(LOG_TAG, "service onDestroy");
    if (windowManager != null) {
        windowManager.removeView(viFloatingWindow);
        viFloatingWindow = null;//  ww w  . j  ava 2  s.c  om
    }
    handler.removeCallbacks(task);
    closeOpenedStream();
    // replace the start time in file
    if (!BLANK_STRING.equals(startTime)) {
        replaceFileString(resultFilePath, START_TIME,
                getString(R.string.start_time) + startTime + Constants.LINE_END);
    } else {
        replaceFileString(resultFilePath, START_TIME, BLANK_STRING);
    }
    isStop = true;
    unregisterReceiver(batteryBroadcast);

    new Thread(new Runnable() {
        @Override
        public void run() {
            boolean isSendSuccessfully = false;
            try {
                isSendSuccessfully = MailSender.sendTextMail(sender, des.decrypt(password), smtp,
                        "Emmagee Performance Test Report", "see attachment", resultFilePath, receivers);
            } catch (Exception e) {
                Log.w(LOG_TAG, "sendTextMail: ", e);
                isSendSuccessfully = false;
            }
            Looper.prepare();
            if (isSendSuccessfully) {
                Toast.makeText(EmmageeService.this, getString(R.string.send_success_toast) + recipients,
                        Toast.LENGTH_LONG).show();
            } else {
                Toast.makeText(EmmageeService.this,
                        getString(R.string.send_fail_toast) + EmmageeService.resultFilePath, Toast.LENGTH_LONG)
                        .show();
            }
            Looper.loop();
        }
    }).start();

    super.onDestroy();
    stopForeground(true);
}

From source file:org.acra.ErrorReporter.java

/**
 * Try to send a report, if an error occurs stores a report file for a later
 * attempt./*from w  w  w.j av  a 2 s.c o m*/
 *
 * @param reportBuilder The report builder used to assemble the report
 */
private void report(final ReportBuilder reportBuilder) {

    if (!enabled) {
        return;
    }

    try {
        exceptionHandlerInitializer.initializeExceptionHandler(this);
    } catch (Exception exceptionInRunnable) {
        ACRA.log.d(LOG_TAG, "Failed to initlize " + exceptionHandlerInitializer + " from #handleException");
    }

    boolean sendOnlySilentReports = false;
    ReportingInteractionMode reportingInteractionMode;
    if (!reportBuilder.mForceSilent) {
        // No interaction mode defined, we assume it has been set during
        // ACRA.initACRA()
        reportingInteractionMode = ACRA.getConfig().mode();
    } else {
        reportingInteractionMode = ReportingInteractionMode.SILENT;

        // An interaction mode has been provided. If ACRA has been
        // initialized with a non SILENT mode and this mode is overridden
        // with SILENT, then we have to send only reports which have been
        // explicitly declared as silent via handleSilentException().
        if (ACRA.getConfig().mode() != ReportingInteractionMode.SILENT) {
            sendOnlySilentReports = true;
        }
    }

    final boolean shouldDisplayToast = reportingInteractionMode == ReportingInteractionMode.TOAST
            || (ACRA.getConfig().resToastText() != 0
                    && (reportingInteractionMode == ReportingInteractionMode.NOTIFICATION
                            || reportingInteractionMode == ReportingInteractionMode.DIALOG));

    final TimeHelper sentToastTimeMillis = new TimeHelper();
    if (shouldDisplayToast) {
        new Thread() {

            /*
             * (non-Javadoc)
             *
             * @see java.lang.Thread#run()
             */
            @Override
            public void run() {
                Looper.prepare();
                ToastSender.sendToast(mContext, ACRA.getConfig().resToastText(), Toast.LENGTH_LONG);
                sentToastTimeMillis.setInitialTimeMillis(System.currentTimeMillis());
                Looper.loop();
            }

        }.start();

        // We will wait a few seconds at the end of the method to be sure
        // that the Toast can be read by the user.
    }

    final CrashReportData crashReportData = crashReportDataFactory.createCrashData(reportBuilder.mMessage,
            reportBuilder.mException, reportBuilder.mCustomData, reportBuilder.mForceSilent,
            reportBuilder.mUncaughtExceptionThread);

    // Always write the report file

    final String reportFileName = getReportFileName(crashReportData);
    saveCrashReportFile(reportFileName, crashReportData);

    if (reportBuilder.mEndsApplication && !ACRA.getConfig().sendReportsAtShutdown()) {
        endApplication(reportBuilder.mUncaughtExceptionThread, reportBuilder.mException);
    }

    SendWorker sender = null;

    if (reportingInteractionMode == ReportingInteractionMode.SILENT
            || reportingInteractionMode == ReportingInteractionMode.TOAST
            || prefs.getBoolean(ACRA.PREF_ALWAYS_ACCEPT, false)) {

        // Approve and then send reports now
        ACRA.log.d(LOG_TAG, "About to start ReportSenderWorker from #handleException");
        sender = startSendingReports(sendOnlySilentReports, true);
        if ((reportingInteractionMode == ReportingInteractionMode.SILENT) && !reportBuilder.mEndsApplication) {
            // Report is being sent silently and the application is not ending.
            // So no need to wait around for the sender to complete.
            return;
        }

    } else if (reportingInteractionMode == ReportingInteractionMode.NOTIFICATION) {
        ACRA.log.d(LOG_TAG, "Creating Notification.");
        createNotification(reportFileName, reportBuilder);
    }

    toastWaitEnded = true;
    if (shouldDisplayToast) {
        // A toast is being displayed, we have to wait for its end before doing anything else.
        // The toastWaitEnded flag will be checked before any other operation.
        toastWaitEnded = false;
        new Thread() {

            @Override
            public void run() {
                ACRA.log.d(LOG_TAG,
                        "Waiting for " + ACRAConstants.TOAST_WAIT_DURATION + " millis from "
                                + sentToastTimeMillis.initialTimeMillis + " currentMillis="
                                + System.currentTimeMillis());
                while (sentToastTimeMillis.getElapsedTime() < ACRAConstants.TOAST_WAIT_DURATION) {
                    try {
                        // Wait a bit to let the user read the toast
                        Thread.sleep(100);
                    } catch (InterruptedException e1) {
                        ACRA.log.d(LOG_TAG, "Interrupted while waiting for Toast to end.", e1);
                    }
                }
                toastWaitEnded = true;
            }
        }.start();
    }

    // Start an AsyncTask waiting for the end of the sender.
    // Once sent, call endApplication() if reportBuilder.mEndApplication
    final SendWorker worker = sender;
    final boolean showDirectDialog = (reportingInteractionMode == ReportingInteractionMode.DIALOG)
            && !prefs.getBoolean(ACRA.PREF_ALWAYS_ACCEPT, false);

    new Thread() {

        @Override
        public void run() {
            // We have to wait for the toast display to be completed.
            ACRA.log.d(LOG_TAG, "Waiting for Toast");
            while (!toastWaitEnded) {
                try {
                    Thread.sleep(100);
                } catch (InterruptedException e1) {
                    ACRA.log.d(LOG_TAG, "Error : ", e1);
                }
            }
            ACRA.log.d(LOG_TAG, "Finished waiting for Toast");

            // We have to wait for the worker job to be completed.
            if (worker != null) {
                ACRA.log.d(LOG_TAG, "Waiting for Worker");
                while (worker.isAlive()) {
                    try {
                        Thread.sleep(100);
                    } catch (InterruptedException e1) {
                        ACRA.log.d(LOG_TAG, "Error : ", e1);
                    }
                }
                ACRA.log.d(LOG_TAG, "Finished waiting for Worker");
            }

            if (showDirectDialog) {
                // Create a new activity task with the confirmation dialog.
                // This new task will be persisted on application restart
                // right after its death.
                ACRA.log.d(LOG_TAG, "Creating CrashReportDialog for " + reportFileName);
                final Intent dialogIntent = createCrashReportDialogIntent(reportFileName, reportBuilder);
                dialogIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
                mContext.startActivity(dialogIntent);
            }

            ACRA.log.d(LOG_TAG,
                    "Wait for Toast + worker ended. Kill Application ? " + reportBuilder.mEndsApplication);

            if (reportBuilder.mEndsApplication) {
                endApplication(reportBuilder.mUncaughtExceptionThread, reportBuilder.mException);
            }
        }
    }.start();
}