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.juick.android.MessagesFragment.java

private void init(final boolean moveToTop) {
    if (implicitlyCreated)
        return;/*from  w  ww.  ja v a 2  s  .  co  m*/

    parent.imagePreviewHelper = listAdapter.imagePreviewHelper = new ImagePreviewHelper(
            (ViewGroup) getView().findViewById(R.id.imagepreview_container), parent);

    final MessageListBackingData savedMainList = JuickAdvancedApplication.instance.getSavedList(getActivity());
    final ListView lv = getListView();
    boolean canUseMainList = getActivity() instanceof MainActivity; //
    if (savedMainList != null && canUseMainList) {
        messagesSource = savedMainList.messagesSource;
        initListWithMessages(savedMainList.messages);
        int selectItem = 0;
        ListAdapter wrappedAdapter = lv.getAdapter();
        for (int i = 0; i < wrappedAdapter.getCount(); i++) {
            Object ai = wrappedAdapter.getItem(i);
            if (ai != null && ai instanceof JuickMessage) {
                if (((JuickMessage) ai).getMID().equals(savedMainList.topMessageId)) {
                    selectItem = i;
                }
            }
        }
        lv.setSelectionFromTop(selectItem, savedMainList.topMessageScrollPos);
        JuickAdvancedApplication.instance.setSavedList(null, false);
    } else {
        final MessagesLoadNotification messagesLoadNotification = new MessagesLoadNotification(getActivity(),
                handler);
        Thread thr = new Thread("Download messages (init)") {

            public void run() {
                final MessagesLoadNotification notification = messagesLoadNotification;
                final Utils.Function<Void, RetainedData> then = new Utils.Function<Void, RetainedData>() {
                    @Override
                    public Void apply(final RetainedData mespos) {
                        handler.post(new Runnable() {
                            @Override
                            public void run() {
                                notification.statusText.setText("Filter and format..");
                            }
                        });
                        Log.w("com.juick.advanced", "getFirst: before filter");
                        final ArrayList<JuickMessage> messages = filterMessages(mespos.messages);
                        Log.w("com.juick.advanced", "getFirst: after filter");
                        Boolean ownView = null;
                        if (!JuickMessagesAdapter.dontKeepParsed(parent)) {
                            for (JuickMessage juickMessage : messages) {
                                if (ownView == null) {
                                    MicroBlog blog = MainActivity.microBlogs
                                            .get(juickMessage.getMID().getMicroBlogCode());
                                    ownView = blog instanceof OwnRenderItems;
                                }
                                if (!ownView) {
                                    juickMessage.parsedText = JuickMessagesAdapter.formatMessageText(parent,
                                            juickMessage, false);
                                }
                            }
                        }
                        final Parcelable listPosition = mespos.viewState;
                        if (isAdded()) {
                            if (messages.size() == 0) {
                                handler.post(new Runnable() {
                                    @Override
                                    public void run() {
                                        if (notification.lastError == null) {
                                            notification.statusText
                                                    .setText(parent.getString(R.string.EmptyList));
                                        } else {
                                            notification.statusText.setText(
                                                    "Error obtaining messages: " + notification.lastError);

                                        }
                                        notification.progressBar.setVisibility(View.GONE);
                                    }
                                });
                            }
                            final Activity activity = getActivity();
                            if (activity != null) {
                                final Parcelable finalListPosition = listPosition;
                                activity.runOnUiThread(new Runnable() {

                                    public void run() {
                                        try {
                                            if (isAdded()) {
                                                lastPrepareMessages(messages, new Runnable() {
                                                    @Override
                                                    public void run() {
                                                        if (!hasListView()) {
                                                            handler.postDelayed(this, 300);
                                                            return;
                                                        }
                                                        initListWithMessages(messages);
                                                        if (moveToTop) {
                                                            lv.setSelection(0);
                                                        } else {
                                                            if (finalListPosition != null) {
                                                                lv.onRestoreInstanceState(finalListPosition);
                                                            } else {
                                                                //setSelection(messagesSource.supportsBackwardRefresh() ? 1 : 0);
                                                                setSelection(0);
                                                            }
                                                        }
                                                        Log.w("com.juick.advanced", "getFirst: end.");
                                                        handler.postDelayed(new Runnable() {
                                                            @Override
                                                            public void run() {
                                                                onListLoaded();
                                                            }
                                                        }, 10);
                                                    }
                                                });
                                            }
                                        } catch (IllegalStateException e) {
                                            Toast.makeText(activity, e.toString(), Toast.LENGTH_LONG).show();
                                        }
                                    }
                                });
                            }
                        } else {
                            Log.w("com.juick.advanced", "getFirst: not added!");
                        }
                        return null;
                    }
                };
                if (getActivity() != null)
                    messagesSource.setContext(getActivity());
                if (restoreData == null) {
                    messagesSource.getFirst(notification, new Utils.Function<Void, ArrayList<JuickMessage>>() {
                        @Override
                        public Void apply(ArrayList<JuickMessage> juickMessages) {
                            return then.apply(new RetainedData(juickMessages, null));
                        }
                    });
                } else {
                    then.apply((RetainedData) restoreData);
                    restoreData = null;
                }
            }
        };
        thr.setPriority(Thread.MIN_PRIORITY);
        thr.start();
    }
}

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 2  s. c  o m*/
 */
