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:jahirfiquitiva.iconshowcase.activities.AltWallpaperViewerActivity.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   ww w .ja  v a 2 s  .c  om*/
        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();
                    Snackbar longSnackbar = Utils.snackbar(AltWallpaperViewerActivity.this, layout,
                            finalSnackbarText, Snackbar.LENGTH_LONG);
                    ViewGroup snackbarView = (ViewGroup) longSnackbar.getView();
                    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
                        snackbarView.setPadding(snackbarView.getPaddingLeft(), snackbarView.getPaddingTop(),
                                snackbarView.getPaddingRight(),
                                Utils.getNavigationBarHeight(AltWallpaperViewerActivity.this));
                    }
                    longSnackbar.show();
                    longSnackbar.setCallback(new Snackbar.Callback() {
                        @Override
                        public void onDismissed(Snackbar snackbar, int event) {
                            super.onDismissed(snackbar, event);
                            reshowFab(fab);
                            setupFullScreen();
                        }
                    });
                }
            });
        }
    }).start();
}

From source file:com.iwuvhugs.seekgame.PhotoFragment.java

/**
 * Capture a still picture. This method should be called when we get a response in
 * {@link #mCaptureCallback} from both {@link #lockFocus()}.
 *//*from  w w  w  .j  a v a2 s  .  c o  m*/
private void captureStillPicture() {
    try {
        final Activity activity = getActivity();
        if (null == activity || null == mCameraDevice) {
            return;
        }
        // This is the CaptureRequest.Builder that we use to take a picture.
        final CaptureRequest.Builder captureBuilder = mCameraDevice
                .createCaptureRequest(CameraDevice.TEMPLATE_STILL_CAPTURE);
        captureBuilder.addTarget(mImageReader.getSurface());

        // Use the same AE and AF modes as the preview.
        captureBuilder.set(CaptureRequest.CONTROL_AF_MODE, CaptureRequest.CONTROL_AF_MODE_CONTINUOUS_PICTURE);
        setAutoFlash(captureBuilder);

        // Orientation
        int rotation = activity.getWindowManager().getDefaultDisplay().getRotation();
        captureBuilder.set(CaptureRequest.JPEG_ORIENTATION, ORIENTATIONS.get(rotation));

        CameraCaptureSession.CaptureCallback CaptureCallback = new CameraCaptureSession.CaptureCallback() {

            @Override
            public void onCaptureCompleted(@NonNull CameraCaptureSession session,
                    @NonNull CaptureRequest request, @NonNull TotalCaptureResult result) {

                //                    showToast("Saved: " + mFile);
                // Send broadcast message
                final Activity activity = getActivity();
                if (activity != null) {
                    activity.runOnUiThread(new Runnable() {
                        @Override
                        public void run() {
                            getActivity().sendBroadcast(new Intent(MainActivity.PHOTO_READY));
                        }
                    });
                }

                Log.i(TAG, "File path: " + mFile.toString());
                unlockFocus();
            }
        };

        mCaptureSession.stopRepeating();
        mCaptureSession.capture(captureBuilder.build(), CaptureCallback, null);
    } catch (CameraAccessException e) {
        e.printStackTrace();
    }
}

From source file:com.stanleyidesis.quotograph.ui.activity.LWQSettingsActivity.java

void setupAddEditQuote() {
    addEditQuote.setAlpha(0f);//from  www .  j  a va  2s .  c o  m
    addEditQuote.setVisibility(View.GONE);
    addEditQuote.setTag(R.id.view_tag_flags, FLAG_HIDE | FLAG_DISABLE);
    addEditQuote.setTag(R.id.view_tag_animator_hide, new Runnable() {
        @Override
        public void run() {
            animateContainer(addEditQuote, true);
        }
    });
    addEditQuote.setTag(R.id.view_tag_animator_reveal, new Runnable() {
        @Override
        public void run() {
            animateContainer(addEditQuote, false);
        }
    });
    new Thread(new Runnable() {
        @Override
        public void run() {
            Activity context = LWQSettingsActivity.this;
            final List<Author> list = Select.from(Author.class).orderBy(NamingHelper.toSQLNameDefault("name"))
                    .list();
            String[] allAuthors = new String[list.size()];
            for (int i = 0; i < list.size(); i++) {
                allAuthors[i] = list.get(i).name;
            }
            final ArrayAdapter<String> authorAdapter = new ArrayAdapter<>(context,
                    R.layout.support_simple_spinner_dropdown_item, allAuthors);
            context.runOnUiThread(new Runnable() {
                @Override
                public void run() {
                    editableAuthor.setAdapter(authorAdapter);
                }
            });
        }
    }).start();
}

