Example usage for android.os Handler Handler

List of usage examples for android.os Handler Handler

Introduction

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

Prototype

@UnsupportedAppUsage
public Handler(boolean async) 

Source Link

Document

Use the Looper for the current thread and set whether the handler should be asynchronous.

Usage

From source file:com.ryan.ryanreader.fragments.UserProfileDialog.java

@Override
public final void prepare(final Context context, final LinearLayout items) {

    final LoadingView loadingView = new LoadingView(context, R.string.download_waiting, true, true);
    items.addView(loadingView);//  www  . j  av a2  s .co m

    username = getArguments().getString("user");
    final CacheManager cm = CacheManager.getInstance(context);

    RedditAPI.getUser(cm, username, new APIResponseHandler.UserResponseHandler(context) {
        @Override
        protected void onDownloadStarted() {
            if (!active)
                return;
            loadingView.setIndeterminate(R.string.download_connecting);
        }

        @Override
        protected void onSuccess(final RedditUser user, long timestamp) {

            new Handler(Looper.getMainLooper()).post(new Runnable() {
                public void run() {

                    if (!active)
                        return;

                    loadingView.setDone(R.string.download_done);

                    final LinearLayout karmaLayout = (LinearLayout) getLayoutInflater().inflate(R.layout.karma);
                    items.addView(karmaLayout);

                    final TextView linkKarma = (TextView) karmaLayout.findViewById(R.id.layout_karma_text_link);
                    final TextView commentKarma = (TextView) karmaLayout
                            .findViewById(R.id.layout_karma_text_comment);

                    linkKarma.setText(String.valueOf(user.link_karma));
                    commentKarma.setText(String.valueOf(user.comment_karma));

                    items.addView(propView(context, R.string.userprofile_created,
                            RRTime.formatDateTime(user.created_utc * 1000, context), false));

                    if (user.has_mail != null) {
                        items.addView(propView(context, R.string.userprofile_hasmail,
                                user.has_mail ? R.string.general_true : R.string.general_false, false));
                    }

                    if (user.has_mod_mail != null) {
                        items.addView(propView(context, R.string.userprofile_hasmodmail,
                                user.has_mod_mail ? R.string.general_true : R.string.general_false, false));
                    }

                    if (user.is_friend) {
                        items.addView(
                                propView(context, R.string.userprofile_isfriend, R.string.general_true, false));
                    }

                    if (user.is_gold) {
                        items.addView(
                                propView(context, R.string.userprofile_isgold, R.string.general_true, false));
                    }

                    if (user.is_mod) {
                        items.addView(propView(context, R.string.userprofile_moderator, R.string.general_true,
                                false));
                    }

                    final Button commentsButton = new Button(context);
                    commentsButton.setText(R.string.userprofile_viewcomments);
                    commentsButton.setOnClickListener(new View.OnClickListener() {
                        public void onClick(View v) {
                            final Intent intent = new Intent(context, CommentListingActivity.class);
                            intent.setData(Uri.parse(Constants.Reddit
                                    .getUri("/user/" + username + "/comments.json").toString()));
                            startActivity(intent);
                            dismiss();
                        }
                    });
                    items.addView(commentsButton);
                    // TODO use margin? or framelayout? scale padding dp
                    // TODO change button color
                    commentsButton.setPadding(20, 20, 20, 20);

                    final Button postsButton = new Button(context);
                    postsButton.setText(R.string.userprofile_viewposts);
                    postsButton.setOnClickListener(new View.OnClickListener() {
                        public void onClick(View v) {
                            final Intent intent = new Intent(context, PostListingActivity.class);
                            intent.putExtra("subreddit", new RedditSubreddit("/user/" + username + "/submitted",
                                    "Submitted by " + username, false));
                            startActivity(intent);
                            dismiss();
                        }
                    });
                    items.addView(postsButton);
                    // TODO use margin? or framelayout? scale padding dp
                    postsButton.setPadding(20, 20, 20, 20);

                }
            });
        }

        @Override
        protected void onCallbackException(Throwable t) {
            BugReportActivity.handleGlobalError(context, t);
        }

        @Override
        protected void onFailure(final RequestFailureType type, final Throwable t, final StatusLine status,
                final String readableMessage) {

            new Handler(Looper.getMainLooper()).post(new Runnable() {
                public void run() {

                    if (!active)
                        return;

                    loadingView.setDone(R.string.download_failed);

                    final RRError error = General.getGeneralErrorForFailure(context, type, t, status);
                    items.addView(new ErrorView(getSupportActivity(), error));
                }
            });
        }

        @Override
        protected void onFailure(final APIFailureType type) {

            new Handler(Looper.getMainLooper()).post(new Runnable() {
                public void run() {

                    if (!active)
                        return;

                    loadingView.setDone(R.string.download_failed);

                    final RRError error = General.getGeneralErrorForFailure(context, type);
                    items.addView(new ErrorView(getSupportActivity(), error));
                }
            });
        }

    }, RedditAccountManager.getInstance(context).getDefaultAccount(), CacheRequest.DownloadType.FORCE, true,
            context);
}