public static void sendFilesTo(final Activity fromActivity, final Intent intent) {
    if (Matrix.getMXSessions(fromActivity).size() == 1) {
        sendFilesTo(fromActivity, intent, Matrix.getMXSession(fromActivity, null));
    } else if (fromActivity instanceof FragmentActivity) {
        FragmentManager fm = ((FragmentActivity) fromActivity).getSupportFragmentManager();

        AccountsSelectionDialogFragment fragment = (AccountsSelectionDialogFragment) fm
                .findFragmentByTag(MXCActionBarActivity.TAG_FRAGMENT_ACCOUNT_SELECTION_DIALOG);
        if (fragment != null) {
            fragment.dismissAllowingStateLoss();
        }

        fragment = AccountsSelectionDialogFragment.newInstance(Matrix.getMXSessions(fromActivity));

        fragment.setListener(new AccountsSelectionDialogFragment.AccountsListener() {
            @Override
            public void onSelected(final MXSession session) {
                fromActivity.runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        sendFilesTo(fromActivity, intent, session);
                    }
                });
            }
        });

        fragment.show(fm, MXCActionBarActivity.TAG_FRAGMENT_ACCOUNT_SELECTION_DIALOG);
    }
}

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

@Override
public void onViewCreated(View view, Bundle savedInstanceState) {
    super.onViewCreated(view, savedInstanceState);

    LayoutInflater li = (LayoutInflater) getActivity().getSystemService(Context.LAYOUT_INFLATER_SERVICE);

    viewLoading = li.inflate(R.layout.listitem_loading, null);
    if (!messagesSource.canNext()) {
        viewLoading.findViewById(R.id.loadingg).setVisibility(View.GONE);
        viewLoading.findViewById(R.id.end_of_messages).setVisibility(View.VISIBLE);
        viewLoading.findViewById(R.id.progress_bar).setVisibility(View.GONE);
        viewLoading.findViewById(R.id.progress_loading_more).setVisibility(View.GONE);
    }// w  ww  .ja v a2s.c  o m

    mRefreshView = (RelativeLayout) li.inflate(R.layout.pull_to_refresh_header, null);
    mRefreshViewText = (TextView) mRefreshView.findViewById(R.id.pull_to_refresh_text);
    mRefreshViewImage = (ImageView) mRefreshView.findViewById(R.id.pull_to_refresh_image);
    mRefreshViewProgress = (ProgressBar) mRefreshView.findViewById(R.id.pull_to_refresh_progress);
    mRefreshViewImage.setMinimumHeight(50);
    mRefreshView.setOnClickListener(this);
    mRefreshOriginalTopPadding = mRefreshView.getPaddingTop();
    mRefreshState = TAP_TO_REFRESH;

    final ListView listView = getListView();
    listView.setBackgroundDrawable(null);
    listView.setScrollBarStyle(View.SCROLLBARS_OUTSIDE_OVERLAY);
    installDividerColor(listView);
    MainActivity.restyleChildrenOrWidget(listView);

    listAdapter = new JuickMessagesAdapter(getActivity(), this, JuickMessagesAdapter.TYPE_MESSAGES,
            allMessages ? JuickMessagesAdapter.SUBTYPE_ALL : JuickMessagesAdapter.SUBTYPE_OTHER);

    listAdapter.setOnForgetListener(new Utils.Function<Void, JuickMessage>() {
        @Override
        public Void apply(final JuickMessage jm) {
            Network.executeJAHTTPS(
                    getActivity(), null, JA_API_URL + "/pending?command=ignore&mid="
                            + ((JuickMessageID) jm.getMID()).getMid() + "&rid=" + jm.getRID(),
                    new Utils.Function<Void, RESTResponse>() {
                        @Override
                        public Void apply(final RESTResponse response) {
                            final Activity activity = getActivity();
                            if (activity == null)
                                return null; // gone.
                            if (response.getErrorText() != null) {
                                activity.runOnUiThread(new Runnable() {
                                    @Override
                                    public void run() {
                                        Toast.makeText(activity, response.getErrorText(), Toast.LENGTH_SHORT)
                                                .show();
                                    }
                                });
                            } else {
                                activity.runOnUiThread(new Runnable() {
                                    @Override
                                    public void run() {
                                        listAdapter.remove(jm);
                                        //To change body of implemented methods use File | Settings | File Templates.
                                        if (listAdapter.getCount() == 0) {
                                            if ((activity instanceof MainActivity)) {
                                                ((MainActivity) activity).doReload();
                                            }
                                        }
                                    }
                                });
                            }
                            return null;
                        }
                    });
            return null;
        }
    });
    listView.setOnTouchListener(this);
    listView.setOnScrollListener(this);
    listView.setOnItemClickListener(this);

    listView.setOnItemLongClickListener(new AdapterView.OnItemLongClickListener() {
        @Override
        public boolean onItemLongClick(final AdapterView<?> parent, final View view, final int position,
                final long id) {
            if (view instanceof ImageGallery) {
                return false; // no need that! (possibly, make this condition work only if not scrolled meanwhile)
            }
            final Object itemAtPosition = parent.getItemAtPosition(position);
            if (itemAtPosition instanceof JuickMessage) {
                doOnClickActualTime = System.currentTimeMillis();
                doOnClick = new Runnable() {
                    @Override
                    public void run() {
                        JuickMessage msg = (JuickMessage) itemAtPosition;
                        MessageMenu messageMenu = MainActivity.getMicroBlog(msg).getMessageMenu(getActivity(),
                                messagesSource, listView, listAdapter);
                        if (messageMenu != null) {
                            messageMenu.onItemLongClick(parent, view, position, id);
                        } else {
                            Toast.makeText(getActivity(), "Not implemented ;-(", Toast.LENGTH_LONG).show();
                        }
                    }
                };
                if (alternativeLongClick) {
                    listView.performHapticFeedback(HapticFeedbackConstants.LONG_PRESS);
                } else {
                    doOnClick.run();
                    doOnClick = null;
                    return true;
                }
            }
            return false;
        }
    });
    listView.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
        @Override
        public void onItemSelected(AdapterView<?> adapterView, View view, int i, long l) {
            System.out.println();
        }

        @Override
        public void onNothingSelected(AdapterView<?> adapterView) {
            System.out.println();
        }
    });
    init(false);
    if (parent != null) {
        parent.onFragmentCreated();
    }
}