From source file:com.com2us.module.inapp.DefaultBilling.java

protected void showPreviousProgressInfoDialog(Activity activity, Runnable runnable) {
    String message;/*from ww  w  .j a v a  2  s. com*/
    String okay;
    String language = this.moduleData.getLanguage();
    String country = this.moduleData.getCountry();
    if (TextUtils.equals("ko", language)) {
        message = "\uc9c0\uae09\ub418\uc9c0 \uc54a\uc740 \uc0c1\ud488\uc774 \uc788\uc2b5\ub2c8\ub2e4. \n\uc7ac \uc9c0\uae09\uc744 \uc2dc\ub3c4\ud569\ub2c8\ub2e4.";
        okay = "\ud655\uc778";
    } else if (TextUtils.equals("fr", language)) {
        message = "Echec de lattribution de certains objets. \nLe processus va recommencer.";
        okay = "OK";
    } else if (TextUtils.equals("de", language)) {
        message = "Nicht erhaltene Items vorhanden. \nVorgang wird wiederholt.";
        okay = "OK";
    } else if (TextUtils.equals("ja", language)) {
        message = "\u652f\u7d66\u3055\u308c\u3066\u306a\u3044\u30a2\u30a4\u30c6\u30e0\u304c\u3042\u308a\u307e\u3059\u3002 \n\u518d\u652f\u7d66\u3044\u305f\u3057\u307e\u3059\u3002";
        okay = "OK";
    } else if (TextUtils.equals("ru", language)) {
        message = "\u041d\u0435 \u0443\u0434\u0430\u043b\u043e\u0441\u044c \u043d\u0430\u0447\u0438\u0441\u043b\u0438\u0442\u044c \u0432\u0441\u0435 \u043f\u0440\u0435\u0434\u043c\u0435\u0442\u044b. \n\u041f\u043e\u043f\u0440\u043e\u0431\u0443\u0435\u043c \u0435\u0449\u0435 \u0440\u0430\u0437.";
        okay = "OK";
    } else if (TextUtils.equals("tw", country)) {
        message = "\u5546\u54c1\u672a\u6210\u529f\u7d66\u4ed8\uff0c \n\u5c07\u5617\u8a66\u91cd\u65b0\u9818\u53d6\u3002";
        okay = "\u78ba\u8a8d";
    } else if (TextUtils.equals("cn", country)) {
        message = "\u5b58\u5728\u672a\u80fd\u652f\u4ed8\u7684\u5546\u54c1\u3002 \n\u5c06\u5c1d\u8bd5\u91cd\u65b0\u652f\u4ed8\u3002";
        okay = "\u786e\u8ba4";
    } else {
        message = "Failed to grant some items. \nThe process will restart.";
        okay = "OK";
    }
    final Activity activity2 = activity;
    final Runnable runnable2 = runnable;
    activity.runOnUiThread(new Runnable() {
        public void run() {
            AlertDialog dialog = new Builder(activity2).setIcon(17301659).setMessage(message)
                    .setPositiveButton(okay, new OnClickListener() {
                        public void onClick(DialogInterface dialog, int whichButton) {
                        }
                    }).create();
            final Activity activity = activity2;
            final Runnable runnable = runnable2;
            dialog.setOnDismissListener(new OnDismissListener() {
                public void onDismiss(DialogInterface dialog) {
                    activity.runOnUiThread(runnable);
                }
            });
            dialog.show();
        }
    });
}

From source file:nya.miku.wishmaster.http.cloudflare.CloudflareChecker.java

