Example usage for android.app Activity runOnUiThread

List of usage examples for android.app Activity runOnUiThread

Introduction

In this page you can find the example usage for android.app Activity runOnUiThread.

Prototype

public final void runOnUiThread(Runnable action) 

Source Link

Document

Runs the specified action on the UI thread.

Usage

From source file:com.nttec.everychan.http.recaptcha.Recaptcha2fallback.java

@Override
public void handle(final Activity activity, final CancellableTask task, final Callback callback) {
    try {//ww  w .  j a  v a 2  s  .c o  m
        final HttpClient httpClient = ((HttpChanModule) MainApplication.getInstance().getChanModule(chanName))
                .getHttpClient();
        final String usingURL = scheme + RECAPTCHA_FALLBACK_URL + publicKey
                + (sToken != null && sToken.length() > 0 ? ("&stoken=" + sToken) : "");
        String refererURL = baseUrl != null && baseUrl.length() > 0 ? baseUrl : usingURL;
        Header[] customHeaders = new Header[] { new BasicHeader(HttpHeaders.REFERER, refererURL) };
        String htmlChallenge;
        if (lastChallenge != null && lastChallenge.getLeft().equals(usingURL)) {
            htmlChallenge = lastChallenge.getRight();
        } else {
            htmlChallenge = HttpStreamer.getInstance().getStringFromUrl(usingURL,
                    HttpRequestModel.builder().setGET().setCustomHeaders(customHeaders).build(), httpClient,
                    null, task, false);
        }
        lastChallenge = null;

        Matcher challengeMatcher = Pattern.compile("name=\"c\" value=\"([\\w-]+)").matcher(htmlChallenge);
        if (challengeMatcher.find()) {
            final String challenge = challengeMatcher.group(1);
            HttpResponseModel responseModel = HttpStreamer.getInstance().getFromUrl(
                    scheme + RECAPTCHA_IMAGE_URL + challenge + "&k=" + publicKey,
                    HttpRequestModel.builder().setGET().setCustomHeaders(customHeaders).build(), httpClient,
                    null, task);
            try {
                InputStream imageStream = responseModel.stream;
                final Bitmap challengeBitmap = BitmapFactory.decodeStream(imageStream);

                final String message;
                Matcher messageMatcher = Pattern.compile("imageselect-message(?:.*?)>(.*?)</div>")
                        .matcher(htmlChallenge);
                if (messageMatcher.find())
                    message = RegexUtils.removeHtmlTags(messageMatcher.group(1));
                else
                    message = null;

                final Bitmap candidateBitmap;
                Matcher candidateMatcher = Pattern
                        .compile("fbc-imageselect-candidates(?:.*?)src=\"data:image/(?:.*?);base64,([^\"]*)\"")
                        .matcher(htmlChallenge);
                if (candidateMatcher.find()) {
                    Bitmap bmp = null;
                    try {
                        byte[] imgData = Base64.decode(candidateMatcher.group(1), Base64.DEFAULT);
                        bmp = BitmapFactory.decodeByteArray(imgData, 0, imgData.length);
                    } catch (Exception e) {
                    }
                    candidateBitmap = bmp;
                } else
                    candidateBitmap = null;

                activity.runOnUiThread(new Runnable() {
                    final int maxX = 3;
                    final int maxY = 3;
                    final boolean[] isSelected = new boolean[maxX * maxY];

                    @SuppressLint("InlinedApi")
                    @Override
                    public void run() {
                        LinearLayout rootLayout = new LinearLayout(activity);
                        rootLayout.setOrientation(LinearLayout.VERTICAL);

                        if (candidateBitmap != null) {
                            ImageView candidateView = new ImageView(activity);
                            candidateView.setImageBitmap(candidateBitmap);
                            int picSize = (int) (activity.getResources().getDisplayMetrics().density * 50
                                    + 0.5f);
                            candidateView.setLayoutParams(new LinearLayout.LayoutParams(picSize, picSize));
                            candidateView.setScaleType(ImageView.ScaleType.FIT_XY);
                            rootLayout.addView(candidateView);
                        }

                        if (message != null) {
                            TextView textView = new TextView(activity);
                            textView.setText(message);
                            CompatibilityUtils.setTextAppearance(textView, android.R.style.TextAppearance);
                            textView.setLayoutParams(
                                    new LinearLayout.LayoutParams(LinearLayout.LayoutParams.MATCH_PARENT,
                                            LinearLayout.LayoutParams.WRAP_CONTENT));
                            rootLayout.addView(textView);
                        }

                        FrameLayout frame = new FrameLayout(activity);
                        frame.setLayoutParams(
                                new LinearLayout.LayoutParams(LinearLayout.LayoutParams.MATCH_PARENT,
                                        LinearLayout.LayoutParams.WRAP_CONTENT));

                        final ImageView imageView = new ImageView(activity);
                        imageView.setLayoutParams(new FrameLayout.LayoutParams(
                                FrameLayout.LayoutParams.MATCH_PARENT, FrameLayout.LayoutParams.MATCH_PARENT));
                        imageView.setScaleType(ImageView.ScaleType.FIT_XY);
                        imageView.setImageBitmap(challengeBitmap);
                        frame.addView(imageView);

                        final LinearLayout selector = new LinearLayout(activity);
                        selector.setLayoutParams(new FrameLayout.LayoutParams(
                                FrameLayout.LayoutParams.MATCH_PARENT, FrameLayout.LayoutParams.MATCH_PARENT));
                        AppearanceUtils.callWhenLoaded(imageView, new Runnable() {
                            @Override
                            public void run() {
                                selector.setLayoutParams(new FrameLayout.LayoutParams(imageView.getWidth(),
                                        imageView.getHeight()));
                            }
                        });
                        selector.setOrientation(LinearLayout.VERTICAL);
                        selector.setWeightSum(maxY);
                        for (int y = 0; y < maxY; ++y) {
                            LinearLayout subSelector = new LinearLayout(activity);
                            subSelector.setLayoutParams(new LinearLayout.LayoutParams(
                                    LinearLayout.LayoutParams.MATCH_PARENT, 0, 1f));
                            subSelector.setOrientation(LinearLayout.HORIZONTAL);
                            subSelector.setWeightSum(maxX);
                            for (int x = 0; x < maxX; ++x) {
                                FrameLayout switcher = new FrameLayout(activity);
                                switcher.setLayoutParams(new LinearLayout.LayoutParams(0,
                                        LinearLayout.LayoutParams.MATCH_PARENT, 1f));
                                switcher.setTag(new int[] { x, y });
                                switcher.setOnClickListener(new View.OnClickListener() {
                                    @Override
                                    public void onClick(View v) {
                                        int[] coord = (int[]) v.getTag();
                                        int index = coord[1] * maxX + coord[0];
                                        isSelected[index] = !isSelected[index];
                                        v.setBackgroundColor(isSelected[index] ? Color.argb(128, 0, 255, 0)
                                                : Color.TRANSPARENT);
                                    }
                                });
                                subSelector.addView(switcher);
                            }
                            selector.addView(subSelector);
                        }

                        frame.addView(selector);
                        rootLayout.addView(frame);

                        Button checkButton = new Button(activity);
                        checkButton.setLayoutParams(
                                new LinearLayout.LayoutParams(LinearLayout.LayoutParams.MATCH_PARENT,
                                        LinearLayout.LayoutParams.WRAP_CONTENT));
                        checkButton.setText(android.R.string.ok);
                        rootLayout.addView(checkButton);

                        ScrollView dlgView = new ScrollView(activity);
                        dlgView.addView(rootLayout);

                        final Dialog dialog = new Dialog(activity);
                        dialog.setTitle("Recaptcha");
                        dialog.setContentView(dlgView);
                        dialog.setCanceledOnTouchOutside(false);
                        dialog.setOnCancelListener(new DialogInterface.OnCancelListener() {
                            @Override
                            public void onCancel(DialogInterface dialog) {
                                if (!task.isCancelled()) {
                                    callback.onError("Cancelled");
                                }
                            }
                        });
                        dialog.getWindow().setLayout(ViewGroup.LayoutParams.MATCH_PARENT,
                                ViewGroup.LayoutParams.WRAP_CONTENT);
                        dialog.show();

                        checkButton.setOnClickListener(new View.OnClickListener() {
                            @Override
                            public void onClick(View v) {
                                dialog.dismiss();
                                if (task.isCancelled())
                                    return;
                                Async.runAsync(new Runnable() {
                                    @Override
                                    public void run() {
                                        try {
                                            List<NameValuePair> pairs = new ArrayList<NameValuePair>();
                                            pairs.add(new BasicNameValuePair("c", challenge));
                                            for (int i = 0; i < isSelected.length; ++i)
                                                if (isSelected[i])
                                                    pairs.add(new BasicNameValuePair("response",
                                                            Integer.toString(i)));

                                            HttpRequestModel request = HttpRequestModel.builder()
                                                    .setPOST(new UrlEncodedFormEntity(pairs, "UTF-8"))
                                                    .setCustomHeaders(new Header[] {
                                                            new BasicHeader(HttpHeaders.REFERER, usingURL) })
                                                    .build();
                                            String response = HttpStreamer.getInstance().getStringFromUrl(
                                                    usingURL, request, httpClient, null, task, false);
                                            String hash = "";
                                            Matcher matcher = Pattern.compile(
                                                    "fbc-verification-token(?:.*?)<textarea[^>]*>([^<]*)<",
                                                    Pattern.DOTALL).matcher(response);
                                            if (matcher.find())
                                                hash = matcher.group(1);

                                            if (hash.length() > 0) {
                                                Recaptcha2solved.push(publicKey, hash);
                                                activity.runOnUiThread(new Runnable() {
                                                    @Override
                                                    public void run() {
                                                        callback.onSuccess();
                                                    }
                                                });
                                            } else {
                                                lastChallenge = Pair.of(usingURL, response);
                                                throw new RecaptchaException(
                                                        "incorrect answer (hash is empty)");
                                            }
                                        } catch (final Exception e) {
                                            Logger.e(TAG, e);
                                            if (task.isCancelled())
                                                return;
                                            handle(activity, task, callback);
                                        }
                                    }
                                });
                            }
                        });
                    }
                });
            } finally {
                responseModel.release();
            }
        } else
            throw new Exception("can't parse recaptcha challenge answer");
    } catch (final Exception e) {
        Logger.e(TAG, e);
        if (!task.isCancelled()) {
            activity.runOnUiThread(new Runnable() {
                @Override
                public void run() {
                    callback.onError(e.getMessage() != null ? e.getMessage() : e.toString());
                }
            });
        }
    }
}