From source file:connectivity.ClarolineService.java

/**
 * Updates completely the course, loading first the Tool list, then the
 * resources for each tool./*from w ww.  j ava 2s  .  c om*/
 * 
 * @param cours
 *            the course to load
 * @param activity
 *            the calling activity
 * @param handler
 *            the handler to execute after the request
 */
public void updateCompleteCourse(final Cours cours, final Activity activity,
        final AsyncHttpResponseHandler handler) {
    getToolListForCours(cours, new AsyncHttpResponseHandler() {

        @Override
        public void onFinish() {
            handler.onFinish();
        }

        @Override
        public void onSuccess(final String response) {
            mCounter = 0;
            for (ResourceList list : cours.lists()) {
                getResourcesForList(list, new AsyncHttpResponseHandler() {
                    @Override
                    public void onSuccess(final String response) {
                        synchronized (cours) {
                            mCounter++;
                            cours.notify();
                        }
                    }
                });
            }
            new Thread(new Runnable() {

                @Override
                public void run() {
                    try {
                        synchronized (cours) {
                            while (mCounter < cours.lists().size()) {
                                cours.wait();
                            }
                            mCounter = 0;

                        }
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    } finally {
                        if (activity != null) {
                            activity.runOnUiThread(new Runnable() {
                                @Override
                                public void run() {
                                    handler.onSuccess(response);
                                }
                            });
                        }
                    }
                }
            }).start();
        }
    });
}