private Cookie checkAntiDDOS(final CloudflareException exception, final HttpHost proxy, CancellableTask task,
        final Activity activity) {
    synchronized (lock) {
        if (processing)
            return null;
        processing = true;//from   w  w w .  j  a v  a2  s. co  m
    }
    processing2 = true;
    currentCookie = null;

    if (Build.VERSION.SDK_INT < Build.VERSION_CODES.LOLLIPOP) {
        CookieSyncManager.createInstance(activity);
        CookieManager.getInstance().removeAllCookie();
    } else {
        CompatibilityImpl.clearCookies(CookieManager.getInstance());
    }

    final ViewGroup layout = (ViewGroup) activity.getWindow().getDecorView().getRootView();
    final WebViewClient client = new WebViewClient() {
        @Override
        public void onReceivedSslError(WebView view, SslErrorHandler handler, SslError error) {
            handler.proceed();
        }

        @Override
        public void onPageFinished(WebView webView, String url) {
            super.onPageFinished(webView, url);
            Logger.d(TAG, "Got Page: " + url);
            String value = null;
            try {
                String[] cookies = CookieManager.getInstance().getCookie(url).split("[;]");
                for (String cookie : cookies) {
                    if ((cookie != null) && (!cookie.trim().equals(""))
                            && (cookie.startsWith(" " + exception.getRequiredCookieName() + "="))) {
                        value = cookie.substring(exception.getRequiredCookieName().length() + 2);
                    }
                }
            } catch (NullPointerException e) {
                Logger.e(TAG, e);
            }
            if (value != null) {
                BasicClientCookieHC4 cf_cookie = new BasicClientCookieHC4(exception.getRequiredCookieName(),
                        value);
                cf_cookie.setDomain("." + Uri.parse(url).getHost());
                cf_cookie.setPath("/");
                currentCookie = cf_cookie;
                Logger.d(TAG, "Cookie found: " + value);
                processing2 = false;
            } else {
                Logger.d(TAG, "Cookie is not found");
            }
        }
    };

    activity.runOnUiThread(new Runnable() {
        @SuppressLint("SetJavaScriptEnabled")
        @Override
        public void run() {
            webView = new WebView(activity);
            webView.setVisibility(View.GONE);
            layout.addView(webView);
            webView.setWebViewClient(client);
            webView.getSettings().setUserAgentString(HttpConstants.USER_AGENT_STRING);
            webView.getSettings().setJavaScriptEnabled(true);
            webViewContext = webView.getContext();
            if (proxy != null)
                WebViewProxy.setProxy(webViewContext, proxy.getHostName(), proxy.getPort());
            webView.loadUrl(exception.getCheckUrl());
        }
    });

    long startTime = System.currentTimeMillis();
    while (processing2) {
        long time = System.currentTimeMillis() - startTime;
        if ((task != null && task.isCancelled()) || time > TIMEOUT) {
            processing2 = false;
        }
    }

    activity.runOnUiThread(new Runnable() {
        @Override
        public void run() {
            try {
                layout.removeView(webView);
                webView.stopLoading();
                webView.clearCache(true);
                webView.destroy();
                webView = null;
            } finally {
                if (proxy != null)
                    WebViewProxy.setProxy(webViewContext, null, 0);
                processing = false;
            }
        }
    });

    return currentCookie;
}

From source file:tv.ouya.sdk.OuyaUnityPlugin.java

public static void initOuyaPlugin(final String jsonData) {
    Activity activity = IOuyaActivity.GetActivity();
    if (null != activity) {
        Runnable runnable = new Runnable() {
            public void run() {
                try {
                    if (null == IOuyaActivity.GetActivity()) {
                        Log.e(TAG, "initOuyaPlugin: activity is null");
                        UnityPlayer.UnitySendMessage("OuyaGameObject", "OnFailureInitializePlugin",
                                "Activity is missing");
                        return;
                    }//from   w w w .  j  ava2s .  c  om

                    if (null == IOuyaActivity.GetApplicationKey()) {
                        Log.e(TAG, "initOuyaPlugin: application key is null");
                        UnityPlayer.UnitySendMessage("OuyaGameObject", "OnFailureInitializePlugin",
                                "Application key is missing");
                        return;
                    }

                    Log.i(TAG, "initOuyaPlugin: Initializing plugin");

                    Bundle developerInfo = new Bundle();

                    developerInfo.putByteArray(OuyaFacade.OUYA_DEVELOPER_PUBLIC_KEY,
                            IOuyaActivity.GetApplicationKey());

                    JSONArray jsonArray = new JSONArray(jsonData);
                    for (int index = 0; index < jsonArray.length(); ++index) {
                        JSONObject jsonObject = jsonArray.getJSONObject(index);
                        String name = jsonObject.getString("key");
                        String value = jsonObject.getString("value");
                        if (null == name || null == value) {
                            continue;
                        }
                        if (name.equals("tv.ouya.product_id_list")) {
                            String[] productIds = value.split(",");
                            if (null == productIds) {
                                continue;
                            }
                            developerInfo.putStringArray("tv.ouya.product_id_list", productIds);
                        } else {
                            developerInfo.putString(name, value);
                        }
                    }

                    UnityOuyaFacade unityOuyaFacade = new UnityOuyaFacade(IOuyaActivity.GetActivity(),
                            IOuyaActivity.GetSavedInstanceState(), developerInfo);

                    IOuyaActivity.SetUnityOuyaFacade(unityOuyaFacade);

                    Log.i(TAG, "initOuyaPlugin: OuyaGameObject send OnSuccessInitializePlugin");
                    UnityPlayer.UnitySendMessage("OuyaGameObject", "OnSuccessInitializePlugin", "");
                } catch (Exception e) {
                    e.printStackTrace();
                    UnityPlayer.UnitySendMessage("OuyaGameObject", "OnFailureInitializePlugin",
                            "InitializePlugin exception");
                }
            }
        };
        activity.runOnUiThread(runnable);
    }
}

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

