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:me.disconnect.mobile.billing.IabHelper.java

/**
 * Asynchronous wrapper for inventory query. This will perform an inventory
 * query as described in {@link #queryInventory}, but will do so asynchronously
 * and call back the specified listener upon completion. This method is safe to
 * call from a UI thread.//from w  ww  .j av  a 2 s . com
 *
 * @param querySkuDetails as in {@link #queryInventory}
 * @param moreSkus as in {@link #queryInventory}
 * @param listener The listener to notify when the refresh operation completes.
 */
public void queryInventoryAsync(final boolean querySkuDetails, final List<String> moreSkus,
        final QueryInventoryFinishedListener listener) {
    final Handler handler = new Handler();
    checkNotDisposed();
    checkSetupDone("queryInventory");
    flagStartAsync("refresh inventory");
    (new Thread(new Runnable() {
        public void run() {
            IabResult result = new IabResult(BILLING_RESPONSE_RESULT_OK, "Inventory refresh successful.");
            Inventory inv = null;
            try {
                inv = queryInventory(querySkuDetails, moreSkus);
            } catch (IabException ex) {
                result = ex.getResult();
            } catch (RuntimeException e) {
                // I added this catch because the security.verify() method can throw a runtime
                // exception with the message "Hash algorithm not found". -MG
                if (listener != null)
                    listener.onQueryInventoryFinished(new IabResult(BILLING_RESPONSE_RESULT_ERROR, null), null);
            }

            flagEndAsync();

            final IabResult result_f = result;
            final Inventory inv_f = inv;
            if (!mDisposed && listener != null) {
                handler.post(new Runnable() {
                    public void run() {
                        listener.onQueryInventoryFinished(result_f, inv_f);
                    }
                });
            }
        }
    })).start();
}

From source file:org.yaaic.fragment.ConversationFragment.java

/**
 * On activity result//from  w w w .  ja v  a  2 s.c om
 */
@Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
    if (resultCode != Activity.RESULT_OK) {
        // ignore other result codes
        return;
    }

    switch (requestCode) {
    case REQUEST_CODE_JOIN:
        joinChannelBuffer = data.getExtras().getString("channel");
        break;
    case REQUEST_CODE_USERS:
        Intent intent = new Intent(getActivity(), UserActivity.class);
        intent.putExtra(Extra.USER, data.getStringExtra(Extra.USER));
        startActivityForResult(intent, REQUEST_CODE_USER);
        break;
    case REQUEST_CODE_NICK_COMPLETION:
        insertNickCompletion(input, data.getExtras().getString(Extra.USER));
        break;
    case REQUEST_CODE_USER:
        final int actionId = data.getExtras().getInt(Extra.ACTION);
        final String nickname = data.getExtras().getString(Extra.USER);
        final IRCConnection connection = binder.getService().getConnection(server.getId());
        final String conversation = server.getSelectedConversation();
        final Handler handler = new Handler();

        // XXX: Implement me - The action should be handled after onResume()
        //                     to catch the broadcasts... now we just wait a second
        // Yes .. that's very ugly - we need some kind of queue that is handled after onResume()

        new Thread() {
            @Override
            public void run() {
                try {
                    Thread.sleep(1000);
                } catch (InterruptedException e) {
                    // Do nothing
                }

                String nicknameWithoutPrefix = nickname;

                while (nicknameWithoutPrefix.startsWith("@") || nicknameWithoutPrefix.startsWith("+")
                        || nicknameWithoutPrefix.startsWith(".") || nicknameWithoutPrefix.startsWith("%")) {
                    // Strip prefix(es) now
                    nicknameWithoutPrefix = nicknameWithoutPrefix.substring(1);
                }

                switch (actionId) {
                case User.ACTION_REPLY:
                    final String replyText = nicknameWithoutPrefix + ": ";
                    handler.post(new Runnable() {
                        @Override
                        public void run() {
                            input.setText(replyText);
                            input.setSelection(replyText.length());
                        }
                    });
                    break;
                case User.ACTION_QUERY:
                    Conversation query = server.getConversation(nicknameWithoutPrefix);
                    if (query == null) {
                        // Open a query if there's none yet
                        query = new Query(nicknameWithoutPrefix);
                        query.setHistorySize(binder.getService().getSettings().getHistorySize());
                        server.addConversation(query);

                        Intent intent = Broadcast.createConversationIntent(Broadcast.CONVERSATION_NEW,
                                server.getId(), nicknameWithoutPrefix);
                        binder.getService().sendBroadcast(intent);
                    }
                    break;
                case User.ACTION_OP:
                    connection.op(conversation, nicknameWithoutPrefix);
                    break;
                case User.ACTION_DEOP:
                    connection.deOp(conversation, nicknameWithoutPrefix);
                    break;
                case User.ACTION_VOICE:
                    connection.voice(conversation, nicknameWithoutPrefix);
                    break;
                case User.ACTION_DEVOICE:
                    connection.deVoice(conversation, nicknameWithoutPrefix);
                    break;
                case User.ACTION_KICK:
                    connection.kick(conversation, nicknameWithoutPrefix);
                    break;
                case User.ACTION_BAN:
                    connection.ban(conversation, nicknameWithoutPrefix + "!*@*");
                    break;
                }
            }
        }.start();

        break;
    }
}