From source file:im.neon.activity.CommonActivityUtils.java

/**
 * Offer to send some dedicated intent data to an existing room
 *
 * @param fromActivity the caller activity
 * @param intent       the intent param/*from  w w w.j  a v a 2s .c  o  m*/
 * @param session      the session/
 */
private static void sendFilesTo(final Activity fromActivity, final Intent intent, final MXSession session) {
    // sanity check
    if ((null == session) || !session.isAlive()) {
        return;
    }

    ArrayList<RoomSummary> mergedSummaries = new ArrayList<>(
            session.getDataHandler().getStore().getSummaries());

    // keep only the joined room
    for (int index = 0; index < mergedSummaries.size(); index++) {
        RoomSummary summary = mergedSummaries.get(index);
        Room room = session.getDataHandler().getRoom(summary.getRoomId());

        if ((null == room) || room.isInvited() || room.isConferenceUserRoom()) {
            mergedSummaries.remove(index);
            index--;
        }
    }

    Collections.sort(mergedSummaries, new Comparator<RoomSummary>() {
        @Override
        public int compare(RoomSummary lhs, RoomSummary rhs) {
            if (lhs == null || lhs.getLatestReceivedEvent() == null) {
                return 1;
            } else if (rhs == null || rhs.getLatestReceivedEvent() == null) {
                return -1;
            }

            if (lhs.getLatestReceivedEvent().getOriginServerTs() > rhs.getLatestReceivedEvent()
                    .getOriginServerTs()) {
                return -1;
            } else if (lhs.getLatestReceivedEvent().getOriginServerTs() < rhs.getLatestReceivedEvent()
                    .getOriginServerTs()) {
                return 1;
            }
            return 0;
        }
    });

    AlertDialog.Builder builderSingle = new AlertDialog.Builder(fromActivity);
    builderSingle.setTitle(fromActivity.getText(R.string.send_files_in));

    VectorRoomsSelectionAdapter adapter = new VectorRoomsSelectionAdapter(fromActivity,
            R.layout.adapter_item_vector_recent_room, session);
    adapter.addAll(mergedSummaries);

    builderSingle.setNegativeButton(fromActivity.getText(R.string.cancel),
            new DialogInterface.OnClickListener() {
                @Override
                public void onClick(DialogInterface dialog, int which) {
                    dialog.dismiss();
                }
            });

    final ArrayList<RoomSummary> fMergedSummaries = mergedSummaries;

    builderSingle.setAdapter(adapter, new DialogInterface.OnClickListener() {

        @Override
        public void onClick(DialogInterface dialog, final int which) {
            dialog.dismiss();
            fromActivity.runOnUiThread(new Runnable() {
                @Override
                public void run() {
                    RoomSummary summary = fMergedSummaries.get(which);

                    HashMap<String, Object> params = new HashMap<>();
                    params.put(VectorRoomActivity.EXTRA_MATRIX_ID, session.getMyUserId());
                    params.put(VectorRoomActivity.EXTRA_ROOM_ID, summary.getRoomId());
                    params.put(VectorRoomActivity.EXTRA_ROOM_INTENT, intent);

                    CommonActivityUtils.goToRoomPage(fromActivity, session, params);
                }
            });
        }
    });
    builderSingle.show();
}