From source file:es.javocsoft.android.lib.toolbox.ToolBox.java

/**
 * This disables correctly the AdMob ads.
 * // ww w .j  av a2 s.  co  m
 * @param activity
 * @param adLayout   The AdView view.
 */
public static void adMob_hideAds(Activity activity, final AdView adLayout) {
    activity.runOnUiThread(new Runnable() {
        @Override
        public void run() {
            adLayout.setEnabled(false);
            adLayout.setVisibility(View.GONE);
        }
    });
}

From source file:es.javocsoft.android.lib.toolbox.ToolBox.java

/**
 * This enables again the AdMob ads.// w w w.ja v  a  2  s  .c  o m
 * 
 * @param activity
 * @param adLayout   The AdView view.
 */
public static void adMob_showAds(Activity activity, final AdView adLayout) {
    activity.runOnUiThread(new Runnable() {
        @Override
        public void run() {
            adLayout.setEnabled(true);
            adLayout.setVisibility(View.VISIBLE);

            AdRequest.Builder adBuilder = new AdRequest.Builder().addTestDevice(AdRequest.DEVICE_ID_EMULATOR);

            adLayout.loadAd(adBuilder.build());
        }
    });
}

From source file:es.javocsoft.android.lib.toolbox.ToolBox.java

/**
 * This enables again the AdMob ads./*w w  w  .ja  v  a  2s .  c o  m*/
 * 
 * @param activity
 * @param adLayout
 * @param excludedDevices
 */
public static void adMob_showAds(Activity activity, final AdView adLayout, final List<String> excludedDevices) {
    activity.runOnUiThread(new Runnable() {
        @Override
        public void run() {
            adLayout.setEnabled(true);
            adLayout.setVisibility(View.VISIBLE);

            AdRequest.Builder adBuilder = new AdRequest.Builder().addTestDevice(AdRequest.DEVICE_ID_EMULATOR);

            for (String dev : excludedDevices) {
                adBuilder.addTestDevice(dev);
            }

            adLayout.loadAd(adBuilder.build());
        }
    });
}

From source file:jahirfiquitiva.iconshowcase.activities.ViewerActivity.java

private void saveWallpaper(final Activity context, final String wallName, final MaterialDialog downloadDialog,
        final Bitmap result) {
    downloadDialog.setContent(context.getString(R.string.saving_wallpaper));
    new Thread(new Runnable() {
        @Override/* www  .jav  a  2s  . com*/
        public void run() {
            if (mPrefs.getDownloadsFolder() != null) {
                downloadsFolder = new File(mPrefs.getDownloadsFolder());
            } else {
                downloadsFolder = new File(context.getString(R.string.walls_save_location,
                        Environment.getExternalStorageDirectory().getAbsolutePath()));
            }
            //noinspection ResultOfMethodCallIgnored
            downloadsFolder.mkdirs();
            final File destFile = new File(downloadsFolder, wallName + ".png");
            String snackbarText;
            if (!destFile.exists()) {
                try {
                    result.compress(Bitmap.CompressFormat.PNG, 100, new FileOutputStream(destFile));
                    snackbarText = context.getString(R.string.wallpaper_downloaded, destFile.getAbsolutePath());
                } catch (final Exception e) {
                    snackbarText = context.getString(R.string.error);
                }
            } else {
                snackbarText = context.getString(R.string.wallpaper_downloaded, destFile.getAbsolutePath());
            }
            final String finalSnackbarText = snackbarText;
            context.runOnUiThread(new Runnable() {
                @Override
                public void run() {
                    downloadDialog.dismiss();

                    if (toHide1 != null && toHide2 != null) {
                        toHide1.setVisibility(View.GONE);
                        toHide2.setVisibility(View.GONE);
                    }

                    Snackbar longSnackbar = Snackbar.make(layout, finalSnackbarText, Snackbar.LENGTH_LONG);
                    final int snackbarLight = ContextCompat.getColor(context, R.color.snackbar_light);
                    final int snackbarDark = ContextCompat.getColor(context, R.color.snackbar_dark);
                    ViewGroup snackbarView = (ViewGroup) longSnackbar.getView();
                    snackbarView.setBackgroundColor(ThemeUtils.darkTheme ? snackbarDark : snackbarLight);
                    longSnackbar.show();
                    longSnackbar.setCallback(new Snackbar.Callback() {
                        @Override
                        public void onDismissed(Snackbar snackbar, int event) {
                            super.onDismissed(snackbar, event);
                            if (toHide1 != null && toHide2 != null) {
                                toHide1.setVisibility(View.VISIBLE);
                                toHide2.setVisibility(View.VISIBLE);
                            }
                        }
                    });
                }
            });
        }
    }).start();
}