From source file:org.cryptsecure.Communicator.java

/**
 * Live update or notify.// ww w  . ja  va 2  s.  c o m
 * 
 * @param context
 *            the context
 * @param newItem
 *            the new item
 */
public static void liveUpdateOrNotify(final Context context, final ConversationItem newItem) {
    Log.d("communicator", "@@@@ liveUpdateOrNotify() POSSIBLY CREATE NOTIFICATION #1 from=" + newItem.from
            + ", part=" + newItem.part + ", multipartid=" + newItem.multipartid);

    // Consider localgroupid as an alternative "from"
    int uidFromTmp = newItem.from;
    int localgroupid = Utility.parseInt(newItem.groupId, -1);
    if (localgroupid != -1) {
        Log.d("communicator", "@@@@ liveUpdateOrNotify() Conversation.getHostUid()=" + Conversation.getHostUid()
                + ", localgroupid=" + localgroupid);
        uidFromTmp = localgroupid;
    }
    final int uidFrom = uidFromTmp;

    final Handler mUIHandler = new Handler(Looper.getMainLooper());
    mUIHandler.post(new Thread() {
        @Override
        public void run() {
            super.run();
            final Handler handler = new Handler();
            handler.postDelayed(new Runnable() {
                public void run() {
                    if (Conversation.isVisible() || Main.isVisible()) {
                        // Possibly there are new users added and we need to
                        // prompt!
                        Setup.possiblyPromptAutoAddedUser(context);
                    }

                    // Live - update if possible,
                    // otherwise create notification!
                    if (Conversation.isVisible() && Conversation.getHostUid() == uidFrom) {
                        // The conversation is currently
                        // open, try to update this
                        // right away!
                        //
                        // ATTENTION: If not scrolled down then send an
                        // additional toast!
                        if (!Conversation.scrolledDown && !newItem.isKey && newItem.readyToProcess()) {
                            if (newItem.transport == DB.TRANSPORT_INTERNET) {
                                Utility.showToastShortAsync(context,
                                        "New message " + newItem.localid + " received.");
                            } else {
                                Utility.showToastShortAsync(context,
                                        "New SMS " + newItem.localid + " received.");
                            }
                        }

                        Log.d("communicator",
                                "@@@@ liveUpdateOrNotify() POSSIBLY CREATE NOTIFICATION #A , part="
                                        + newItem.part + ", newItem.multipartid=" + newItem.multipartid);

                        if (!newItem.multipartid.equals(DB.NO_MULTIPART_ID)) {
                            // This IS a multipart message
                            Conversation.hideMultiparts(context, newItem.multipartid);
                        }
                        Conversation.getInstance().updateConversationlist(context);
                        if (!newItem.multipartid.equals(DB.NO_MULTIPART_ID)) {
                            Conversation
                                    .setMultipartProgress(
                                            context, newItem.multipartid, DB.getPercentReceivedComplete(context,
                                                    newItem.multipartid, newItem.from, newItem.parts),
                                            newItem.text);
                        }
                    } else {
                        // The conversation is NOT
                        // currently
                        // open, we need a new
                        // notification
                        Log.d("communicator",
                                "@@@@ liveUpdateOrNotify() POSSIBLY CREATE NOTIFICATION #2 " + newItem.from);
                        if (!newItem.isKey && newItem.readyToProcess()) {
                            Log.d("communicator", "@@@@ liveUpdateOrNotify() POSSIBLY CREATE NOTIFICATION #3 "
                                    + newItem.from);
                            createNotification(context, newItem, uidFrom);
                        }
                        if (Conversation.isAlive() && Conversation.getHostUid() == uidFrom) {
                            // Still update because conversation is in
                            // memory!
                            // Also possibly scroll down: If the user
                            // unlocks the phone,
                            // and scrolledDown was true, then he expects to
                            // see the
                            // last/newest message!
                            if (!newItem.multipartid.equals(DB.NO_MULTIPART_ID)) {
                                // This IS a multipart message
                                Conversation.hideMultiparts(context, newItem.multipartid);
                            }
                            Conversation.getInstance().updateConversationlist(context);
                            if (!newItem.multipartid.equals(DB.NO_MULTIPART_ID)) {
                                Conversation.setMultipartProgress(
                                        context, newItem.multipartid, DB.getPercentReceivedComplete(context,
                                                newItem.multipartid, newItem.from, newItem.parts),
                                        newItem.text);
                            }

                        }
                    }

                    if (Main.isVisible()) {
                        Main.getInstance().rebuildUserlist(context, false);
                    }
                }
            }, 200);
        }
    });
}

