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:org.floppp.observerpattern_activityfragments.model.StockPrice.java

private void emit() {
    final Handler handler = new Handler();
    new Thread(new Runnable() {
        @Override/*w  ww. j  a va 2 s  . co  m*/
        public void run() {
            while (true) {
                final Pair<OPTIONS, Double> price = getPrice();
                handler.post(new Runnable() {
                    @Override
                    public void run() {
                        receiver.priceChanged(price);
                    }
                });
            }
        }
    }).start();
}

From source file:nacho.tfg.blepresencetracker.MyFirebaseInstanceIDService.java

/**
 * Persist token to third-party servers.
 *
 * Modify this method to associate the user's FCM InstanceID token with any server-side account
 * maintained by your application.//from w  w w  .ja va2  s  . co m
 *
 * @param token The new token.
 */
private void sendRegistrationToServer(String token) {
    // Add custom implementation, as needed.
    Intent intent = new Intent(ACTION_SHOW_TOKEN);
    intent.putExtra("token", token);
    LocalBroadcastManager.getInstance(this).sendBroadcast(intent);

    AsyncTask<String, Void, Boolean> asyncTask = new AsyncTask<String, Void, Boolean>() {

        @Override
        protected void onPreExecute() {
            super.onPreExecute();

        }

        @Override
        protected Boolean doInBackground(String... params) {
            String data = params[0];
            String ip = "192.168.4.1";
            int port = 7777;
            try {
                Socket socket = new Socket(ip, port);
                while (!socket.isConnected()) {

                }

                OutputStream out = socket.getOutputStream();
                PrintWriter output = new PrintWriter(out);

                output.println(data);
                output.flush();
                out.close();
                output.close();

                socket.close();
            } catch (SocketException e) {
                e.printStackTrace();
                return false;
            } catch (IOException e) {
                e.printStackTrace();
                return false;
            }
            return true;
        }

        @Override
        protected void onPostExecute(Boolean result) {
            super.onPostExecute(result);
            if (result) {
                SharedPreferences settings = PreferenceManager
                        .getDefaultSharedPreferences(MyFirebaseInstanceIDService.this);
                SharedPreferences.Editor editor = settings.edit();
                editor.putBoolean(getString(R.string.registration_id_sent), true);
                editor.commit();
            } else {
                SharedPreferences settings = PreferenceManager
                        .getDefaultSharedPreferences(MyFirebaseInstanceIDService.this);
                SharedPreferences.Editor editor = settings.edit();
                editor.putBoolean(getString(R.string.registration_id_sent), false);
                editor.commit();
            }
        }
    };

    // Change wifi network to "NodeMCU WiFi"

    String ssid = "";
    WifiManager wifiManager = (WifiManager) getSystemService(Context.WIFI_SERVICE);
    WifiInfo wifiInfo = wifiManager.getConnectionInfo();
    if (WifiInfo.getDetailedStateOf(wifiInfo.getSupplicantState()) == NetworkInfo.DetailedState.CONNECTED) {
        ssid = wifiInfo.getSSID();
    }

    if (!ssid.equals("NodeMCU WiFi")) {
        Handler handler = new Handler(Looper.getMainLooper());
        handler.post(new Runnable() {
            @Override
            public void run() {
                Toast.makeText(getApplicationContext(), getString(R.string.toast_connect_NodeMCU),
                        Toast.LENGTH_LONG).show();

            }
        });

    }
}

From source file:com.android.volley.ExecutorDelivery.java

/**
 * Creates a new response delivery interface.
 * @param handler {@link Handler} to post responses on
 *//*from   w  w w .j a va  2 s.  c om*/
public ExecutorDelivery(final Handler handler) {
    // Make an Executor that just wraps the handler.
    mResponsePoster = new Executor() {
        @Override
        public void execute(Runnable command) {
            handler.post(command);
        }
    };
}

From source file:com.phonegap.plugins.speech.XSpeechRecognizer.java

private void stopSpeechRecognitionActivity() {
    Handler loopHandler = new Handler(Looper.getMainLooper());
    loopHandler.post(new Runnable() {

        @Override//from w w w.  j a  v a2 s.c om
        public void run() {
            recognizer.stopListening();
            // recognizer.cancel();
        }

    });
}

From source file:ch.ethz.tik.hrouting.providers.PlacesAutoCompleteAdapter.java

