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:org.solovyev.android.Threads.java

/**
 * Method tries to run <var>runnable</var> on UI thread. Run can be failed if:
 * 1. Specified <var>activity</var> is null
 * 2. Specified <var>activity</var> is finishing
 *
 * @param activity activity bound to runnable
 * @param runnable runnable to bve executed
 *//*from   w w w.  j  a v  a  2  s.co  m*/
public static void tryRunOnUiThread(@Nullable final Activity activity, @Nonnull final Runnable runnable) {
    if (activity != null && !activity.isFinishing()) {
        if (isUiThread()) {
            runnable.run();
        } else {
            activity.runOnUiThread(new Runnable() {
                @Override
                public void run() {
                    // some time may pass and activity might be closing
                    if (!activity.isFinishing()) {
                        runnable.run();
                    }
                }
            });
        }
    }
}

From source file:Main.java

public static final void toastMessage(final Activity activity, final String message, String logLevel) {
    if ("w".equals(logLevel)) {
        Log.w("sdkDemo", message);
    } else if ("e".equals(logLevel)) {
        Log.e("sdkDemo", message);
    } else {//from  w ww. j a v  a  2  s. co  m
        Log.d("sdkDemo", message);
    }
    activity.runOnUiThread(new Runnable() {
        @Override
        public void run() {
            // TODO Auto-generated method stub
            if (mToast != null) {
                mToast.cancel();
                mToast = null;
            }
            mToast = Toast.makeText(activity, message, Toast.LENGTH_SHORT);
            mToast.show();
        }
    });
}

From source file:Main.java

public static boolean getBrightness(final Activity activity, float brightness) {
    final WindowManager.LayoutParams layoutParams = activity.getWindow().getAttributes();
    layoutParams.screenBrightness = brightness;

    if (isUIThread())
        activity.getWindow().setAttributes(layoutParams);
    else//from w  w  w.ja  v  a 2  s .  c o  m
        activity.runOnUiThread(new Runnable() {

            @Override
            public void run() {
                activity.getWindow().setAttributes(layoutParams);

            }
        });

    return false;

}

From source file:com.tum.atse.Utils.java

/**
 * Called if the device does not have Google Play Services installed.
 *///from   w ww  . j a  va 2 s .  c o m
public static void showGooglePlayServicesAvailabilityErrorDialog(final Activity activity,
        final int connectionStatusCode) {
    final int REQUEST_GOOGLE_PLAY_SERVICES = 0;
    activity.runOnUiThread(new Runnable() {
        @Override
        public void run() {
            Dialog dialog = GooglePlayServicesUtil.getErrorDialog(connectionStatusCode, activity,
                    REQUEST_GOOGLE_PLAY_SERVICES);
            dialog.show();
        }
    });
}

From source file:net.vexelon.myglob.utils.Utils.java

/**
 * Display alert dialog using string message
 * @param context/*  w  ww.  j a  v  a  2s . c  o  m*/
 * @param message
 * @param titleResId
 */
public static void showAlertDialog(Activity activity, String message, String title) {
    final Activity act = activity;
    final String s1 = message, s2 = title;
    activity.runOnUiThread(new Runnable() {

        @Override
        public void run() {
            AlertDialog alert = createAlertDialog(act, s1, s2);
            alert.show();
        }
    });
}

From source file:fr.cph.chicago.util.Util.java

/**
 * Function to show settings alert dialog
 *//*from  w  w  w .j  ava  2s . c  om*/
static void showSettingsAlert(@NonNull final Activity activity) {
    new Thread() {
        public void run() {
            activity.runOnUiThread(() -> {
                final AlertDialog.Builder alertDialogBuilder = new AlertDialog.Builder(activity);
                alertDialogBuilder.setTitle("GPS settings");
                alertDialogBuilder.setMessage(
                        "GPS is not enabled. Do you want to go to settings main.java.fr.cph.chicago.res.menu?");
                alertDialogBuilder.setCancelable(false).setPositiveButton("Yes", (dialog, id) -> {
                    final Intent intent = new Intent(Settings.ACTION_LOCATION_SOURCE_SETTINGS);
                    activity.startActivity(intent);
                }).setNegativeButton("No", (dialog, id) -> dialog.cancel());
                final AlertDialog alertDialog = alertDialogBuilder.create();
                alertDialog.show();
            });
        }
    }.start();
}

From source file:com.google.unity.AdMobPlugin.java