From source file:ir.occc.android.irc.activity.ConversationActivity.java

/**
 * On activity result/*from ww  w .j  av a 2  s .  c  o  m*/
 */
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
    if (resultCode != RESULT_OK) {
        // ignore other result codes
        return;
    }

    switch (requestCode) {
    case REQUEST_CODE_SPEECH:
        ArrayList<String> matches = data.getStringArrayListExtra(RecognizerIntent.EXTRA_RESULTS);
        if (matches.size() > 0) {
            ((EditText) findViewById(R.id.input)).setText(matches.get(0));
        }
        break;
    case REQUEST_CODE_JOIN:
        joinChannelBuffer = data.getExtras().getString("channel");
        break;
    case REQUEST_CODE_USERS:
        Intent intent = new Intent(this, UserActivity.class);
        intent.putExtra(Extra.USER, data.getStringExtra(Extra.USER));
        startActivityForResult(intent, REQUEST_CODE_USER);
        break;
    case REQUEST_CODE_NICK_COMPLETION:
        insertNickCompletion((EditText) findViewById(R.id.input), data.getExtras().getString(Extra.USER));
        break;
    case REQUEST_CODE_USER:
        final int actionId = data.getExtras().getInt(Extra.ACTION);
        final String nickname = data.getExtras().getString(Extra.USER);
        final IRCConnection connection = binder.getService().getConnection(server.getId());
        final String conversation = server.getSelectedConversation();
        final Handler handler = new Handler();

        // XXX: Implement me - The action should be handled after onResume()
        //                     to catch the broadcasts... now we just wait a second
        // Yes .. that's very ugly - we need some kind of queue that is handled after onResume()

        new Thread() {
            @Override
            public void run() {
                try {
                    Thread.sleep(1000);
                } catch (InterruptedException e) {
                    // Do nothing
                }

                String nicknameWithoutPrefix = nickname;

                while (nicknameWithoutPrefix.startsWith("@") || nicknameWithoutPrefix.startsWith("+")
                        || nicknameWithoutPrefix.startsWith(".") || nicknameWithoutPrefix.startsWith("%")) {
                    // Strip prefix(es) now
                    nicknameWithoutPrefix = nicknameWithoutPrefix.substring(1);
                }

                switch (actionId) {
                case User.ACTION_REPLY:
                    final String replyText = nicknameWithoutPrefix + ": ";
                    handler.post(new Runnable() {
                        @Override
                        public void run() {
                            EditText input = (EditText) findViewById(R.id.input);
                            input.setText(replyText);
                            input.setSelection(replyText.length());
                        }
                    });
                    break;
                case User.ACTION_QUERY:
                    Conversation query = server.getConversation(nicknameWithoutPrefix);
                    if (query == null) {
                        // Open a query if there's none yet
                        query = new Query(nicknameWithoutPrefix);
                        query.setHistorySize(binder.getService().getSettings().getHistorySize());
                        server.addConversation(query);

                        Intent intent = Broadcast.createConversationIntent(Broadcast.CONVERSATION_NEW,
                                server.getId(), nicknameWithoutPrefix);
                        binder.getService().sendBroadcast(intent);
                    }
                    break;
                case User.ACTION_OP:
                    connection.op(conversation, nicknameWithoutPrefix);
                    break;
                case User.ACTION_DEOP:
                    connection.deOp(conversation, nicknameWithoutPrefix);
                    break;
                case User.ACTION_VOICE:
                    connection.voice(conversation, nicknameWithoutPrefix);
                    break;
                case User.ACTION_DEVOICE:
                    connection.deVoice(conversation, nicknameWithoutPrefix);
                    break;
                case User.ACTION_KICK:
                    connection.kick(conversation, nicknameWithoutPrefix);
                    break;
                case User.ACTION_BAN:
                    connection.ban(conversation, nicknameWithoutPrefix + "!*@*");
                    break;
                }
            }
        }.start();

        break;
    }
}

From source file:com.kaltura.playersdk.PlayerViewController.java