From source file:org.linphone.ContactsManager.java

public synchronized void prepareContactsInBackgroundWithUI(final Activity activity,
        final FragmentManager manager, final ProgressDialog pd) {
    if (contactCursor != null) {
        contactCursor.close();/* ww w.  j  ava  2s.  co  m*/
    }
    if (sipContactCursor != null) {
        sipContactCursor.close();
    }

    //      if(LinphoneActivity.instance().getResources().getBoolean(R.bool.use_linphone_friend)){
    //         contactList = new ArrayList<Contact>();
    //         for(LinphoneFriend friend : LinphoneManager.getLc().getFriendList()){
    //            Contact contact = new Contact(friend.getRefKey(),friend.getAddress());
    //            contactList.add(contact);
    //         }
    //         contactCursor = getFriendListCursor(contactList,true);
    //         return;
    //      }

    Log.e("LINPHONE", "preparing contacts in background:use_linphone_friend");
    //if(mAccount == null) return;

    contactCursor = Compatibility.getContactsCursor(contentResolver, getContactsId());

    Log.e("LINPHONE", "preparing contacts in background contactCursor" + contactCursor == null);
    sipContactCursor = Compatibility.getSIPContactsCursor(contentResolver, getContactsId());

    Thread sipContactsHandler = new Thread(new Runnable() {
        @Override
        public void run() {
            if (sipContactCursor != null && sipContactCursor.getCount() > 0) {
                for (int i = 0; i < sipContactCursor.getCount(); i++) {
                    Contact contact = Compatibility.getContact(contentResolver, sipContactCursor, i);
                    if (contact == null)
                        continue;

                    contact.refresh(contentResolver);
                    //Add tag to Linphone contact if it not existed
                    if (LinphoneActivity.isInstanciated()
                            && LinphoneActivity.instance().getResources().getBoolean(R.bool.use_linphone_tag)) {
                        if (!isContactHasLinphoneTag(contact, contentResolver)) {
                            Compatibility.createLinphoneContactTag(context, contentResolver, contact,
                                    findRawContactID(contentResolver, String.valueOf(contact.getID())));
                        }
                    }

                    sipContactList.add(contact);
                }
            }
            if (contactCursor != null) {
                for (int i = 0; i < contactCursor.getCount(); i++) {
                    Contact contact = Compatibility.getContact(contentResolver, contactCursor, i);
                    if (contact == null)
                        continue;

                    //Remove linphone contact tag if the contact has no sip address
                    if (LinphoneActivity.isInstanciated()
                            && LinphoneActivity.instance().getResources().getBoolean(R.bool.use_linphone_tag)) {
                        if (removeContactTagIsNeeded(contact)
                                && findRawLinphoneContactID(contact.getID()) != null) {
                            removeLinphoneContactTag(contact);
                        }
                    }
                    for (Contact c : sipContactList) {
                        if (c != null && c.getID().equals(contact.getID())) {
                            contact = c;
                            break;
                        }
                    }
                    contactList.add(contact);
                }

                activity.runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        pd.dismiss();
                        manager.popBackStackImmediate();
                    }
                });
            }
        }
    });

    contactList = new ArrayList<Contact>();
    sipContactList = new ArrayList<Contact>();

    sipContactsHandler.start();
}