From source file:mobisocial.socialkit.musubi.multiplayer.TurnBasedApp.java

public TurnBasedApp(Musubi musubi, DbObj objContext) {
    if (musubi == null || objContext == null) {
        throw new NullPointerException("ObjContext is null");
    }//from ww  w .j ava2 s  .  c o  m

    mMusubi = musubi;
    mObjContext = objContext;
    mDbFeed = mObjContext.getSubfeed();
    mObserver = new TurnObserver(new Handler(mMusubi.getContext().getMainLooper()));
    mLocalMember = mDbFeed.getLocalUser().getId();
}

From source file:com.jerrellmardis.amphitheatre.task.DownloadTaskHelper.java

public static void traverseSmbFiles(SmbFile root, NtlmPasswordAuthentication auth)
        throws SmbException, MalformedURLException {
    int fileCount = 0;
    boolean video_folder = false;
    final Video v = new Video();
    Handler h = new Handler(Looper.getMainLooper()) {
        @Override/*from   w  ww.j av  a2  s.c  o  m*/
        public void handleMessage(Message msg) {
            //                            super.handleMessage(msg);
            Video vid = (Video) msg.getData().getSerializable("VIDEO");
            Log.d(TAG, "Handle " + msg.getData().getInt("WHEN") + " " + vid.getName());
            updateSingleVideo(vid, null);
        }

    };

    for (SmbFile f : root.listFiles()) {
        if (f.getParent().contains("Entertainment Media")) {
            //                Log.d(TAG, "Discovered "+f.getPath()+" "+f.isDirectory());
        }
        if (f.isDirectory()) {
            try {
                //TODO Port VOB folder support to USB and internal storage
                SmbFile[] directoryContents = f.listFiles();
                //                    Log.d(TAG, "Going into directory "+f.getPath());
                //If this works, then we can explore
                //Let's do some quick name checking to for time savings
                if (f.getName().contains("Entertainment Media")) {
                    //                        Log.d(TAG, Arrays.asList(f.listFiles()).toString());
                }
                if (!f.getName().contains("iTunes") && !f.getName().contains("Digi Pix")
                        && !f.getName().contains("AppData") && !f.getName().startsWith(".")
                        && !f.getName().contains("Avid") && !f.getName().contains("Spotify")
                        && !f.getName().contains("audacity_temp") && !f.getName().contains("Media_previews")
                        && !f.getName().contains("GFX_previews")
                        && !f.getName().contains("Samsung Install Files") && !f.getName().contains("AE Renders")
                        && !f.getName().contains("LocalData") && !f.getName().contains("$RECYCLE")
                        && !f.getName().contains("Encore DVD") && !f.getName().contains("16 GB Photo card")
                        && !f.getName().contains("Ignore") && !f.getName().contains("Documents") //TEMP
                        && !f.getName().contains("Downloads") //TEMP
                        && !f.getName().contains("TypeGEMs") //TEMP
                        && !f.getName().contains("KofC7032Web") //TEMP
                        && !f.getName().contains("hype mobile docs") //TEMP
                        && !f.getName().contains("Thrive Music Video") //TEMP
                        /*&& f.getPath().contains("Entertainment") //TEMP*/
                        && !f.getName().contains("Preview Files")) {
                    Log.d(TAG, "Check " + f.getPath());
                    traverseSmbFiles(f, auth);
                } else {
                    //                        Log.d(TAG, "Don't check " + f.getPath());
                }
            } catch (Exception e) {
                //This folder isn't accessible
                Log.d(TAG, "Inaccessible: " + f.getName() + " " + e.getMessage());
                //This will save us time in the traversal
            }
        } else/* if(f.getPath().contains("Films"))*/ { //TEMP
            //Is this something we want to add?
            //                Log.d(TAG, "Non-directory "+f.getPath());
            if (VideoUtils.isVideoFile(f.getPath())) {
                Log.d(TAG, f.getName() + " is a video");
                //Perhaps. Let's do some checking.
                /* VOB check
                If the files are in a structure like:
                { Movie Name } -> VIDEO_TS -> VTS_nn_n.vob
                        
                Then use the movie name as the source, and each vob url will
                be added in a comma-separated list to the video url string
                */

                if (f.getPath().contains("VIDEO_TS")) {
                    Log.d(TAG, "Special case for " + f.getPath());
                    //We have a special case!
                    String grandparentPath = f.getPath().substring(0, f.getPath().indexOf("VIDEO_TS"));
                    SmbFile grandparent = new SmbFile(grandparentPath, auth);

                    //Let's delete this video and all like it from our video database
                    //TODO Makes more sense to not delete and replace a video, just to update in place
                    //                        Log.d(TAG, "Purge where video_url like "+"%" + grandparent.getPath().replace("'", "\'") + "%");
                    List<Video> videos = Select.from(Video.class).where(Condition.prop("video_url")
                            .like("%" + grandparent.getPath().replace("'", "\'") + "%")).list();
                    //                        Log.d(TAG, "Purging "+videos.size()+" item(s)");
                    for (Video vx : videos) {
                        //                            Log.d(TAG, "Deleting "+vx.getVideoUrl());
                        vx.delete();
                    }

                    v.setName(grandparent.getName().replace("/", "").replace("_", " ") + ".avi"); //FIXME VOB currently not supported
                    v.setSource(FileSource.SMB);
                    v.setIsMatched(true); //Kind of a lie, but we know it's a thing!
                    //Get all the video files
                    ArrayList<String> urls = new ArrayList<>();
                    for (SmbFile f2 : grandparent.listFiles()) {
                        for (SmbFile f3 : f2.listFiles()) {
                            if (VideoUtils.isVideoFile(f3.getPath())) {
                                //Presumably in order
                                urls.add(f3.getPath());
                            }
                        }
                    }
                    //                        Log.d(TAG, urls.toString()); //This works well
                    v.setVideoUrl(urls);
                    video_folder = true;
                } else {
                    //Add the video like normal
                    //Let's delete this video and all like it from our video database
                    List<Video> videos = Select.from(Video.class)
                            .where(Condition.prop("video_url").like("%" + f.getPath().replace("'", "''") + "%"))
                            .list();
                    //                        Log.d(TAG, "Purging "+videos.size()+" item(s)");
                    for (Video vx : videos) {
                        //                            Log.d(TAG, "Deleting "+vx.getVideoUrl());
                        vx.delete();
                    }

                    v.setName(f.getName());
                    v.setSource(FileSource.SMB);
                    v.setVideoUrl(f.getPath());

                    fileCount++;
                    //Send a request to update metadata every second, to prevent as many 429 errors and memory exceptions
                    Message m = new Message();
                    Bundle mBundle = new Bundle();
                    mBundle.putSerializable("VIDEO", v.clone());
                    mBundle.putInt("WHEN", (int) (1000 * fileCount + Math.round(Math.random() * 100)));
                    m.setData(mBundle);
                    //                        h.sendEmptyMessageDelayed(1000 * fileCount, 1000 * fileCount);
                    h.sendMessageDelayed(m, 1000 * fileCount);
                    Log.d(TAG, "Queued " + mBundle.getInt("WHEN") + "  -  " + v.getName());
                    v.save(); //Need to save here, otherwise purging won't work as expected
                }

                //                    Log.d(TAG, v.toString());

                //                    return;
            }
            //Ignore otherwise
        }
    }
    //Let's do VOB video
    if (video_folder) {
        //            Log.d(TAG, "Done rooting through "+root.getPath());
        Log.d(TAG, "Created info for VOB " + v.toString());
        fileCount++;
        //Send a request to update metadata every second, to prevent as many 429 errors and memory exceptions
        Message m = new Message();
        Bundle mBundle = new Bundle();
        mBundle.putSerializable("VIDEO", v.clone());
        m.setData(mBundle);
        //                        h.sendEmptyMessageDelayed(1000 * fileCount, 1000 * fileCount);
        h.sendMessageDelayed(m, 1000 * fileCount);
        Log.d(TAG, "Queued " + 1000 * fileCount + "  -  " + v.getName());
        v.save(); //Need to save here, otherwise purging won't work as expected
    }
}