private void setupPlayerViewController(final Context context) {
    mPowerManager = (PowerManager) context.getSystemService(context.POWER_SERVICE);
    // Get a handler that can be used to post to the main thread
    Handler mainHandler = new Handler(context.getMainLooper());
    Runnable myRunnable = new Runnable() {
        @Override/*from   ww w. j  a  va  2s  .co m*/
        public void run() {
            if (!ChromecastHandler.initialized)
                ChromecastHandler.initialize(context, new OnCastDeviceChangeListener() {

                    @Override
                    public void onCastDeviceChange(CastDevice oldDevice, CastDevice newDevice) {
                        if (ChromecastHandler.selectedDevice != null) {
                            notifyKPlayer("trigger", new String[] { "chromecastDeviceConnected" });
                        } else {
                            notifyKPlayer("trigger", new String[] { "chromecastDeviceDisConnected" });
                        }
                        //                                    createPlayerInstance();
                    }
                }, new OnCastRouteDetectedListener() {
                    @Override
                    public void onCastRouteDetected() {
                        setChromecastVisiblity();
                    }
                });
        }
    };
    mainHandler.post(myRunnable);
}

From source file:org.matrix.console.activity.RoomActivity.java

/**
 * Send a list of images from their URIs
 * @param mediaUris the media URIs//from  w  ww.jav a 2s .co m
 */