From source file:net.etuldan.sparss.fragment.EntryFragment.java

@Override
public boolean onOptionsItemSelected(MenuItem item) {
    if (mEntriesIds != null) {
        final Activity activity = getActivity();

        switch (item.getItemId()) {
        case R.id.menu_star: {
            mFavorite = !mFavorite;//from  w  ww . j a  v a  2  s.c o  m

            if (mFavorite) {
                item.setTitle(R.string.menu_unstar).setIcon(R.drawable.ic_star);
            } else {
                item.setTitle(R.string.menu_star).setIcon(R.drawable.ic_star_border);
            }

            final Uri uri = ContentUris.withAppendedId(mBaseUri, mEntriesIds[mCurrentPagerPos]);
            new Thread() {
                @Override
                public void run() {
                    ContentValues values = new ContentValues();
                    values.put(EntryColumns.IS_FAVORITE, mFavorite ? 1 : 0);
                    ContentResolver cr = MainApplication.getContext().getContentResolver();
                    cr.update(uri, values, null, null);

                    // Update the cursor
                    Cursor updatedCursor = cr.query(uri, null, null, null, null);
                    updatedCursor.moveToFirst();
                    mEntryPagerAdapter.setUpdatedCursor(mCurrentPagerPos, updatedCursor);
                }
            }.start();
            break;
        }
        case R.id.menu_share: {
            Cursor cursor = mEntryPagerAdapter.getCursor(mCurrentPagerPos);
            if (cursor != null) {
                String link = cursor.getString(mLinkPos);
                if (link != null) {
                    String title = cursor.getString(mTitlePos);
                    startActivity(Intent.createChooser(
                            new Intent(Intent.ACTION_SEND).putExtra(Intent.EXTRA_SUBJECT, title)
                                    .putExtra(Intent.EXTRA_TEXT, link).setType(Constants.MIMETYPE_TEXT_PLAIN),
                            getString(R.string.menu_share)));
                }
            }
            break;
        }
        case R.id.menu_full_screen: {
            setImmersiveFullScreen(true);
            break;
        }
        case R.id.menu_copy_clipboard: {
            Cursor cursor = mEntryPagerAdapter.getCursor(mCurrentPagerPos);
            String link = cursor.getString(mLinkPos);
            ClipboardManager clipboard = (ClipboardManager) activity
                    .getSystemService(Context.CLIPBOARD_SERVICE);
            ClipData clip = ClipData.newPlainText("Copied Text", link);
            clipboard.setPrimaryClip(clip);

            Toast.makeText(activity, R.string.copied_clipboard, Toast.LENGTH_SHORT).show();
            break;
        }
        case R.id.menu_mark_as_unread: {
            final Uri uri = ContentUris.withAppendedId(mBaseUri, mEntriesIds[mCurrentPagerPos]);
            new Thread() {
                @Override
                public void run() {
                    ContentResolver cr = MainApplication.getContext().getContentResolver();
                    cr.update(uri, FeedData.getUnreadContentValues(), null, null);
                }
            }.start();
            activity.finish();
            break;
        }
        case R.id.menu_open_in_browser: {
            Cursor cursor = mEntryPagerAdapter.getCursor(mCurrentPagerPos);
            if (cursor != null) {
                String link = cursor.getString(mLinkPos);
                if (link != null) {
                    Intent browserIntent = new Intent(Intent.ACTION_VIEW, Uri.parse(link));
                    startActivity(browserIntent);
                }
            }
            break;
        }
        case R.id.menu_switch_full_original: {
            isChecked = !item.isChecked();
            item.setChecked(isChecked);
            if (mPreferFullText) {
                getActivity().runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        mPreferFullText = false;
                        mEntryPagerAdapter.displayEntry(mCurrentPagerPos, null, true);
                    }
                });
            } else {
                Cursor cursor = mEntryPagerAdapter.getCursor(mCurrentPagerPos);
                final boolean alreadyMobilized = !cursor.isNull(mMobilizedHtmlPos);

                if (alreadyMobilized) {
                    activity.runOnUiThread(new Runnable() {
                        @Override
                        public void run() {
                            mPreferFullText = true;
                            mEntryPagerAdapter.displayEntry(mCurrentPagerPos, null, true);
                        }
                    });
                } else if (!isRefreshing()) {
                    ConnectivityManager connectivityManager = (ConnectivityManager) activity
                            .getSystemService(Context.CONNECTIVITY_SERVICE);
                    final NetworkInfo networkInfo = connectivityManager.getActiveNetworkInfo();

                    // since we have acquired the networkInfo, we use it for basic checks
                    if (networkInfo != null && networkInfo.getState() == NetworkInfo.State.CONNECTED) {
                        FetcherService.addEntriesToMobilize(new long[] { mEntriesIds[mCurrentPagerPos] });
                        activity.startService(new Intent(activity, FetcherService.class)
                                .setAction(FetcherService.ACTION_MOBILIZE_FEEDS));
                        activity.runOnUiThread(new Runnable() {
                            @Override
                            public void run() {
                                showSwipeProgress();
                            }
                        });
                    } else {
                        activity.runOnUiThread(new Runnable() {
                            @Override
                            public void run() {
                                Toast.makeText(activity, R.string.network_error, Toast.LENGTH_SHORT).show();
                            }
                        });
                    }
                }
            }
            break;
        }
        default:
            break;
        }
    }

    return super.onOptionsItemSelected(item);
}

From source file:net.news.inrss.fragment.EntryFragment.java