/**
 * Creates an {@link AdView} to old ads.
 *
 * @param activity The activity to place the {@code AdView}.
 * @param publisherId Your publisher ID from the AdMob or DFP console
 * @param adSizeString A string ad size constant representing  the desired ad size.
 * @param positionAtTop True to position the ad at the top of the screen. False to position
 *     the ad at the bottom of the screen.
 *///from  ww w  .ja v  a2  s .c om
public static void createBannerView(final Activity activity, final String publisherId,
        final String adSizeString, final boolean positionAtTop) {
    Log.d(LOGTAG, "called createBannerView in Java code");
    final AdMobPlugin plugin = AdMobPlugin.instance();
    plugin.activity = activity;
    activity.runOnUiThread(new Runnable() {
        @Override
        public void run() {
            AdSize adSize = AdMobPlugin.adSizeFromSize(adSizeString);
            if (adSize == null) {
                Log.e(AdMobPlugin.LOGTAG, "AdSize is null. Did you use an AdSize constant?");
                return;
            }
            plugin.adView = new AdView(activity, adSize, publisherId);
            plugin.adView.setAdListener(plugin);
            LinearLayout layout = new LinearLayout(activity);
            FrameLayout.LayoutParams layoutParams = new FrameLayout.LayoutParams(
                    FrameLayout.LayoutParams.FILL_PARENT, FrameLayout.LayoutParams.WRAP_CONTENT);
            layoutParams.gravity = positionAtTop ? Gravity.TOP : Gravity.BOTTOM;
            activity.addContentView(layout, layoutParams);
            LinearLayout.LayoutParams adParams = new LinearLayout.LayoutParams(
                    LinearLayout.LayoutParams.FILL_PARENT, LinearLayout.LayoutParams.FILL_PARENT);
            layout.addView(plugin.adView, adParams);
        }
    });
}

From source file:longism.com.api.APIUtils.java

/**
 * TODO Function:Load json by type.<br>
 *
 * @param activity    - to get context//from   w  ww .j a va  2s . c  om
 * @param action      - get or post or s.thing else. Define at top of class
 * @param data        - Parameter
 * @param url         - host of API
 * @param apiCallBack - call back to handle action when start, finish, success or fail
 * @param username    - username if sever need to log in
 * @param password    - password if sever need to log in
 * @date: July 07, 2015
 * @author: Nguyen Long
 */