private void sendMedias(final ArrayList<Uri> mediaUris) {

    final View progressBackground = findViewById(R.id.medias_processing_progress_background);
    final View progress = findViewById(R.id.medias_processing_progress);

    progressBackground.setVisibility(View.VISIBLE);
    progress.setVisibility(View.VISIBLE);

    final HandlerThread handlerThread = new HandlerThread("MediasEncodingThread");
    handlerThread.start();

    final android.os.Handler handler = new android.os.Handler(handlerThread.getLooper());

    Runnable r = new Runnable() {
        @Override
        public void run() {
            handler.post(new Runnable() {
                public void run() {
                    final int mediaCount = mediaUris.size();

                    for (Uri anUri : mediaUris) {
                        // crash from Google Analytics : null URI on a nexus 5
                        if (null != anUri) {
                            final Uri mediaUri = anUri;
                            String filename = null;

                            if (mediaUri.toString().startsWith("content://")) {
                                Cursor cursor = null;
                                try {
                                    cursor = RoomActivity.this.getContentResolver().query(mediaUri, null, null,
                                            null, null);
                                    if (cursor != null && cursor.moveToFirst()) {
                                        filename = cursor
                                                .getString(cursor.getColumnIndex(OpenableColumns.DISPLAY_NAME));
                                    }
                                } catch (Exception e) {
                                    Log.e(LOG_TAG, "cursor.getString " + e.getMessage());
                                } finally {
                                    if (null != cursor) {
                                        cursor.close();
                                    }
                                }

                                if (TextUtils.isEmpty(filename)) {
                                    List uriPath = mediaUri.getPathSegments();
                                    filename = (String) uriPath.get(uriPath.size() - 1);
                                }
                            } else if (mediaUri.toString().startsWith("file://")) {
                                // try to retrieve the filename from the file url.
                                try {
                                    filename = anUri.getLastPathSegment();
                                } catch (Exception e) {
                                }

                                if (TextUtils.isEmpty(filename)) {
                                    filename = null;
                                }
                            }

                            final String fFilename = filename;

                            ResourceUtils.Resource resource = ResourceUtils.openResource(RoomActivity.this,
                                    mediaUri);

                            if (null == resource) {
                                RoomActivity.this.runOnUiThread(new Runnable() {
                                    @Override
                                    public void run() {
                                        handlerThread.quit();
                                        progressBackground.setVisibility(View.GONE);
                                        progress.setVisibility(View.GONE);

                                        Toast.makeText(RoomActivity.this,
                                                getString(R.string.message_failed_to_upload), Toast.LENGTH_LONG)
                                                .show();
                                    }

                                    ;
                                });

                                return;
                            }

                            // save the file in the filesystem
                            String mediaUrl = mMediasCache.saveMedia(resource.contentStream, null,
                                    resource.mimeType);
                            String mimeType = resource.mimeType;
                            Boolean isManaged = false;

                            if ((null != resource.mimeType) && resource.mimeType.startsWith("image/")) {
                                // manage except if there is an error
                                isManaged = true;

                                // try to retrieve the gallery thumbnail
                                // if the image comes from the gallery..
                                Bitmap thumbnailBitmap = null;

                                try {
                                    ContentResolver resolver = getContentResolver();

                                    List uriPath = mediaUri.getPathSegments();
                                    long imageId = -1;
                                    String lastSegment = (String) uriPath.get(uriPath.size() - 1);

                                    // > Kitkat
                                    if (lastSegment.startsWith("image:")) {
                                        lastSegment = lastSegment.substring("image:".length());
                                    }

                                    imageId = Long.parseLong(lastSegment);

                                    thumbnailBitmap = MediaStore.Images.Thumbnails.getThumbnail(resolver,
                                            imageId, MediaStore.Images.Thumbnails.MINI_KIND, null);
                                } catch (Exception e) {
                                    Log.e(LOG_TAG,
                                            "MediaStore.Images.Thumbnails.getThumbnail " + e.getMessage());
                                }

                                double thumbnailWidth = mConsoleMessageListFragment.getMaxThumbnailWith();
                                double thumbnailHeight = mConsoleMessageListFragment.getMaxThumbnailHeight();

                                // no thumbnail has been found or the mimetype is unknown
                                if ((null == thumbnailBitmap) || (thumbnailBitmap.getHeight() > thumbnailHeight)
                                        || (thumbnailBitmap.getWidth() > thumbnailWidth)) {
                                    // need to decompress the high res image
                                    BitmapFactory.Options options = new BitmapFactory.Options();
                                    options.inPreferredConfig = Bitmap.Config.ARGB_8888;
                                    resource = ResourceUtils.openResource(RoomActivity.this, mediaUri);

                                    // get the full size bitmap
                                    Bitmap fullSizeBitmap = null;

                                    if (null == thumbnailBitmap) {
                                        fullSizeBitmap = BitmapFactory.decodeStream(resource.contentStream,
                                                null, options);
                                    }

                                    if ((fullSizeBitmap != null) || (thumbnailBitmap != null)) {
                                        double imageWidth;
                                        double imageHeight;

                                        if (null == thumbnailBitmap) {
                                            imageWidth = fullSizeBitmap.getWidth();
                                            imageHeight = fullSizeBitmap.getHeight();
                                        } else {
                                            imageWidth = thumbnailBitmap.getWidth();
                                            imageHeight = thumbnailBitmap.getHeight();
                                        }

                                        if (imageWidth > imageHeight) {
                                            thumbnailHeight = thumbnailWidth * imageHeight / imageWidth;
                                        } else {
                                            thumbnailWidth = thumbnailHeight * imageWidth / imageHeight;
                                        }

                                        try {
                                            thumbnailBitmap = Bitmap.createScaledBitmap(
                                                    (null == fullSizeBitmap) ? thumbnailBitmap : fullSizeBitmap,
                                                    (int) thumbnailWidth, (int) thumbnailHeight, false);
                                        } catch (OutOfMemoryError ex) {
                                            Log.e(LOG_TAG, "Bitmap.createScaledBitmap " + ex.getMessage());
                                        }
                                    }

                                    // the valid mimetype is not provided
                                    if ("image/*".equals(mimeType)) {
                                        // make a jpg snapshot.
                                        mimeType = null;
                                    }

                                    // unknown mimetype
                                    if ((null == mimeType) || (mimeType.startsWith("image/"))) {
                                        try {
                                            // try again
                                            if (null == fullSizeBitmap) {
                                                System.gc();
                                                fullSizeBitmap = BitmapFactory
                                                        .decodeStream(resource.contentStream, null, options);
                                            }

                                            if (null != fullSizeBitmap) {
                                                Uri uri = Uri.parse(mediaUrl);

                                                if (null == mimeType) {
                                                    // the images are save in jpeg format
                                                    mimeType = "image/jpeg";
                                                }

                                                resource.contentStream.close();
                                                resource = ResourceUtils.openResource(RoomActivity.this,
                                                        mediaUri);

                                                try {
                                                    mMediasCache.saveMedia(resource.contentStream,
                                                            uri.getPath(), mimeType);
                                                } catch (OutOfMemoryError ex) {
                                                    Log.e(LOG_TAG, "mMediasCache.saveMedia" + ex.getMessage());
                                                }

                                            } else {
                                                isManaged = false;
                                            }

                                            resource.contentStream.close();

                                        } catch (Exception e) {
                                            isManaged = false;
                                            Log.e(LOG_TAG, "sendMedias " + e.getMessage());
                                        }
                                    }

                                    // reduce the memory consumption
                                    if (null != fullSizeBitmap) {
                                        fullSizeBitmap.recycle();
                                        System.gc();
                                    }
                                }

                                String thumbnailURL = mMediasCache.saveBitmap(thumbnailBitmap, null);

                                if (null != thumbnailBitmap) {
                                    thumbnailBitmap.recycle();
                                }

                                //
                                if (("image/jpg".equals(mimeType) || "image/jpeg".equals(mimeType))
                                        && (null != mediaUrl)) {

                                    Uri imageUri = Uri.parse(mediaUrl);
                                    // get the exif rotation angle
                                    final int rotationAngle = ImageUtils
                                            .getRotationAngleForBitmap(RoomActivity.this, imageUri);

                                    if (0 != rotationAngle) {
                                        // always apply the rotation to the image
                                        ImageUtils.rotateImage(RoomActivity.this, thumbnailURL, rotationAngle,
                                                mMediasCache);

                                        // the high res media orientation should be not be done on uploading
                                        //ImageUtils.rotateImage(RoomActivity.this, mediaUrl, rotationAngle, mMediasCache))
                                    }
                                }

                                // is the image content valid ?
                                if (isManaged && (null != thumbnailURL)) {

                                    final String fThumbnailURL = thumbnailURL;
                                    final String fMediaUrl = mediaUrl;
                                    final String fMimeType = mimeType;

                                    RoomActivity.this.runOnUiThread(new Runnable() {
                                        @Override
                                        public void run() {
                                            // if there is only one image
                                            if (mediaCount == 1) {
                                                // display an image preview before sending it
                                                mPendingThumbnailUrl = fThumbnailURL;
                                                mPendingMediaUrl = fMediaUrl;
                                                mPendingMimeType = fMimeType;
                                                mPendingFilename = fFilename;

                                                mConsoleMessageListFragment.scrollToBottom();

                                                manageSendMoreButtons();
                                            } else {
                                                mConsoleMessageListFragment.uploadImageContent(fThumbnailURL,
                                                        fMediaUrl, fFilename, fMimeType);
                                            }
                                        }
                                    });
                                }
                            }

                            // default behaviour
                            if ((!isManaged) && (null != mediaUrl)) {
                                final String fMediaUrl = mediaUrl;
                                final String fMimeType = mimeType;

                                RoomActivity.this.runOnUiThread(new Runnable() {
                                    @Override
                                    public void run() {
                                        if ((null != fMimeType) && fMimeType.startsWith("video/")) {
                                            mConsoleMessageListFragment.uploadVideoContent(fMediaUrl, null,
                                                    fMimeType);
                                        } else {
                                            mConsoleMessageListFragment.uploadFileContent(fMediaUrl, fMimeType,
                                                    fFilename);
                                        }
                                    }
                                });
                            }
                        }
                    }

                    RoomActivity.this.runOnUiThread(new Runnable() {
                        @Override
                        public void run() {
                            handlerThread.quit();
                            progressBackground.setVisibility(View.GONE);
                            progress.setVisibility(View.GONE);
                        };
                    });
                }
            });
        }
    };

    Thread t = new Thread(r);
    t.start();
}