From source file:org.quantumbadger.redreader.common.General.java

public static void quickToast(final Context context, final String text, final int duration) {
    new Handler(Looper.getMainLooper()).post(new Runnable() {
        public void run() {
            Toast.makeText(context, text, duration).show();
        }//from  ww  w. j  a v a 2s . co m
    });
}

From source file:com.vk.sdk.payments.VKPaymentsServerSender.java

private VKPaymentsServerSender(@NonNull Context ctx) {
    mAppCtx = ctx;/*  w w w.  j a v a2 s .co  m*/

    mCheckUserInstallAnswer = restoreAnswer(ctx);

    HandlerThread handlerThread = new HandlerThread(getClass().getName());
    handlerThread.start();
    mHandler = new Handler(handlerThread.getLooper());

    // !!! WARNING !!! this for wait reference url from vk client
    mHandler.post(new Runnable() {
        @Override
        public void run() {
            try {
                Thread.sleep(1000); // time for wait reference url
            } catch (Exception e) {
                // nothing
            }
        }
    });
}

From source file:com.ryan.ryanreader.common.General.java

public static void quickToast(final Context context, final String text) {
    new Handler(Looper.getMainLooper()).post(new Runnable() {
        public void run() {
            Toast.makeText(context, text, Toast.LENGTH_LONG).show();
        }//from   w  w w  . j ava 2s. c o  m
    });
}

