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:audio.lisn.adapter.StoreBookViewAdapter.java

private void updateTimer() {
    try {/*from  w w w. jav a2 s.c  om*/
        int currentPosition = mediaPlayer.getCurrentPosition();
        int totalDuration = mediaPlayer.getDuration();
        leftTime = AppUtils.milliSecondsToTimer(totalDuration - currentPosition);
        // Get a handler that can be used to post to the main thread
        Handler mainHandler = new Handler(context.getMainLooper());

        Runnable timerRunnable = new Runnable() {
            @Override
            public void run() {
                notifyDataSetChanged();

            } // This is your code
        };
        mainHandler.post(timerRunnable);
    } catch (Exception e) {

    }

}

From source file:com.mikhaellopez.saveinsta.activity.MainActivity.java

private void startDownloadVideo(final String urlVideo, final String fileName) {
    final Handler handler = new Handler();
    new Thread(new Runnable() {
        @Override//from  w w w  . jav a2  s .  c  om
        public void run() {
            final boolean isDownload = downloadVideo(urlVideo, fileName);
            handler.post(new Runnable() {
                @Override
                public void run() {
                    if (isDownload) {
                        Snackbar.make(mCoordinatorLayout, R.string.snackbar_video_saved, Snackbar.LENGTH_SHORT)
                                .show();
                    } else {
                        Snackbar.make(mCoordinatorLayout, R.string.snackbar_save_video_failed,
                                Snackbar.LENGTH_SHORT).show();
                    }
                }
            });

        }
    }).start();
}

From source file:cz.yetanotherview.webcamviewer.app.MainActivity.java

private void autoRefreshTimer(int interval) {
    final Handler handler = new Handler();
    Timer timer = new Timer();
    TimerTask doAsynchronousTask = new TimerTask() {
        @Override//from   w  w w  .ja v  a 2s  .  c  o  m
        public void run() {
            handler.post(new Runnable() {
                public void run() {
                    try {
                        //refresh();
                    } catch (Exception ignored) {
                    }
                }
            });
        }
    };
    timer.schedule(doAsynchronousTask, 0, interval);
}

From source file:com.owncloud.android.services.OperationsService.java

/**
 * Notifies the currently subscribed listeners about the end of an operation.
 *
 * @param operation         Finished operation.
 * @param result            Result of the operation.
 *//*  w  w  w  .ja v  a  2 s .  c  o m*/
protected void dispatchResultToOperationListeners(final RemoteOperation operation,
        final RemoteOperationResult result) {
    int count = 0;
    Iterator<OnRemoteOperationListener> listeners = mOperationsBinder.mBoundListeners.keySet().iterator();
    while (listeners.hasNext()) {
        final OnRemoteOperationListener listener = listeners.next();
        final Handler handler = mOperationsBinder.mBoundListeners.get(listener);
        if (handler != null) {
            handler.post(new Runnable() {
                @Override
                public void run() {
                    listener.onRemoteOperationFinish(operation, result);
                }
            });
            count += 1;
        }
    }
    if (count == 0) {
        Pair<RemoteOperation, RemoteOperationResult> undispatched = new Pair<>(operation, result);
        mUndispatchedFinishedOperations.put(operation.hashCode(), undispatched);
    }
    Log_OC.d(TAG, "Called " + count + " listeners");
}

From source file:com.money.manager.ex.assetallocation.AssetAllocationActivity.java

private LoaderManager.LoaderCallbacks<AssetClass> setUpLoaderCallbacks() {
    return new LoaderManager.LoaderCallbacks<AssetClass>() {
        @Override//from  ww  w  .ja  v  a2s  .c  o m
        public Loader<AssetClass> onCreateLoader(int id, Bundle args) {
            return new AssetAllocationLoader(AssetAllocationActivity.this);
        }

        @Override
        public void onLoadFinished(Loader<AssetClass> loader, final AssetClass data) {
            AssetAllocationActivity.this.assetAllocation = data;

            // Create handler to perform showing of fragment(s).
            Handler h = new Handler(Looper.getMainLooper());
            Runnable runnable = new Runnable() {
                public void run() {
                    showAssetClass(data);
                }
            };

            // show the data
            AssetAllocationFragment fragment = (AssetAllocationFragment) UIHelpers
                    .getVisibleFragment(AssetAllocationActivity.this);
            // If there are no other fragments, create the initial view.
            if (fragment == null) {
                h.post(runnable);
            } else {
                // Otherwise, find the fragment and update the data.
                //                    refreshDataInFragment(data);
                refreshDataInFragments(data);
            }
        }

        @Override
        public void onLoaderReset(Loader<AssetClass> loader) {
            // adapter swap cursor?
        }
    };
}