From source file:com.ywesee.amiko.MainActivity.java

/**
 * This function creates the main layout, called when splashscreen is over
 */// w  w w. j a v  a2s.c  o  m
public void createMainLayout() {
    //
    setContentView(R.layout.activity_main);

    // Initialize views
    mSuggestView = getLayoutInflater().inflate(R.layout.suggest_view, null);
    mShowView = getLayoutInflater().inflate(R.layout.show_view, null);

    // Sets current view
    mCurrentView = mSuggestView;

    // Setup webviews
    // Add views to viewholder
    mViewHolder = (ViewGroup) findViewById(R.id.main_layout);
    mViewHolder.addView(mSuggestView);
    mViewHolder.addView(mShowView);

    setLayoutTransition();

    mBottomNavigationView = findViewById(R.id.bottom_navigation);
    setupBottomNavigationViewListener();

    // Define and load webview
    ExpertInfoView mExpertInfoView = new ExpertInfoView(this, (WebView) findViewById(R.id.fach_info_view));
    mExpertInfoView.adjustZoom();

    mWebView = mExpertInfoView.getWebView();
    setFindListener(mWebView);
    setupGestureDetector(mWebView);

    // Set up observer to JS messages
    JSInterface jsinterface = mExpertInfoView.getJSInterface();
    jsinterface.addObserver(new Observer() {
        @Override
        public void update(Observable o, Object arg) {
            String s = (String) arg;
            if (s.equals("notify_interaction")) {
                // Remove softkeyboard
                hideSoftKeyboard(100);
                // Take screenshot and start email activity after 500ms (wait for the keyboard to disappear)
                final Handler handler = new Handler();
                handler.postDelayed(new Runnable() {
                    @Override
                    public void run() {
                        sendFeedbackScreenshot(MainActivity.this, 2);
                    }
                }, 500);
            } else {
                if (s.equals("delete_all")) {
                    mMedInteractionBasket.clearBasket();
                } else {
                    mMedInteractionBasket.deleteFromBasket(s);
                }
                //
                // TODO: please comment this "hack"
                //
                Handler mainHandler = new Handler(getMainLooper());
                mainHandler.post(new Runnable() {
                    @Override
                    public void run() {
                        mMedInteractionBasket.updateInteractionsHtml();
                        String html_str = mMedInteractionBasket.getInteractionsHtml();
                        mWebView.loadDataWithBaseURL("file:///android_res/drawable/", html_str, "text/html",
                                "utf-8", null);
                    }
                });
            }
        }
    });

    // Initialize suggestion listview
    mListView = (ListView) findViewById(R.id.suggestView);
    mListView.setClickable(true);

    // Set visibility of views
    mSuggestView.setVisibility(View.VISIBLE);
    mShowView.setVisibility(View.GONE);

    // Setup initial view
    setCurrentView(mSuggestView, false);
    // Reset it
    resetView(false);
}