From source file:com.cloudant.todo.TasksModel.java

public TasksModel(Context context) {

    this.mContext = context;

    // Set up our tasks datastore within its own folder in the applications
    // data directory.
    File path = this.mContext.getApplicationContext().getDir(DATASTORE_MANGER_DIR, Context.MODE_PRIVATE);
    DatastoreManager manager = new DatastoreManager(path.getAbsolutePath());
    try {//  w ww. ja  v a2s.  c  om
        this.mDatastore = manager.openDatastore(TASKS_DATASTORE_NAME);
    } catch (DatastoreNotCreatedException dnce) {
        Log.e(LOG_TAG, "Unable to open Datastore", dnce);
    }

    Log.d(LOG_TAG, "Set up database at " + path.getAbsolutePath());

    // Set up the replicator objects from the app's settings.
    try {
        this.reloadReplicationSettings();
    } catch (URISyntaxException e) {
        Log.e(LOG_TAG, "Unable to construct remote URI from configuration", e);
    }

    // Allow us to switch code called by the ReplicationListener into
    // the main thread so the UI can update safely.
    this.mHandler = new Handler(Looper.getMainLooper());

    Log.d(LOG_TAG, "TasksModel set up " + path.getAbsolutePath());
}

From source file:org.peercast.core.PeerCastServiceController.java

/**
 * PeerCastService???/*from ww w  .  j  a  va  2 s  . co  m*/
 * 
 *<ul>
 * <li>
 *    MSG_GET_APPLICATION_PROPERTIES = 0x00;<br>
 *   ????<br>
 *   :  getInt("port") ??=0<br><br>
 * <li>    
 *  MSG_GET_CHANNELS = 0x01;<br>
 *  ??????<br>
 *   :  nativeGetChannel()?<br>
 *   : Channel.java <br><br>
 * <li>    
 *  MSG_GET_STATS = 0x02;<br>
 *  ?????<br>
  *   :   nativeGetStats()?<br>
  *   : Stats.java <br><br>
 *
 * @param what MSG_ ??
 * @param listener ??Bundle????
 */