private void loadMore() {

    if (getView() == null) {
        // not ready yet (or finished)
        return;/*from www  .jav a 2  s .c o  m*/
    }
    loading = true;
    restoreData = null;

    final MoreMessagesLoadNotification progressNotification = new MoreMessagesLoadNotification();
    Thread thr = new Thread("Download messages (more)") {

        public void run() {
            final Activity activity = getActivity();
            if (activity != null && isAdded()) {
                try {
                    messagesSource.setContext(activity);
                    messagesSource.getNext(progressNotification,
                            new Utils.Function<Void, ArrayList<JuickMessage>>() {
                                @Override
                                public Void apply(final ArrayList<JuickMessage> messages) {
                                    final ArrayList<JuickMessage> messagesFiltered = filterMessages(messages);
                                    if (!JuickMessagesAdapter.dontKeepParsed(parent)) {
                                        for (JuickMessage juickMessage : messagesFiltered) {
                                            juickMessage.parsedText = JuickMessagesAdapter
                                                    .formatMessageText(activity, juickMessage, false);
                                        }
                                    }
                                    activity.runOnUiThread(new Runnable() {

                                        public void run() {

                                            lastPrepareMessages(messagesFiltered, new Runnable() {
                                                @Override
                                                public void run() {
                                                    progressNotification.loadingg.setVisibility(View.GONE);
                                                    progressNotification.progressBar.setVisibility(View.GONE);
                                                    if (messages.size() == 0) {
                                                        progressNotification.progress
                                                                .setText(progressNotification.lastError);
                                                    }
                                                    if (getView() == null)
                                                        return; // already closed?
                                                    MyListView parent = (MyListView) getListView();

                                                    if (getListView().getAdapter().getCount()
                                                            - (recentFirstVisibleItem
                                                                    + recentVisibleItemCount) > 3) {
                                                        parent.blockLayoutRequests = true; // a nafig nam layout, at least 3 items below?
                                                    }
                                                    try {
                                                        listAdapter.addAllMessages(messagesFiltered);
                                                    } finally {
                                                        parent.blockLayoutRequests = false;
                                                    }
                                                    handler.postDelayed(new Runnable() {
                                                        @Override
                                                        public void run() {
                                                            loading = false;
                                                        }
                                                    }, 1000);
                                                }
                                            });

                                        }
                                    });
                                    return null; //To change body of implemented methods use File | Settings | File Templates.
                                }
                            });
                } catch (OutOfMemoryError e) {
                    messagesSource.setCanNext(false);
                    MainActivity.handleException(
                            new RuntimeException("OOM: " + XMPPControlActivity.getMemoryStatusString(), e));
                    progressNotification.notifyDownloadError("OUT OF MEMORY");
                }
            }
        }
    };
    thr.start();
}

From source file:nya.miku.wishmaster.http.cloudflare.InterceptingAntiDDOS.java