From source file:com.embeddedlog.LightUpDroid.LightUpPiSync.java

/**
 * Initiates a background thread to check if the LightUpPi server is reachable.
 *
 * @param guiHandler Handler for the activity GUI, for which to send one of the two runnables.
 * @param online Runnable to execute in the Handler if the server is online.
 * @param offline Runnable to execute in the Handler if the server is offline.
 *//*from  w  w  w . j ava2s  .  c  o  m*/
public void startBackgroundServerCheck(final Handler guiHandler, final Runnable online,
        final Runnable offline) {
    // Check for network connectivity
    ConnectivityManager connMgr = (ConnectivityManager) mActivityContext
            .getSystemService(Context.CONNECTIVITY_SERVICE);
    NetworkInfo networkInfo = connMgr.getActiveNetworkInfo();
    if ((networkInfo != null) && networkInfo.isConnected()
            && ((scheduleServerCheck == null) || scheduleServerCheck.isShutdown())) {
        // Get the ping address
        final Uri.Builder pingUri = getServerUriBuilder();
        pingUri.appendPath("ping");
        // Schedule the background server check
        scheduleServerCheck = Executors.newScheduledThreadPool(1);
        scheduleServerCheck.scheduleWithFixedDelay(new Runnable() {
            public void run() {
                int response = 0;
                try {
                    URL url = new URL(pingUri.build().toString());
                    HttpURLConnection conn = (HttpURLConnection) url.openConnection();
                    conn.setReadTimeout(3000); /* milliseconds */
                    conn.setConnectTimeout(5000); /* milliseconds */
                    conn.setRequestMethod("GET");
                    conn.setDoInput(true);
                    conn.connect();
                    response = conn.getResponseCode();
                } catch (Exception e) {
                    // Safely ignored as a response!=200 will trigger the offline title
                }
                if (response == 200) {
                    if (Log.LOGV)
                        Log.i(LOG_TAG + "Server response 200");
                    guiHandler.post(online);
                } else {
                    if (Log.LOGV)
                        Log.i(LOG_TAG + "Server response NOT 200");
                    guiHandler.post(offline);
                }
            }
        }, 0, 30, TimeUnit.SECONDS);
        if (Log.LOGV)
            Log.v(LOG_TAG + "BackgroundServerCheck started");
    } else {
        if (Log.LOGV)
            Log.d(LOG_TAG + "Server response NOT 200");
        guiHandler.post(offline);
    }
}

From source file:org.ametro.util.WebUtil.java