From source file:com.googlecode.networklog.AppFragment.java

protected void getInstalledApps(final boolean refresh) {
    synchronized (groupDataBuffer) {
        synchronized (groupData) {
            groupData.clear();//ww  w  . j a v a2s.com
            groupDataBuffer.clear();

            synchronized (ApplicationsTracker.installedAppsLock) {
                for (ApplicationsTracker.AppEntry app : ApplicationsTracker.installedApps) {
                    if (NetworkLog.state != NetworkLog.State.RUNNING
                            && NetworkLog.initRunner.running == false) {
                        MyLog.d("[AppFragment] Initialization aborted");
                        return;
                    }

                    GroupItem item = new GroupItem();
                    item.app = app;
                    item.lastTimestamp = 0;
                    item.childrenData = new HashMap<String, ChildItem>();
                    item.childrenDataFiltered = new HashMap<String, ChildItem>();
                    if (NetworkLogService.throughputBps) {
                        item.throughputString = "0bps/0bps";
                    } else {
                        item.throughputString = "0B/0B";
                    }
                    groupData.add(item);
                    groupDataBuffer.add(item);
                }
            }

            if (refresh == true) {
                Activity activity = getActivity();

                if (activity != null) {
                    activity.runOnUiThread(new Runnable() {
                        public void run() {
                            preSortData();
                            if (NetworkLog.filterTextInclude.length() > 0
                                    || NetworkLog.filterTextExclude.length() > 0) {
                                setFilter("");
                            } else {
                                refreshAdapter();
                            }
                        }
                    });
                }
            }

            // groupDataBuffer must always be sorted by UID for binary search
            Collections.sort(groupDataBuffer, new SortAppsByUid());
        }
    }
}

From source file:jahirfiquitiva.iconshowcase.activities.WallpaperViewerActivity.java

private void saveWallpaper(final Activity context, final String wallName, final MaterialDialog downloadDialog,
        final Bitmap result) {
    downloadDialog.setContent(context.getString(R.string.saving_wallpaper));
    new Thread(new Runnable() {
        @Override//from   w w w .j  ava2 s . c o  m
        public void run() {
            if (mPrefs.getDownloadsFolder() != null) {
                downloadsFolder = new File(mPrefs.getDownloadsFolder());
            } else {
                downloadsFolder = new File(context.getString(R.string.walls_save_location,
                        Environment.getExternalStorageDirectory().getAbsolutePath()));
            }
            //noinspection ResultOfMethodCallIgnored
            downloadsFolder.mkdirs();
            final File destFile = new File(downloadsFolder, wallName + ".png");
            String snackbarText;
            if (!destFile.exists()) {
                try {
                    result.compress(Bitmap.CompressFormat.PNG, 100, new FileOutputStream(destFile));
                    snackbarText = context.getString(R.string.wallpaper_downloaded, destFile.getAbsolutePath());
                } catch (final Exception e) {
                    snackbarText = context.getString(R.string.error);
                }
            } else {
                snackbarText = context.getString(R.string.wallpaper_downloaded, destFile.getAbsolutePath());
            }
            final String finalSnackbarText = snackbarText;
            context.runOnUiThread(new Runnable() {
                @Override
                public void run() {
                    downloadDialog.dismiss();

                    if (toHide1 != null && toHide2 != null) {
                        toHide1.setVisibility(View.GONE);
                        toHide2.setVisibility(View.GONE);
                    }

                    Utils.snackbar(context, layout, finalSnackbarText, Snackbar.LENGTH_LONG)
                            .setCallback(new Snackbar.Callback() {
                                @Override
                                public void onDismissed(Snackbar snackbar, int event) {
                                    super.onDismissed(snackbar, event);
                                    if (toHide1 != null && toHide2 != null) {
                                        toHide1.setVisibility(View.VISIBLE);
                                        toHide2.setVisibility(View.VISIBLE);
                                    }
                                }
                            }).show();
                }
            });
        }
    }).start();
}