public void sendCommand(int what, final OnServiceResultListener listener) {
    if (serverMessenger == null)
        new IllegalStateException("service not connected.");
    Message msg = Message.obtain(null, what);
    msg.replyTo = new Messenger(new Handler(new Handler.Callback() {
        //Handler???
        @Override
        public boolean handleMessage(Message msg) {
            listener.onServiceResult(msg.getData());
            return true;
        }
    }));
    try {
        serverMessenger.send(msg);
    } catch (RemoteException e) {
        Log.e(TAG, "what=" + what, e);
    }
}

From source file:com.frostwire.android.gui.adapters.menu.FileListAdapter.java

@Override
protected MenuAdapter getMenuAdapter(View view) {
    Handler h = new Handler(Looper.getMainLooper());
    h.sendEmptyMessage(5011105);/*from w w w .  j av a  2 s.co  m*/

    Context context = getContext();

    List<MenuAction> items = new ArrayList<>();

    // due to long click generic handle
    FileDescriptor fd = null;

    if (view.getTag() instanceof FileDescriptorItem) {
        FileDescriptorItem item = (FileDescriptorItem) view.getTag();
        fd = item.fd;
    } else if (view.getTag() instanceof FileDescriptor) {
        fd = (FileDescriptor) view.getTag();
    }

    if (checkIfNotExists(fd)) {
        return null;
    }

    List<FileDescriptor> checked = convertItems(getChecked());
    ensureCorrectMimeType(fd);
    boolean canOpenFile = fd.mime != null
            && (fd.mime.contains("audio") || fd.mime.contains("bittorrent") || fd.filePath != null);
    int numChecked = checked.size();

    boolean showSingleOptions = showSingleOptions(checked, fd);

    if (TransferManager.canSeedFromMyFilesTempHACK()) {
        if (showSingleOptions) {
            items.add(new SeedAction(context, fd));
        } else {
            items.add(new SeedAction(context, checked));
        }
    }

    if (showSingleOptions) {
        if (canOpenFile) {
            items.add(new OpenMenuAction(context, fd.filePath, fd.mime));
        }

        if ((fd.fileType == Constants.FILE_TYPE_RINGTONES || fd.fileType == Constants.FILE_TYPE_AUDIO)
                && numChecked <= 1) {
            items.add(new SetAsRingtoneMenuAction(context, fd));
        }

        if (fd.fileType == Constants.FILE_TYPE_PICTURES && numChecked <= 1) {
            items.add(new SetAsWallpaperMenuAction(context, fd));
        }

        if (fd.fileType != Constants.FILE_TYPE_APPLICATIONS && numChecked <= 1) {
            items.add(new RenameFileMenuAction(context, this, fd));
        }

        if (fd.mime != null && fd.mime.equals(Constants.MIME_TYPE_BITTORRENT) && numChecked <= 1) {
            items.add(new CopyToClipboardMenuAction(context, R.drawable.contextmenu_icon_magnet,
                    R.string.transfers_context_menu_copy_magnet,
                    R.string.transfers_context_menu_copy_magnet_copied,
                    new MagnetUriBuilder(fd.filePath).getMagnet()));

            items.add(new CopyToClipboardMenuAction(context, R.drawable.contextmenu_icon_copy,
                    R.string.transfers_context_menu_copy_infohash,
                    R.string.transfers_context_menu_copy_infohash_copied, new InfoHashBuilder(fd.filePath)));
        }
    }

    List<FileDescriptor> list = checked;
    if (list.size() == 0) {
        list = Arrays.asList(fd);
    }

    if (fd.fileType == Constants.FILE_TYPE_AUDIO) {
        items.add(new AddToPlaylistMenuAction(context, list));
    }

    if (fd.fileType != Constants.FILE_TYPE_APPLICATIONS) {
        items.add(new SendFileMenuAction(context, fd));
        items.add(new DeleteFileMenuAction(context, this, list));
    }

    return new MenuAdapter(context, fd.title, items);
}

From source file:edu.rowan.app.fragments.FoodRatingFragment.java

@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    mainThreadHandler = new Handler(getActivity().getApplicationContext().getMainLooper());
}