public static void downloadFileAsync(final Context appContext, final File path, final URI uri,
        final File temp) {

    final DownloadContext context = new DownloadContext();
    context.Path = path;/*w  w  w.j  a  va  2s.c o m*/
    context.IsCanceled = false;
    context.IsUnpackFinished = false;
    context.IsFailed = false;

    final NotificationManager notificationManager = (NotificationManager) appContext
            .getSystemService(Context.NOTIFICATION_SERVICE);

    final Handler handler = new Handler();

    final Runnable updateProgress = new Runnable() {
        public void run() {
            if (context.Notification == null) {
                context.Notification = new Notification(android.R.drawable.stat_sys_download,
                        "Downloading icons", System.currentTimeMillis());
                context.Notification.flags = Notification.FLAG_NO_CLEAR;
                Intent notificationIntent = new Intent();
                context.ContentIntent = PendingIntent.getActivity(appContext, 0, notificationIntent, 0);
            }
            if (context.IsFailed) {
                notificationManager.cancelAll();
                context.Notification = new Notification(android.R.drawable.stat_sys_warning,
                        "Icons download failed", System.currentTimeMillis());
                context.Notification.setLatestEventInfo(appContext, "aMetro", "Icons downloaded failed",
                        context.ContentIntent);
                notificationManager.notify(2, context.Notification);

            } else if (context.IsUnpackFinished) {
                notificationManager.cancelAll();
                context.Notification = new Notification(android.R.drawable.stat_sys_download_done,
                        "Icons unpacked", System.currentTimeMillis());
                context.Notification.setLatestEventInfo(appContext, "aMetro", "Icons downloaded and unpacked.",
                        context.ContentIntent);
                notificationManager.notify(3, context.Notification);

            } else if (context.Position == 0 && context.Total == 0) {
                context.Notification.setLatestEventInfo(appContext, "aMetro",
                        "Download icons: connecting server", context.ContentIntent);
                notificationManager.notify(1, context.Notification);
            } else if (context.Position < context.Total) {
                context.Notification.setLatestEventInfo(appContext, "aMetro",
                        "Download icons: " + context.Position + "/" + context.Total, context.ContentIntent);
                notificationManager.notify(1, context.Notification);
            } else {
                context.Notification.setLatestEventInfo(appContext, "aMetro", "Icons unpacking",
                        context.ContentIntent);
                notificationManager.notify(1, context.Notification);
            }
        }
    };

    final Thread async = new Thread() {
        public void run() {
            WebUtil.downloadFile(context, uri, temp, false, new IDownloadListener() {

                public void onBegin(Object context, File file) {
                    DownloadContext downloadContext = (DownloadContext) context;
                    downloadContext.Total = 0;
                    downloadContext.Position = 0;
                    handler.removeCallbacks(updateProgress);
                    handler.post(updateProgress);
                }

                public boolean onUpdate(Object context, long position, long total) {
                    DownloadContext downloadContext = (DownloadContext) context;
                    downloadContext.Total = total;
                    downloadContext.Position = position;
                    handler.removeCallbacks(updateProgress);
                    handler.post(updateProgress);
                    return !downloadContext.IsCanceled;
                }

                public void onDone(Object context, File file) throws Exception {
                    DownloadContext downloadContext = (DownloadContext) context;
                    File path = downloadContext.Path;
                    ZipUtil.unzip(file, path);
                    downloadContext.IsUnpackFinished = true;
                    handler.removeCallbacks(updateProgress);
                    handler.post(updateProgress);
                }

                public void onCanceled(Object context, File file) {
                    DownloadContext downloadContext = (DownloadContext) context;
                    downloadContext.IsCanceled = true;
                    handler.removeCallbacks(updateProgress);
                    handler.post(updateProgress);
                }

                public void onFailed(Object context, File file, Throwable reason) {
                    DownloadContext downloadContext = (DownloadContext) context;
                    downloadContext.IsFailed = true;
                    handler.removeCallbacks(updateProgress);
                    handler.post(updateProgress);
                }

            });
        };
    };
    async.start();
}

From source file:com.licubeclub.zionhs.Schedule.java

private void networkTask() {
    SRL.setRefreshing(true);/* w ww .  ja  v  a 2  s  .co m*/
    ScheduleCacheManager manager = new ScheduleCacheManager();
    NetworkChecker NetCheck = new NetworkChecker(Schedule.this);
    if (NetCheck.isNetworkConnected()) {
        final Handler mHandler = new Handler();

        new Thread() {
            public void run() {

                //Task

                //Notices URL
                try {
                    int skip = 0;
                    boolean skipedboolean = false;
                    schedulearray = new ArrayList<String>();
                    dayarray = new ArrayList<String>();

                    //                    ? ?? ? ??  
                    Document doc = Jsoup.connect(URL).get();

                    Elements rawdaydata = doc.select(".listDay"); //Get contents from the class,"listDay"
                    for (Element el : rawdaydata) {
                        String daydata = el.text();
                        if (daydata.equals("") | daydata == null) {
                            if (skipedboolean) {
                            } else {
                                skip++;
                            }
                        } else {
                            dayarray.add(daydata); // add value to ArrayList
                            skipedboolean = true;
                        }
                    }
                    Log.d("Schedule", "Parsed Day Array" + dayarray);

                    Elements rawscheduledata = doc.select(".listData"); //Get contents from tags,"a" which are in the class,"ellipsis"
                    for (Element el : rawscheduledata) {
                        String scheduledata = el.text();
                        if (skip > 0) {
                            skip--;
                        } else {
                            schedulearray.add(scheduledata); // add value to ArrayList
                        }
                    }
                    Log.d("Schedule", "Parsed Schedule Array" + schedulearray);

                    //                    SRL.setRefreshing(false);
                } catch (IOException e) {
                    e.printStackTrace();
                    //                    SRL.setRefreshing(false);

                }
                mHandler.post(new Runnable() {
                    public void run() {
                        //UI Task
                        adapter = new ListCalendarAdapter(Schedule.this, dayarray, schedulearray);
                        listview.setAdapter(adapter);
                        ScheduleCacheManager manager = new ScheduleCacheManager();
                        manager.updateCache(dayarray, schedulearray);
                        SRL.setRefreshing(false);
                        handler.sendEmptyMessage(0);
                    }
                });

            }
        }.start();

    } else {
        Log.d("Schedule", "Loading from Cache");
        Toast.makeText(Schedule.this, getResources().getString(R.string.network_connection_warning),
                Toast.LENGTH_LONG).show();
        dayarray = manager.loadDateCache();
        schedulearray = manager.loadContentCache();
        adapter = new ListCalendarAdapter(Schedule.this, dayarray, schedulearray);
        listview.setAdapter(adapter);
    }

}