@Override
public boolean onOptionsItemSelected(MenuItem item) {
    if (mEntriesIds != null) {
        final Activity activity = getActivity();

        switch (item.getItemId()) {
        case R.id.menu_star: {
            mFavorite = !mFavorite;/*from  w w  w  .j  a  v a 2  s. c o  m*/

            if (mFavorite) {
                item.setTitle(R.string.menu_unstar).setIcon(R.drawable.ic_star);
            } else {
                item.setTitle(R.string.menu_star).setIcon(R.drawable.ic_star_border);
            }

            final Uri uri = ContentUris.withAppendedId(mBaseUri, mEntriesIds[mCurrentPagerPos]);
            new Thread() {
                @Override
                public void run() {
                    ContentValues values = new ContentValues();
                    values.put(EntryColumns.IS_FAVORITE, mFavorite ? 1 : 0);
                    ContentResolver cr = MainApplication.getContext().getContentResolver();
                    cr.update(uri, values, null, null);

                    // Update the cursor
                    Cursor updatedCursor = cr.query(uri, null, null, null, null);
                    updatedCursor.moveToFirst();
                    mEntryPagerAdapter.setUpdatedCursor(mCurrentPagerPos, updatedCursor);
                }
            }.start();
            break;
        }
        case R.id.menu_share: {
            Cursor cursor = mEntryPagerAdapter.getCursor(mCurrentPagerPos);
            if (cursor != null) {
                String link = cursor.getString(mLinkPos);
                if (link != null) {
                    String title = cursor.getString(mTitlePos);
                    startActivity(Intent.createChooser(
                            new Intent(Intent.ACTION_SEND).putExtra(Intent.EXTRA_SUBJECT, title)
                                    .putExtra(Intent.EXTRA_TEXT, link).setType(Constants.MIMETYPE_TEXT_PLAIN),
                            getString(R.string.menu_share)));
                }
            }
            break;
        }
        case R.id.menu_full_screen: {
            setImmersiveFullScreen(true);
            break;
        }
        case R.id.menu_copy_clipboard: {
            Cursor cursor = mEntryPagerAdapter.getCursor(mCurrentPagerPos);
            String link = cursor.getString(mLinkPos);
            ClipboardManager clipboard = (ClipboardManager) activity
                    .getSystemService(Context.CLIPBOARD_SERVICE);
            ClipData clip = ClipData.newPlainText("Copied Text", link);
            clipboard.setPrimaryClip(clip);

            Toast.makeText(activity, R.string.copied_clipboard, Toast.LENGTH_SHORT).show();
            break;
        }
        case R.id.menu_mark_as_unread: {
            final Uri uri = ContentUris.withAppendedId(mBaseUri, mEntriesIds[mCurrentPagerPos]);
            new Thread() {
                @Override
                public void run() {
                    ContentResolver cr = MainApplication.getContext().getContentResolver();
                    cr.update(uri, FeedData.getUnreadContentValues(), null, null);
                }
            }.start();
            activity.finish();
            break;
        }
        case R.id.menu_open_in_browser: {
            Cursor cursor = mEntryPagerAdapter.getCursor(mCurrentPagerPos);
            if (cursor != null) {
                String link = cursor.getString(mLinkPos);
                if (link != null) {
                    Intent browserIntent = new Intent(Intent.ACTION_VIEW, Uri.parse(link));
                    startActivity(browserIntent);
                }
            }
            break;
        }
        case R.id.menu_switch_full_original: {
            if (mPreferFullText) {
                getActivity().runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        mPreferFullText = false;
                        Log.d(TAG, "run: manual call of displayEntry(), fullText=false");
                        mEntryPagerAdapter.displayEntry(mCurrentPagerPos, null, true);
                    }
                });
            } else {
                Cursor cursor = mEntryPagerAdapter.getCursor(mCurrentPagerPos);
                final boolean alreadyMobilized = !cursor.isNull(mMobilizedHtmlPos);

                if (alreadyMobilized) {
                    Log.d(TAG, "onOptionsItemSelected: alreadyMobilized");
                    mPreferFullText = true;
                    activity.runOnUiThread(new Runnable() {
                        @Override
                        public void run() {
                            Log.d(TAG, "run: manual call of displayEntry(), fullText=true");
                            mEntryPagerAdapter.displayEntry(mCurrentPagerPos, null, true);
                        }
                    });
                } else if (!isRefreshing()) {
                    Log.d(TAG, "onOptionsItemSelected: about to load article...");
                    mPreferFullText = false;
                    ConnectivityManager connectivityManager = (ConnectivityManager) activity
                            .getSystemService(Context.CONNECTIVITY_SERVICE);
                    final NetworkInfo networkInfo = connectivityManager.getActiveNetworkInfo();

                    // since we have acquired the networkInfo, we use it for basic checks
                    if (networkInfo != null && networkInfo.getState() == NetworkInfo.State.CONNECTED) {
                        FetcherService.addEntriesToMobilize(new long[] { mEntriesIds[mCurrentPagerPos] });
                        activity.startService(new Intent(activity, FetcherService.class)
                                .setAction(FetcherService.ACTION_MOBILIZE_FEEDS));
                    } else {
                        activity.runOnUiThread(new Runnable() {
                            @Override
                            public void run() {
                                Toast.makeText(activity, R.string.network_error, Toast.LENGTH_SHORT).show();
                            }
                        });
                        Log.d(TAG, "onOptionsItemSelected: cannot load article. no internet connection.");
                    }
                } else {
                    Log.d(TAG, "onOptionsItemSelected: refreshing already in progress");
                }
            }
            mShowFullContentItem.setChecked(mPreferFullText);
            break;
        }
        default:
            break;
        }
    }

    return super.onOptionsItemSelected(item);
}