/**  anti-DDOS , ? ? ??  webview  httpclient (? ?? ? ?-?  API >= 11) */
Cookie check(final CloudflareException exception, final ExtendedHttpClient httpClient,
        final CancellableTask task, final Activity activity) {
    synchronized (lock) {
        if (processing)
            return null;
        processing = true;/*from   w w w  . j a v a2  s.co  m*/
    }
    processing2 = true;
    currentCookie = null;

    final HttpRequestModel rqModel = HttpRequestModel.builder().setGET().build();
    final CookieStore cookieStore = httpClient.getCookieStore();
    CloudflareChecker.removeCookie(cookieStore, exception.getRequiredCookieName());
    final ViewGroup layout = (ViewGroup) activity.getWindow().getDecorView().getRootView();
    final WebViewClient client = new WebViewClient() {
        @Override
        public void onReceivedSslError(WebView view, SslErrorHandler handler, SslError error) {
            handler.proceed();
        }

        @Override
        public WebResourceResponse shouldInterceptRequest(WebView view, String url) {
            HttpResponseModel responseModel = null;
            try {
                responseModel = HttpStreamer.getInstance().getFromUrl(url, rqModel, httpClient, null, task);
                for (int i = 0; i < 3 && responseModel.statusCode == 400; ++i) {
                    Logger.d(TAG, "HTTP 400");
                    responseModel.release();
                    responseModel = HttpStreamer.getInstance().getFromUrl(url, rqModel, httpClient, null, task);
                }
                for (Cookie cookie : cookieStore.getCookies()) {
                    if (CloudflareChecker.isClearanceCookie(cookie, url, exception.getRequiredCookieName())) {
                        Logger.d(TAG, "Cookie found: " + cookie.getValue());
                        currentCookie = cookie;
                        processing2 = false;
                        return new WebResourceResponse("text/html", "UTF-8",
                                new ByteArrayInputStream("cookie received".getBytes()));
                    }
                }
                BufOutputStream output = new BufOutputStream();
                IOUtils.copyStream(responseModel.stream, output);
                return new WebResourceResponse(null, null, output.toInputStream());
            } catch (Exception e) {
                Logger.e(TAG, e);
            } finally {
                if (responseModel != null)
                    responseModel.release();
            }
            return new WebResourceResponse("text/html", "UTF-8",
                    new ByteArrayInputStream("something wrong".getBytes()));
        }
    };

    activity.runOnUiThread(new Runnable() {
        @SuppressLint("SetJavaScriptEnabled")
        @Override
        public void run() {
            webView = new WebView(activity);
            webView.setVisibility(View.GONE);
            layout.addView(webView);
            webView.setWebViewClient(client);
            webView.getSettings().setUserAgentString(HttpConstants.USER_AGENT_STRING);
            webView.getSettings().setJavaScriptEnabled(true);
            webView.loadUrl(exception.getCheckUrl());
        }
    });

    long startTime = System.currentTimeMillis();
    while (processing2) {
        long time = System.currentTimeMillis() - startTime;
        if ((task != null && task.isCancelled()) || time > CloudflareChecker.TIMEOUT) {
            processing2 = false;
        }
    }

    activity.runOnUiThread(new Runnable() {
        @Override
        public void run() {
            try {
                layout.removeView(webView);
                webView.stopLoading();
                webView.clearCache(true);
                webView.destroy();
                webView = null;
            } finally {
                processing = false;
            }
        }
    });
    return currentCookie;
}

From source file:paulscode.android.mupen64plusae.jni.CoreFragment.java

@Override
public void onFailure(final int errorCode) {
    final Activity activity = getActivity();
    if (activity != null) {
        // Messages match return codes from mupen64plus-ui-console/main.c
        String message = null;//from w w  w  . j a v a2s  .c  o m

        if (errorCode != 0) {
            switch (errorCode) {
            case 1:
                message = activity.getString(R.string.toast_nativeMainFailure01);
                break;
            case 2:
                message = activity.getString(R.string.toast_nativeMainFailure02);
                break;
            case 3:
                message = activity.getString(R.string.toast_nativeMainFailure03);
                break;
            case 4:
                message = activity.getString(R.string.toast_nativeMainFailure04);
                break;
            case 5:
                message = activity.getString(R.string.toast_nativeMainFailure05);
                break;
            case 6:
                message = activity.getString(R.string.toast_nativeMainFailure06);
                break;
            case 7:
                message = activity.getString(R.string.toast_nativeMainFailure07);
                break;
            case 8:
                message = activity.getString(R.string.toast_nativeMainFailure08);
                break;
            case 9:
                message = activity.getString(R.string.toast_nativeMainFailure09);
                break;
            case 10:
                message = activity.getString(R.string.toast_nativeMainFailure10);
                break;
            case 11:
                message = activity.getString(R.string.toast_nativeMainFailure11);
                break;
            case 12:
                message = activity.getString(R.string.toast_nativeMainFailure12);
                break;
            case 13:
                message = activity.getString(R.string.toast_nativeMainFailure13);
                break;
            default:
                message = activity.getString(R.string.toast_nativeMainFailureUnknown);
                break;
            }
            Log.e("CoreFragment", "Launch failure: " + message);
        }

        final String finalMessage = message;

        activity.runOnUiThread(new Runnable() {
            @Override
            public void run() {
                Notifier.showToast(activity, finalMessage);
            }
        });
    }
}