private StringBuilder getJsonResults(String requestType, List<String> parameters) {
    StringBuilder jsonResults = new StringBuilder();
    HttpURLConnection connection = null;
    String query = buildQuery(requestType, parameters);
    try {//from ww  w. ja  va 2 s.c  o  m
        URL url = new URL(query);
        connection = (HttpURLConnection) url.openConnection();
        InputStreamReader in = new InputStreamReader(connection.getInputStream());

        // Load the results into a StringBuilder
        int read;
        char[] buff = new char[1024];
        while ((read = in.read(buff)) != -1) {
            jsonResults.append(buff, 0, read);
        }
    } catch (MalformedURLException e) {
        Log.e(LOG_TAG, "Error processing Places API URL", e);
        e.printStackTrace();
        return null;
    } catch (IOException e) {
        Log.e(LOG_TAG, "Error connecting to Places API", e);
        e.printStackTrace();

        // Autocomplete is running in a thread, create a handler to post
        // message to the main thread
        Handler mHandler = new Handler(getContext().getMainLooper());
        mHandler.post(new Runnable() {
            @Override
            public void run() {
                Toast.makeText(getContext().getApplicationContext(), "Not able to reach Google Place API",
                        Toast.LENGTH_LONG).show();
            }
        });

        return null;
    } finally {
        if (connection != null) {
            connection.disconnect();
        }
    }
    return jsonResults;
}

From source file:me.tassoevan.cordova.ForegroundService.java

@Override
public void onCreate() {
    super.onCreate();

    final Handler handler = new Handler();

    startForeground(NOTIFICATION_ID, makeNotification());

    keepAliveTask = new TimerTask() {
        @Override//from w w w . j  a va  2 s.co m
        public void run() {
            handler.post(new Runnable() {
                @Override
                public void run() {
                    Log.d(BackgroundPlugin.class.getName(), "" + new Date().getTime());
                }
            });
        }
    };

    scheduler.schedule(keepAliveTask, 0, 1000);
}

From source file:com.onesignal.OneSignal.java

static void runOnUiThread(Runnable action) {
    Handler handler = new Handler(Looper.getMainLooper());
    handler.post(action);
}

From source file:at.andreasrohner.spartantimelapserec.BackgroundService.java

@Override
public void onDestroy() {
    created = false;/* ww  w  . j  a  va 2s. co  m*/
    File projectDir = null;

    final Handler handler = new Handler(handlerThread.getLooper());
    handler.post(new Runnable() {
        @Override
        public void run() {
            if (recorder != null)
                recorder.stop();
            handlerThread.quit();
        }
    });

    try {
        handlerThread.join(5000);
        if (handlerThread.isAlive()) {
            handlerThread.quit();
            handlerThread.join(2000);
        }
    } catch (Exception e) {
    }

    if (recorder != null) {
        projectDir = recorder.getOutputDir();
        recorder = null;
    }

    if (surfaceView != null) {
        WindowManager winMgr = (WindowManager) getSystemService(Context.WINDOW_SERVICE);
        winMgr.removeView(surfaceView);
    }

    if (wakeLock != null)
        wakeLock.release();

    if (projectDir != null && projectDir.exists())
        sendBroadcast(new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE, Uri.fromFile(projectDir)));
}

From source file:com.phonegap.plugins.speech.XSpeechRecognizer.java

public boolean execute(String action, JSONArray args, CallbackContext callbackContext) {
    this.callbackContext = callbackContext;
    Boolean isValidAction = true;

    if (ACTION_SPEECH_RECOGNIZE_START.equals(action)) {
        Handler loopHandler = new Handler(Looper.getMainLooper());
        loopHandler.post(new Runnable() {
            @Override/*from ww w  . j av  a2 s  . com*/
            public void run() {
                recognizer = SpeechRecognizer.createSpeechRecognizer(cordova.getActivity().getBaseContext());
                recognizer.setRecognitionListener(new listener());
            }

        });
        startSpeechRecognitionActivity(args);
    } else if (ACTION_GET_SUPPORTED_LANGUAGES.equals(action)) {
        getSupportedLanguages();
    } else if (ACTION_SPEECH_RECOGNIZE_STOP.equals(action)) {
        stopSpeechRecognitionActivity();
    } else {
        this.callbackContext.error("Unknown action: " + action);
        isValidAction = false;
    }

    return isValidAction;
}

From source file:com.sentaroh.android.Utilities.ContextMenu.CustomContextMenuFragment.java

private void reInitViewWidget() {
    if (DEBUG_ENABLE)
        Log.v(APPLICATION_TAG, "reInitViewWidget");
    if (!terminateRequired) {
        Handler hndl = new Handler();
        hndl.post(new Runnable() {
            @Override//from   ww  w  .  j av  a  2  s .c om
            public void run() {
                mDialog.hide();
                //               mDialog.getWindow().getDecorView().invalidate();
                mDialog.getWindow().getCurrentFocus().invalidate();
                initViewWidget();
                CommonDialog.setDlgBoxSizeCompact(mDialog);
                mDialog.show();
            }
        });
    }
}