From source file:run.ace.NativeHost.java

void send(final JSONArray messages, final CallbackContext callbackContext) {
    final Activity activity = _activity;
    Runnable runnable = new Runnable() {
        public void run() {
            try {
                Object returnValue = null;
                boolean hasReturnValue = false; // Needed because null can be a valid return value
                int numMessages = messages.length();

                for (int i = 0; i < numMessages; i++) {
                    Object instance = null;
                    Handle handle;//from   ww w.j a v  a  2s.co  m
                    JSONArray message = messages.getJSONArray(i);
                    //android.util.Log.d("Ace", "TODO: MSG: " + message);
                    int messageType = message.getInt(0);

                    switch (messageType) {
                    case IncomingMessages.MSG_CREATE:
                        instance = IncomingMessages.create(message, activity);
                        handle = Handle.fromJSONObject(message.getJSONObject(1));
                        handle.register(instance);
                        break;
                    case IncomingMessages.MSG_SET:
                        IncomingMessages.set(message);
                        break;
                    case IncomingMessages.MSG_INVOKE:
                        returnValue = IncomingMessages.invoke(message);
                        hasReturnValue = true;
                        break;
                    case IncomingMessages.MSG_EVENTADD:
                        IncomingMessages.eventAdd(message);
                        break;
                    case IncomingMessages.MSG_EVENTREMOVE:
                        IncomingMessages.eventRemove(message);
                        break;
                    case IncomingMessages.MSG_STATICINVOKE:
                        returnValue = IncomingMessages.staticInvoke(message);
                        hasReturnValue = true;
                        break;
                    case IncomingMessages.MSG_FIELDGET:
                        returnValue = IncomingMessages.fieldGet(message);
                        hasReturnValue = true;
                        break;
                    case IncomingMessages.MSG_STATICFIELDGET:
                        returnValue = IncomingMessages.staticFieldGet(message);
                        hasReturnValue = true;
                        break;
                    case IncomingMessages.MSG_GETINSTANCE:
                        instance = IncomingMessages.getInstance(message, activity, _webView);
                        handle = Handle.fromJSONObject(message.getJSONObject(1));
                        handle.register(instance);
                        break;
                    case IncomingMessages.MSG_NAVIGATE:
                        IncomingMessages.navigate((View) Handle.deserialize(message.getJSONObject(1)),
                                activity);
                        break;
                    case IncomingMessages.MSG_FIELDSET:
                        IncomingMessages.fieldSet(message);
                        break;
                    case IncomingMessages.MSG_PRIVATEFIELDGET:
                        returnValue = IncomingMessages.privateFieldGet(message);
                        hasReturnValue = true;
                        break;
                    default:
                        throw new RuntimeException("Unknown message type: " + messageType);
                    }
                }

                if (numMessages == 1 && hasReturnValue) {
                    // This is a single (non-batched) invoke with a return value
                    // (or a field get).
                    // Send it.
                    // TODO: Need to handle arrays of primitives/objects as well
                    if (Utils.isBoxedNumberOrString(returnValue) || returnValue == null) {
                        // Send the primitive value
                        JSONArray primitive = new JSONArray();
                        primitive.put(returnValue);
                        callbackContext.success(primitive);
                    } else {
                        // Send the object as a handle
                        // Use existing handle if this object already has one
                        Handle handle = Handle.fromObject(returnValue);
                        if (handle == null) {
                            handle = new Handle();
                            handle.register(returnValue);
                        }
                        callbackContext.success(handle.toJSONObject());
                    }
                } else {
                    callbackContext.success();
                }
            } catch (Exception ex) {
                android.util.Log.d("Ace", "Caught exception: " + exceptionWithStackTrace(ex));
                callbackContext.error(exceptionWithStackTrace(ex));
            }
        };
    };
    activity.runOnUiThread(runnable);
}

From source file:com.polychrom.cordova.ActionBarPlugin.java