From source file:com.money.manager.ex.assetallocation.editor.AssetAllocationEditorActivity.java

private LoaderManager.LoaderCallbacks<AssetClass> setUpLoaderCallbacks() {
    return new LoaderManager.LoaderCallbacks<AssetClass>() {
        @Override//from   w  w w . ja v  a2  s .  c  om
        public Loader<AssetClass> onCreateLoader(int id, Bundle args) {
            return new AssetAllocationLoader(AssetAllocationEditorActivity.this);
        }

        @Override
        public void onLoadFinished(Loader<AssetClass> loader, final AssetClass data) {
            AssetAllocationEditorActivity.this.assetAllocation = data;

            // Create handler to perform showing of fragment(s).
            Handler h = new Handler(Looper.getMainLooper());
            Runnable runnable = new Runnable() {
                public void run() {
                    showAssetClass(data);
                }
            };

            // show the data
            AssetAllocationContentsFragment fragment = (AssetAllocationContentsFragment) UIHelpers
                    .getVisibleFragment(AssetAllocationEditorActivity.this);
            // If there are no other fragments, create the initial view.
            if (fragment == null) {
                h.post(runnable);
            } else {
                // Otherwise, find the fragment and update the data.
                //                    refreshDataInFragment(data);
                refreshDataInFragments(data);
            }
        }

        @Override
        public void onLoaderReset(Loader<AssetClass> loader) {
            // adapter swap cursor?
        }
    };
}

From source file:com.facebook.samples.musicdashboard.MusicGalleryFragment.java

void fetchMusic() {
    // Kill any current downloads
    if (downloadThread != null) {
        downloadThread.quit();/*from   w w  w  . j a  v a2 s .co  m*/
        downloadThread = null;
    }

    songs = new ArrayList<Song>();

    Context c = getActivity().getApplicationContext();
    final MusicFetcher fetcher = new MusicFetcher(c);

    // The handler for song image/info download
    Handler handler = new Handler();
    // The listener for song image/info download
    SongImageDownloadListener listener = new SongImageDownloadListener() {
        public void onSongImageUpdated() {
            if (null == adapter)
                return;
            // Notify the GridView that data has changed
            adapter.notifyDataSetChanged();
        }
    };

    // The thread to download song image info
    downloadThread = new SongFetcherThread("SongImage", c, handler, listener);
    downloadThread.start();

    final Handler mHandler = new Handler();
    // Facebook - Graph API request for the music.listens info
    MusicDashboardApplication.mAsyncRunner.request("me/music.listens", new BaseRequestListener() {

        @Override
        public void onComplete(final String response, Object state) {
            // Pass the JSON response and get the music info
            songs = fetcher.fetchSongs(response);
            mHandler.post(new Runnable() {
                @Override
                public void run() {
                    // Update the GridView with initial info that does
                    // not include song image and other details that
                    // are about to be downloaded
                    setAdapter(new SongAdapter(songs));

                    // Clear the cache in preparation for image downloads
                    downloadThread.clearSongImages();

                    // For each song that was parsed out in the "fetchSongs"
                    // call, get the song info and image
                    for (Song song : songs) {
                        downloadThread.downloadSongInfo(song);
                        downloadThread.downloadSongImage(song);
                    }
                }
            });

        }

    });
}

From source file:org.proninyaroslav.libretorrent.fragments.AddTorrentFragment.java