public static void LoadJSONByType(final Activity activity, final int action, final HashMap<String, String> data,
        final String url, final String username, final String password, final APICallBack apiCallBack) {
    activity.runOnUiThread(new Runnable() {
        @Override
        public void run() {
            apiCallBack.uiStart();
        }
    });
    new Thread(new Runnable() {
        @Override
        public synchronized void run() {
            try {
                HttpGet get = null;
                HttpPost post = null;
                HttpResponse response = null;
                String paramString = null;

                ArrayList<BasicNameValuePair> list = new ArrayList<BasicNameValuePair>();
                if (data != null) {
                    Set<String> set = data.keySet();
                    for (String key : set) {
                        BasicNameValuePair value = new BasicNameValuePair(key, data.get(key));
                        list.add(value);
                    }
                }
                HttpParams params = new BasicHttpParams();
                HttpConnectionParams.setSoTimeout(params, TIMEOUT_TIME);
                HttpConnectionParams.setConnectionTimeout(params, TIMEOUT_TIME);

                DefaultHttpClient client = new DefaultHttpClient(params);

                /**
                 * Select action to do
                 */
                switch (action) {
                case ACTION_GET_JSON:
                    paramString = URLEncodedUtils.format(list, "utf-8");
                    get = new HttpGet(url + "?" + paramString);
                    response = client.execute(get);
                    break;
                case ACTION_POST_JSON:
                    post = new HttpPost(url);
                    post.setEntity(new UrlEncodedFormEntity(list, "UTF-8"));
                    response = client.execute(post);
                    break;
                case ACTION_GET_JSON_WITH_AUTH:
                    paramString = URLEncodedUtils.format(list, "utf-8");
                    get = new HttpGet(url + "?" + paramString);
                    setAuthenticate(client, get, username, password);
                    response = client.execute(get);
                    break;
                case ACTION_POST_JSON_WITH_AUTH:
                    post = new HttpPost(url);
                    post.setEntity(new UrlEncodedFormEntity(list, "UTF-8"));
                    setAuthenticate(client, post, username, password);
                    response = client.execute(post);
                    break;
                }

                final StringBuilder builder = new StringBuilder();
                if (response != null && response.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {

                    InputStream inputStream = response.getEntity().getContent();
                    Scanner scanner = new Scanner(inputStream);
                    while (scanner.hasNext()) {
                        builder.append(scanner.nextLine());
                    }
                    inputStream.close();
                    scanner.close();
                    apiCallBack.success(builder.toString(), 0);
                } else {
                    apiCallBack.fail(response != null && response.getStatusLine() != null ? "response null"
                            : "" + response.getStatusLine().getStatusCode());
                }
            } catch (final Exception e) {
                apiCallBack.fail(e.getMessage());
            } finally {
                activity.runOnUiThread(new Runnable() {

                    @Override
                    public void run() {
                        apiCallBack.uiEnd();
                    }
                });
            }
        }
    }).start();
}

From source file:fi.mikuz.boarder.util.FileProcessor.java

private static void notify(final Activity activity, final String text) {
    activity.runOnUiThread(new Runnable() {
        public void run() {
            AlertDialog.Builder builder = new AlertDialog.Builder(activity);
            builder.setMessage(text);/*www  .ja v  a  2  s.  c om*/
            builder.show();
        }
    });
}

From source file:longism.com.api.APIUtils.java

/**
 * TODO Function:Upload file then Load json by type POST.<br>
 *
 * @param activity    - to get context//from   w  w w. j  a  va  2s .  c  o  m
 * @param action      - need authenticate or not, define at top of class
 * @param data        - parameter String
 * @param files       - param file input <key,path of file>
 * @param url         - host of API
 * @param apiCallBack - call back to handle action when start, finish, success or fail
 * @date: July 07, 2015
 * @author: Nguyen Long
 */
public static void loadJSONWithUploadFile(final Activity activity, final int action,
        final HashMap<String, String> data, final HashMap<String, String> files, final String url,
        final String sUserName, final String sUserPassword, final APICallBack apiCallBack) {

    activity.runOnUiThread(new Runnable() {
        @Override
        public void run() {
            apiCallBack.uiStart();
        }
    });
    new Thread(new Runnable() {
        @Override
        public synchronized void run() {
            try {
                HttpParams params = new BasicHttpParams();
                HttpConnectionParams.setSoTimeout(params, TIMEOUT_TIME);
                HttpConnectionParams.setConnectionTimeout(params, TIMEOUT_TIME);
                Charset chars = Charset.forName("UTF-8");
                DefaultHttpClient client = new DefaultHttpClient(params);
                HttpPost post = new HttpPost(url);
                //               DLog.e("Accountant", "url  : " + url);
                MultipartEntity multipartEntity = new MultipartEntity();
                if (files != null) {
                    Set<String> set = files.keySet();
                    for (String key : set) {
                        //                     DLog.e("Accountant", "param  : " + key);
                        File file = new File(files.get(key));
                        multipartEntity.addPart(key, new FileBody(file));
                    }
                }
                if (data != null) {
                    Set<String> set = data.keySet();
                    for (String key : set) {
                        //                     DLog.e("Accountant", "param  : " + key);
                        StringBody stringBody = new StringBody(data.get(key), chars);
                        multipartEntity.addPart(key, stringBody);
                    }

                }
                post.setEntity(multipartEntity);
                /**
                 * if need authen then run this code below
                 */
                if (action == ACTION_UPLOAD_WITH_AUTH) {
                    setAuthenticate(client, post, sUserName, sUserPassword);
                }

                HttpResponse response = null;
                response = client.execute(post);
                final StringBuilder builder = new StringBuilder();
                if (response != null && response.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {

                    InputStream inputStream = response.getEntity().getContent();
                    Scanner scanner = new Scanner(inputStream);
                    while (scanner.hasNext()) {
                        builder.append(scanner.nextLine());
                    }
                    inputStream.close();
                    scanner.close();
                    apiCallBack.success(builder.toString(), 0);
                } else {
                    apiCallBack.fail(response != null && response.getStatusLine() != null ? "response null"
                            : "" + response.getStatusLine().getStatusCode());
                }
            } catch (final Exception e) {
                apiCallBack.fail(e.getMessage());
            } finally {
                activity.runOnUiThread(new Runnable() {

                    @Override
                    public void run() {
                        apiCallBack.uiEnd();
                    }
                });
            }
        }
    }).start();
}