@Override
public boolean execute(final String action, final JSONArray args, final CallbackContext callbackContext)
        throws JSONException {
    if (!plugin_actions.contains(action)) {
        return false;
    }/*w w  w .  j  a v a2  s. c om*/

    final Activity ctx = (Activity) cordova;

    if ("isAvailable".equals(action)) {
        JSONObject result = new JSONObject();
        result.put("value", ctx.getWindow().hasFeature(Window.FEATURE_ACTION_BAR));
        callbackContext.success(result);
        return true;
    }

    final ActionBar bar = ctx.getActionBar();
    if (bar == null) {
        Window window = ctx.getWindow();
        if (!window.hasFeature(Window.FEATURE_ACTION_BAR)) {
            callbackContext
                    .error("ActionBar feature not available, Window.FEATURE_ACTION_BAR must be enabled!");
        } else {
            callbackContext.error("Failed to get ActionBar");
        }

        return true;
    }

    if (menu == null) {
        callbackContext.error("Options menu not initialised");
        return true;
    }

    final StringBuffer error = new StringBuffer();
    JSONObject result = new JSONObject();

    if ("isShowing".equals(action)) {
        result.put("value", bar.isShowing());
    } else if ("getHeight".equals(action)) {
        result.put("value", bar.getHeight());
    } else if ("getDisplayOptions".equals(action)) {
        result.put("value", bar.getDisplayOptions());
    } else if ("getNavigationMode".equals(action)) {
        result.put("value", bar.getNavigationMode());
    } else if ("getSelectedNavigationItem".equals(action)) {
        result.put("value", bar.getSelectedNavigationIndex());
    } else if ("getSubtitle".equals(action)) {
        result.put("value", bar.getSubtitle());
    } else if ("getTitle".equals(action)) {
        result.put("value", bar.getTitle());
    } else {
        try {
            JSONException exception = new Runnable() {
                public JSONException exception = null;

                public void run() {
                    try {
                        // This is a bit of a hack (should be specific to the request, not global)
                        bases = new String[] { removeFilename(webView.getOriginalUrl()),
                                removeFilename(webView.getUrl()) };

                        if ("show".equals(action)) {
                            bar.show();
                        } else if ("hide".equals(action)) {
                            bar.hide();
                        } else if ("setMenu".equals(action)) {
                            if (args.isNull(0)) {
                                error.append("menu can not be null");
                                return;
                            }

                            menu_definition = args.getJSONArray(0);

                            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB) {
                                ctx.invalidateOptionsMenu();
                            }
                        } else if ("setTabs".equals(action)) {
                            if (args.isNull(0)) {
                                error.append("menu can not be null");
                                return;
                            }

                            bar.removeAllTabs();
                            tab_callbacks.clear();

                            if (!buildTabs(bar, args.getJSONArray(0))) {
                                error.append("Invalid tab bar definition");
                            }
                        } else if ("setDisplayHomeAsUpEnabled".equals(action)) {
                            if (args.isNull(0)) {
                                error.append("showHomeAsUp can not be null");
                                return;
                            }

                            bar.setDisplayHomeAsUpEnabled(args.getBoolean(0));
                        } else if ("setDisplayOptions".equals(action)) {
                            if (args.isNull(0)) {
                                error.append("options can not be null");
                                return;
                            }

                            final int options = args.getInt(0);
                            bar.setDisplayOptions(options);
                        } else if ("setDisplayShowHomeEnabled".equals(action)) {
                            if (args.isNull(0)) {
                                error.append("showHome can not be null");
                                return;
                            }

                            bar.setDisplayShowHomeEnabled(args.getBoolean(0));
                        } else if ("setDisplayShowTitleEnabled".equals(action)) {
                            if (args.isNull(0)) {
                                error.append("showTitle can not be null");
                                return;
                            }

                            bar.setDisplayShowTitleEnabled(args.getBoolean(0));
                        } else if ("setDisplayUseLogoEnabled".equals(action)) {
                            if (args.isNull(0)) {
                                error.append("useLogo can not be null");
                                return;
                            }

                            bar.setDisplayUseLogoEnabled(args.getBoolean(0));
                        } else if ("setHomeButtonEnabled".equals(action)) {
                            if (args.isNull(0)) {
                                error.append("enabled can not be null");
                                return;
                            }

                            bar.setHomeButtonEnabled(args.getBoolean(0));
                        } else if ("setIcon".equals(action)) {
                            if (args.isNull(0)) {
                                error.append("icon can not be null");
                                return;
                            }

                            Drawable drawable = getDrawableForURI(args.getString(0));
                            bar.setIcon(drawable);
                        } else if ("setListNavigation".equals(action)) {
                            JSONArray items = null;
                            if (args.isNull(0) == false) {
                                items = args.getJSONArray(0);
                            }

                            navigation_adapter.setItems(items);
                            bar.setListNavigationCallbacks(navigation_adapter, navigation_listener);
                        } else if ("setLogo".equals(action)) {
                            if (args.isNull(0)) {
                                error.append("logo can not be null");
                                return;
                            }

                            Drawable drawable = getDrawableForURI(args.getString(0));
                            bar.setLogo(drawable);
                        } else if ("setNavigationMode".equals(action)) {
                            if (args.isNull(0)) {
                                error.append("mode can not be null");
                                return;
                            }

                            final int mode = args.getInt(0);
                            bar.setNavigationMode(mode);
                        } else if ("setSelectedNavigationItem".equals(action)) {
                            if (args.isNull(0)) {
                                error.append("position can not be null");
                                return;
                            }

                            bar.setSelectedNavigationItem(args.getInt(0));
                        } else if ("setSubtitle".equals(action)) {
                            if (args.isNull(0)) {
                                error.append("subtitle can not be null");
                                return;
                            }

                            bar.setSubtitle(args.getString(0));
                        } else if ("setTitle".equals(action)) {
                            if (args.isNull(0)) {
                                error.append("title can not be null");
                                return;
                            }

                            bar.setTitle(args.getString(0));
                        }
                    } catch (JSONException e) {
                        exception = e;
                    } finally {
                        synchronized (this) {
                            this.notify();
                        }
                    }
                }

                // Run task synchronously
                {
                    synchronized (this) {
                        ctx.runOnUiThread(this);
                        this.wait();
                    }
                }
            }.exception;

            if (exception != null) {
                throw exception;
            }
        } catch (InterruptedException e) {
            error.append("Function interrupted on UI thread");
        }
    }

    if (error.length() == 0) {
        if (result.length() > 0) {
            callbackContext.success(result);
        } else {
            callbackContext.success();
        }
    } else {
        callbackContext.error(error.toString());
    }

    return true;
}

From source file:com.juick.android.MessagesFragment.java