@Override
public void onActivityCreated(Bundle savedInstanceState) {
    super.onActivityCreated(savedInstanceState);

    if (activity == null) {
        activity = (AppCompatActivity) getActivity();
    }/*from   w  ww. j  ava  2  s.c  o  m*/

    adapter = new ViewPagerAdapter(activity.getSupportFragmentManager());

    Utils.showColoredStatusBar_KitKat(activity);

    toolbar = (Toolbar) activity.findViewById(R.id.toolbar);
    if (toolbar != null) {
        toolbar.setTitle(R.string.add_torrent_title);
    }

    activity.setSupportActionBar(toolbar);
    setHasOptionsMenu(true);

    if (activity.getSupportActionBar() != null) {
        activity.getSupportActionBar().setDisplayHomeAsUpEnabled(true);
    }

    if (savedInstanceState != null) {
        pathToTempTorrent = savedInstanceState.getString(TAG_PATH_TO_TEMP_TORRENT);
        saveTorrentFile = savedInstanceState.getBoolean(TAG_SAVE_TORRENT_FILE);
        hasTorrent = savedInstanceState.getBoolean(TAG_HAS_TORRENT);
        /*
         * No initialize fragments in the event of an decode error or
         * torrent decoding in process (after configuration changes)
         */
        if (hasTorrent) {
            initFragments();
        }

    } else {
        final StringBuilder progressDialogText = new StringBuilder("");
        if (uri == null || uri.getScheme() == null) {
            progressDialogText.append(getString(R.string.decode_torrent_default_message));
        } else {
            switch (uri.getScheme()) {
            case Utils.MAGNET_PREFIX:
                progressDialogText.append(getString(R.string.decode_torrent_fetch_magnet_message));
                break;
            case Utils.HTTP_PREFIX:
            case Utils.HTTPS_PREFIX:
                progressDialogText.append(getString(R.string.decode_torrent_downloading_torrent_message));
                break;
            default:
                progressDialogText.append(getString(R.string.decode_torrent_default_message));
                break;
            }
        }

        /*
         * The AsyncTask class must be loaded on the UI thread. This is done automatically as of JELLY_BEAN.
         * http://developer.android.com/intl/ru/reference/android/os/AsyncTask.html
         */
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN) {
            decodeTask = new TorrentDecodeTask(progressDialogText.toString());
            decodeTask.executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR, uri);
        } else {
            Handler handler = new Handler(activity.getMainLooper());
            Runnable r = new Runnable() {
                @Override
                public void run() {
                    decodeTask = new TorrentDecodeTask(progressDialogText.toString());
                    decodeTask.executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR, uri);
                }
            };
            handler.post(r);
        }
    }
}

From source file:com.uraroji.garage.android.arrraycopybench.MainActivity.java

private void showResult(final String title, final BenchResult benchResult, Handler handler) {
    handler.post(new Runnable() {
        public void run() {
            mResultTextView.setText(mResultTextView.getText() + title + " :\n");
            mResultTextView.setText(mResultTextView.getText() + "\taverage "
                    + String.format("%.2f", benchResult.average() / 1000d) + " microsec\n");
            mResultTextView.setText(mResultTextView.getText() + "\ttotal "
                    + String.format("%.2f", benchResult.total() / 1000d) + " microsec\n");
        }/* w  w w . jav  a2 s. c  o  m*/
    });
}

From source file:de.stadtrallye.rallyesoft.model.Server.java

private void notifyServerInfo() {
    android.os.Handler handler;
    synchronized (listeners) {
        serverLock.readLock().lock();//  w  w w. j  a v  a2s  .  co  m
        try {
            for (final IServer.IServerListener listener : listeners) {
                handler = listener.getCallbackHandler();
                if (handler != null) {
                    handler.post(new Runnable() {
                        @Override
                        public void run() {
                            serverLock.readLock().lock();
                            try {
                                listener.onServerInfoChanged(serverInfo);
                            } finally {
                                serverLock.readLock().unlock();
                            }
                        }
                    });
                } else {
                    listener.onServerInfoChanged(serverInfo);
                }
            }
        } finally {
            serverLock.readLock().unlock();
        }
    }
}