public void lastPrepareMessages(final List<JuickMessage> list, final Runnable then) {
    databaseGetter.getService(new Utils.ServiceGetter.Receiver<DatabaseService>() {
        @Override/*w w  w. jav a  2 s .  c  o  m*/
        public void withService(final DatabaseService service) {
            new Thread("processLastReads cont") {
                @Override
                public void run() {
                    for (JuickMessage juickMessage : list) {
                        // we can use service inside here, because getMessageReadStatus0 is thread-safe
                        final DatabaseService.MessageReadStatus messageReadStatus0 = service
                                .getMessageReadStatus0(juickMessage.getMID());
                        if (messageReadStatus0.read) {
                            juickMessage.read = true;
                            juickMessage.readComments = messageReadStatus0.nreplies;
                        }
                    }

                    final Activity act = getActivity();

                    if (act != null) {
                        if (sp.getBoolean("text_accelerated", false)) {
                            // accelerate text draw

                            final Bitmap bm = Bitmap.createBitmap(10, 10, Bitmap.Config.ALPHA_8);
                            while (MessagesFragment.this.getView().getMeasuredWidth() == 0) {
                                try {
                                    Thread.sleep(100);
                                } catch (InterruptedException e) {
                                    e.printStackTrace(); //To change body of catch statement use File | Settings | File Templates.
                                }
                            }

                            TextView tv = new TextView(act);
                            tv.setTextSize(JuickMessagesAdapter.getTextSize(act));
                            MainActivity.restyleChildrenOrWidget(tv);
                            final int outerViewWidth = MessagesFragment.this.getView().getMeasuredWidth();
                            final int width = outerViewWidth - 6;
                            tv.setWidth(width);
                            tv.setLayoutParams(new ViewGroup.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT,
                                    ViewGroup.LayoutParams.WRAP_CONTENT));
                            final ArrayList<JuickMessagesAdapter.CanvasPainter> stuff = new ArrayList<JuickMessagesAdapter.CanvasPainter>();

                            Canvas canvas = new Canvas(bm) {
                                @Override
                                public void drawText(char[] text, int index, int count, float x, float y,
                                        Paint paint) {
                                    super.drawText(text, index, count, x, y, paint); //To change body of overridden methods use File | Settings | File Templates.
                                }

                                @Override
                                public void drawText(String text, float x, float y, Paint paint) {
                                    super.drawText(text, x, y, paint); //To change body of overridden methods use File | Settings | File Templates.
                                }

                                @Override
                                public void drawText(String text, int start, int end, float x, float y,
                                        Paint paint) {
                                    super.drawText(text, start, end, x, y, paint); //To change body of overridden methods use File | Settings | File Templates.
                                }

                                @Override
                                public void drawText(CharSequence text, int start, int end, float x, float y,
                                        Paint paint) {
                                    super.drawText(text, start, end, x, y, paint); //To change body of overridden methods use File | Settings | File Templates.
                                }

                                @Override
                                public void drawVertices(VertexMode mode, int vertexCount, float[] verts,
                                        int vertOffset, float[] texs, int texOffset, int[] colors,
                                        int colorOffset, short[] indices, int indexOffset, int indexCount,
                                        Paint paint) {
                                    super.drawVertices(mode, vertexCount, verts, vertOffset, texs, texOffset,
                                            colors, colorOffset, indices, indexOffset, indexCount, paint); //To change body of overridden methods use File | Settings | File Templates.
                                }

                                @Override
                                public void drawPosText(char[] text, int index, int count, float[] pos,
                                        Paint paint) {
                                    super.drawPosText(text, index, count, pos, paint); //To change body of overridden methods use File | Settings | File Templates.
                                }

                                @Override
                                public void drawPosText(String text, float[] pos, Paint paint) {
                                    super.drawPosText(text, pos, paint); //To change body of overridden methods use File | Settings | File Templates.
                                }

                                @Override
                                public void drawTextOnPath(char[] text, int index, int count, Path path,
                                        float hOffset, float vOffset, Paint paint) {
                                    super.drawTextOnPath(text, index, count, path, hOffset, vOffset, paint); //To change body of overridden methods use File | Settings | File Templates.
                                }

                                @Override
                                public void drawTextOnPath(String text, Path path, float hOffset, float vOffset,
                                        Paint paint) {
                                    super.drawTextOnPath(text, path, hOffset, vOffset, paint); //To change body of overridden methods use File | Settings | File Templates.
                                }

                                public void drawTextRun(final CharSequence text, final int start, final int end,
                                        final int contextStart, final int contextEnd, final float x,
                                        final float y, final int dir, final Paint paint) {
                                    stuff.add(new JuickMessagesAdapter.CanvasPainter() {

                                        Paint paintClone = getPaintFromCache(paint);

                                        @Override
                                        public void paintOnCanvas(Canvas c, Paint workPaint) {
                                            try {
                                                drawTextRun.invoke(c, text, start, end, contextStart,
                                                        contextEnd, x, y, dir, paintClone);
                                            } catch (Throwable t) {
                                            }
                                        }
                                    });
                                }

                                @Override
                                public boolean getClipBounds(Rect bounds) {
                                    bounds.top = 0;
                                    bounds.bottom = 100000;
                                    bounds.left = 0;
                                    bounds.right = width;
                                    return true;
                                }
                            };

                            for (JuickMessage juickMessage : list) {
                                JuickMessagesAdapter.ParsedMessage pm = (JuickMessagesAdapter.ParsedMessage) juickMessage.parsedText;
                                if (pm != null && pm.textContent != null)
                                    tv.setText(pm.textContent);
                                stuff.clear();
                                tv.measure(View.MeasureSpec.makeMeasureSpec(width, View.MeasureSpec.EXACTLY),
                                        View.MeasureSpec.makeMeasureSpec(0, View.MeasureSpec.UNSPECIFIED));
                                tv.draw(canvas);
                                if (stuff.size() > 0) {
                                    juickMessage.parsedUI = new JuickMessagesAdapter.RenderedText(
                                            outerViewWidth, tv.getMeasuredHeight(),
                                            new ArrayList<JuickMessagesAdapter.CanvasPainter>(stuff));
                                } else {
                                    juickMessage.parsedUI = null;
                                }
                            }
                        }
                        act.runOnUiThread(then);
                    }
                }
            }.start();
        }
    });
}