Example usage for android.os Looper getMainLooper

List of usage examples for android.os Looper getMainLooper

Introduction

In this page you can find the example usage for android.os Looper getMainLooper.

Prototype

public static Looper getMainLooper() 

Source Link

Document

Returns the application's main looper, which lives in the main thread of the application.

Usage

From source file:com.kytse.aria2remote.DownloadListFragment.java

@Override
public void onAria2ListItemInserted(Aria2.ListType type, final int position) {
    if (type == mType) {
        Handler handler = new Handler(Looper.getMainLooper());
        handler.post(new Runnable() {
            @Override//from  www. j  a va 2s .co  m
            public void run() {
                mAdapter.notifyItemInserted(position);
            }
        });
    }
}

From source file:com.github.yuukis.businessmap.app.ContactsTaskFragment.java

private void showProgress() {
    String title = getString(R.string.title_geocoding);
    String message = getString(R.string.message_geocoding);
    int max = mGeocodingResultCache.size();

    Bundle args = new Bundle();
    args.putString(ProgressDialogFragment.TITLE, title);
    args.putString(ProgressDialogFragment.MESSAGE, message);
    args.putBoolean(ProgressDialogFragment.CANCELABLE, true);
    args.putInt(ProgressDialogFragment.MAX, max);
    final DialogFragment dialog = ProgressDialogFragment.newInstance();
    dialog.setArguments(args);/* w w  w.j av a 2 s .c  o m*/
    if (getActivity() != null) {
        new Handler(Looper.getMainLooper()).post(new Runnable() {
            @Override
            public void run() {
                dialog.show(getActivity().getSupportFragmentManager(), ProgressDialogFragment.TAG);
            }
        });
    }
}

From source file:com.ryan.ryanreader.fragments.MainMenuFragment.java

@Override
public View onCreateView(final LayoutInflater inflater, final ViewGroup container,
        final Bundle savedInstanceState) {

    // TODO load menu position?

    final Context context;

    // // w  w w  .  jav a  2 s . c om
    if (container != null) {
        context = container.getContext(); // TODO just use the inflater's
        // context in every case?
    } else {
        context = inflater.getContext();
    }

    // 
    final RedditAccount user = RedditAccountManager.getInstance(context).getDefaultAccount();

    final LinearLayout outer = new LinearLayout(context);

    // 
    outer.setOrientation(LinearLayout.VERTICAL);

    notifications = new LinearLayout(context);
    notifications.setOrientation(LinearLayout.VERTICAL);

    loadingView = new LoadingView(context, R.string.download_waiting, true, true);

    final ListView lv = new ListView(context);
    lv.setDivider(null);

    // listview?
    lv.addFooterView(notifications);

    final int paddingPx = General.dpToPixels(context, 8);
    lv.setPadding(paddingPx, 0, paddingPx, 0);

    adapter = new MainMenuAdapter(context, user, this);
    lv.setAdapter(adapter);

    lv.setOnItemClickListener(new AdapterView.OnItemClickListener() {
        public void onItemClick(final AdapterView<?> adapterView, final View view, final int position,
                final long id) {
            adapter.clickOn(position);
        }
    });

    final AtomicReference<APIResponseHandler.SubredditResponseHandler> accessibleSubredditResponseHandler = new AtomicReference<APIResponseHandler.SubredditResponseHandler>(
            null);

    final APIResponseHandler.SubredditResponseHandler responseHandler = new APIResponseHandler.SubredditResponseHandler(
            context) {

        @Override
        protected void onDownloadNecessary() {
            new Handler(Looper.getMainLooper()).post(new Runnable() {
                public void run() {
                    notifications.addView(loadingView);
                }
            });
        }

        @Override
        protected void onDownloadStarted() {
            loadingView.setIndeterminate(R.string.download_subreddits);
        }

        @Override
        protected void onSuccess(final List<RedditSubreddit> result, final long timestamp) {

            if (result.size() == 0) {
                // Just get the defaults instead
                new Handler(Looper.getMainLooper()).post(new Runnable() {
                    public void run() {
                        notifications.removeView(loadingView);
                        RedditAPI.getUserSubreddits(CacheManager.getInstance(context),
                                accessibleSubredditResponseHandler.get(), RedditAccountManager.getAnon(),
                                force ? CacheRequest.DownloadType.FORCE
                                        : CacheRequest.DownloadType.IF_NECESSARY,
                                force, context);
                    }
                });

            } else {

                adapter.setSubreddits(result);

                if (loadingView != null)
                    loadingView.setDone(R.string.download_done);
            }
        }

        @Override
        protected void onCallbackException(final Throwable t) {
            BugReportActivity.handleGlobalError(context, t);
        }

        @Override
        protected void onFailure(final RequestFailureType type, final Throwable t, final StatusLine status,
                final String readableMessage) {

            if (loadingView != null)
                loadingView.setDone(R.string.download_failed);
            final RRError error = General.getGeneralErrorForFailure(context, type, t, status);

            new Handler(Looper.getMainLooper()).post(new Runnable() {
                public void run() {
                    notifications.addView(new ErrorView(getSupportActivity(), error));
                }
            });
        }

        @Override
        protected void onFailure(final APIFailureType type) {

            if (loadingView != null)
                loadingView.setDone(R.string.download_failed);
            final RRError error = General.getGeneralErrorForFailure(context, type);

            new Handler(Looper.getMainLooper()).post(new Runnable() {
                public void run() {
                    notifications.addView(new ErrorView(getSupportActivity(), error));
                }
            });
        }
    };

    accessibleSubredditResponseHandler.set(responseHandler);

    RedditAPI.getUserSubreddits(CacheManager.getInstance(context), responseHandler, user,
            force ? CacheRequest.DownloadType.FORCE : CacheRequest.DownloadType.IF_NECESSARY, force, context);

    outer.addView(lv);
    lv.getLayoutParams().height = ViewGroup.LayoutParams.MATCH_PARENT;

    return outer;
}

From source file:com.phonegap.plugins.speech.XSpeechRecognizer.java

private void stopSpeechRecognitionActivity() {
    Handler loopHandler = new Handler(Looper.getMainLooper());
    loopHandler.post(new Runnable() {

        @Override//from  w w  w.ja  v a2 s .c om
        public void run() {
            recognizer.stopListening();
            // recognizer.cancel();
        }

    });
}

From source file:com.rxsampleapp.RxApiTestActivity.java

public void getAnUser(View view) {
    RxAndroidNetworking.get(ApiEndPoint.BASE_URL + ApiEndPoint.GET_JSON_OBJECT).addPathParameter("userId", "1")
            .setUserAgent("getAnUser").build().setAnalyticsListener(new AnalyticsListener() {
                @Override//from   www . j a  v a  2 s .  com
                public void onReceived(long timeTakenInMillis, long bytesSent, long bytesReceived,
                        boolean isFromCache) {
                    Log.d(TAG, " timeTakenInMillis : " + timeTakenInMillis);
                    Log.d(TAG, " bytesSent : " + bytesSent);
                    Log.d(TAG, " bytesReceived : " + bytesReceived);
                    Log.d(TAG, " isFromCache : " + isFromCache);
                }
            }).getParseObservable(new TypeToken<User>() {
            }).subscribeOn(Schedulers.io()).observeOn(AndroidSchedulers.mainThread())
            .subscribe(new Observer<User>() {
                @Override
                public void onCompleted() {
                    Log.d(TAG, "onComplete Detail : getAnUser completed");
                }

                @Override
                public void onError(Throwable e) {
                    Utils.logError(TAG, e);
                }

                @Override
                public void onNext(User user) {
                    Log.d(TAG, "onResponse isMainThread : "
                            + String.valueOf(Looper.myLooper() == Looper.getMainLooper()));
                    Log.d(TAG, "id : " + user.id);
                    Log.d(TAG, "firstname : " + user.firstname);
                    Log.d(TAG, "lastname : " + user.lastname);
                }
            });
}

From source file:com.kytse.aria2remote.DownloadListFragment.java

@Override
public void onAria2ListItemRemoved(Aria2.ListType type, final int position) {
    if (type == mType) {
        Handler handler = new Handler(Looper.getMainLooper());
        handler.post(new Runnable() {
            @Override/*from   w w w.  j av a2s .  c  om*/
            public void run() {
                mAdapter.notifyItemRemoved(position);
            }
        });
    }
}

From source file:com.felkertech.n.tv.fragments.VideoDetailsFragment.java

private void setupDetailsOverviewRow() {
    final DetailsOverviewRow row = new DetailsOverviewRow(jsonChannel);
    row.setImageDrawable(getResources().getDrawable(R.drawable.c_background5));
    int width = Utils.convertDpToPixel(getActivity().getApplicationContext(), DETAIL_THUMB_WIDTH);
    int height = Utils.convertDpToPixel(getActivity().getApplicationContext(), DETAIL_THUMB_HEIGHT);
    new Thread(new Runnable() {
        @Override//from w ww .jav a  2 s.  com
        public void run() {
            try {
                final Bitmap bitmap = Picasso.with(getActivity()).load(jsonChannel.getLogo()).centerInside()
                        .error(R.drawable.c_background5).resize(DETAIL_THUMB_WIDTH, DETAIL_THUMB_HEIGHT).get();
                new Handler(Looper.getMainLooper()).post(new Runnable() {
                    @Override
                    public void run() {
                        row.setImageBitmap(getActivity(), bitmap);
                        mAdapter.notifyArrayItemRangeChanged(0, mAdapter.size());
                    }
                });
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }).start();

    ArrayObjectAdapter actions = new ArrayObjectAdapter();
    // Add another action IF it isn't a channel you already have:
    ChannelDatabase cdn = ChannelDatabase.getInstance(getActivity());
    if (cdn.findChannelByMediaUrl(jsonChannel.getMediaUrl()) == null) {
        actions.add(new Action(ACTION_ADD, getString(R.string.add_channel_txt)));
    } else {
        actions.add(new Action(ACTION_EDIT, getString(R.string.edit_channel)));
    }
    actions.add(new Action(ACTION_WATCH, getString(R.string.play)));
    row.setActionsAdapter(actions);
    mAdapter.add(row);
}

From source file:com.projectsexception.myapplist.iconloader.IconManager.java

/**
 * Constructs the work queues and thread pools used to download and decode images.
 *//* w  w w.j  ava2 s  .c om*/
private IconManager() {

    /*
     * Creates a work queue for the pool of Thread objects used for downloading, using a linked
     * list queue that blocks when the queue is empty.
     */
    mDownloadWorkQueue = new LinkedBlockingQueue<Runnable>();

    /*
     * Creates a work queue for the set of of task objects that control downloading and
     * decoding, using a linked list queue that blocks when the queue is empty.
     */
    mIconTaskWorkQueue = new LinkedBlockingQueue<IconTask>();

    /*
     * Creates a new pool of Thread objects for the download work queue
     */
    mDownloadThreadPool = new ThreadPoolExecutor(CORE_POOL_SIZE, MAXIMUM_POOL_SIZE, KEEP_ALIVE_TIME,
            KEEP_ALIVE_TIME_UNIT, mDownloadWorkQueue);

    // Instantiates a new cache based on the cache size estimate
    mIconCache = new LruCache<String, Drawable>(IMAGE_CACHE_SIZE);

    /*
     * Instantiates a new anonymous Handler object and defines its
     * handleMessage() method. The Handler *must* run on the UI thread, because it moves
     * Drawables from the IconTask object to the View object.
     * To force the Handler to run on the UI thread, it's defined as part of the IconManager
     * constructor. The constructor is invoked when the class is first referenced, and that
     * happens when the View invokes startDownload. Since the View runs on the UI Thread, so
     * does the constructor and the Handler.
     */
    mHandler = new Handler(Looper.getMainLooper()) {

        /*
         * handleMessage() defines the operations to perform when the
         * Handler receives a new Message to process.
         */
        @Override
        public void handleMessage(Message inputMessage) {

            // Gets the image task from the incoming Message object.
            IconTask iconTask = (IconTask) inputMessage.obj;

            // Sets an IconView that's a weak reference to the
            // input ImageView
            IconView localView = iconTask.getIconView();

            // If this input view isn't null
            if (localView != null) {

                /*
                 * Gets the package name of the *weak reference* to the input
                 * ImageView. The weak reference won't have changed, even if
                 * the input ImageView has.
                 */
                String packageName = localView.getPackageName();

                /*
                 * Compares the URL of the input ImageView to the URL of the
                 * weak reference. Only updates the drawable in the ImageView
                 * if this particular Thread is supposed to be serving the
                 * ImageView.
                 */
                if (iconTask.getPackageName() != null && iconTask.getPackageName().equals(packageName)) {

                    /*
                     * Chooses the action to take, based on the incoming message
                     */
                    switch (inputMessage.what) {

                    // If the download has started, sets background color to dark green
                    case LOAD_STARTED:
                        localView.setStatusResource(R.drawable.ic_default_launcher);
                        break;
                    /*
                     * The decoding is done, so this sets the
                     * ImageView's bitmap to the bitmap in the
                     * incoming message
                     */
                    case TASK_COMPLETE:
                        localView.setImageDrawable(iconTask.getDrawable());
                        recycleTask(iconTask);
                        break;
                    // The download failed, sets the background color to dark red
                    case LOAD_FAILED:
                        localView.setStatusResource(R.drawable.ic_default_launcher);

                        // Attempts to re-use the Task object
                        recycleTask(iconTask);
                        break;
                    default:
                        // Otherwise, calls the super method
                        super.handleMessage(inputMessage);
                    }
                }
            }
        }
    };
}

From source file:com.alucas.snorlax.module.feature.encounter.EncounterNotification.java

@SuppressWarnings("deprecation")
void show(int pokemonNumber, String pokemonName, Gender gender, double iv, int attack, int defense, int stamina,
        int cp, double level, int hp, double baseWeight, double weight, double baseHeight, double height,
        MoveSettings fastMove, MoveSettings chargeMove, double fleeRate, double pokeRate, double greatRate,
        double ultraRate, PokemonType type1, PokemonType type2, PokemonRarity pokemonClass) {
    final double weightRatio = weight / baseWeight;
    final double heightRatio = height / baseHeight;
    final MODIFIER resourceModifier = (pokemonNumber == PokemonId.PIKACHU_VALUE ? MODIFIER.FAN
            : pokemonNumber == PokemonId.RATTATA_VALUE && heightRatio < 0.80 ? MODIFIER.YOUNGSTER
                    : pokemonNumber == PokemonId.MAGIKARP_VALUE && weightRatio > 1.30 ? MODIFIER.FISHERMAN
                            : MODIFIER.NO);

    final String genderSymbol = PokemonFormat.formatGender(mResources, gender);
    final String fastMoveName = PokemonFormat.formatMove(fastMove.getMovementId());
    final String chargeMoveName = PokemonFormat.formatMove(chargeMove.getMovementId());
    final String fastMoveTypeName = PokemonFormat.formatType(fastMove.getPokemonType());
    final String chargeMoveTypeName = PokemonFormat.formatType(chargeMove.getPokemonType());
    final String fastMoveTypeSymbol = TYPE_SYMBOL.containsKey(fastMove.getPokemonType())
            ? mResources.getString(TYPE_SYMBOL.get(fastMove.getPokemonType()))
            : "?";
    final String chargeMoveTypeSymbol = TYPE_SYMBOL.containsKey(chargeMove.getPokemonType())
            ? mResources.getString(TYPE_SYMBOL.get(chargeMove.getPokemonType()))
            : "?";

    final Map<String, Pair<String, Integer>> symbols = getSymbolReplacementTable();
    new Handler(Looper.getMainLooper()).post(() -> {
        Notification notification = new NotificationCompat.Builder(mContext)
                .setSmallIcon(R.drawable.ic_pokeball)
                .setLargeIcon(Bitmap.createScaledBitmap(
                        BitmapFactory.decodeResource(mResources,
                                Resource.getPokemonResourceId(mContext, mResources, pokemonNumber,
                                        resourceModifier)),
                        Resource.getLargeIconWidth(mResources), Resource.getLargeIconHeight(mResources), false))
                .setContentTitle(EncounterFormat.format(
                        mContext.getString(R.string.notification_title, genderSymbol, pokemonName, cp, level),
                        symbols))/*from  w ww .j  a v  a 2  s.  com*/
                .setContentText(EncounterFormat.format(mContext.getString(R.string.notification_content, iv,
                        fleeRate, pokeRate, greatRate, ultraRate), symbols))
                .setStyle(new NotificationCompat.InboxStyle()
                        .addLine(EncounterFormat
                                .format(mContext.getString(R.string.notification_category_stats_content_iv, iv,
                                        attack, defense, stamina), symbols))
                        .addLine(EncounterFormat.format(mContext.getString(
                                R.string.notification_category_stats_content_hp, hp, fleeRate), symbols))
                        .addLine(EncounterFormat
                                .bold(mContext.getString(R.string.notification_category_moves_title)))
                        .addLine(EncounterFormat
                                .format(mContext.getString(R.string.notification_category_moves_fast,
                                        fastMoveName, fastMoveTypeName, fastMove.getPower()), symbols))
                        .addLine(
                                EncounterFormat.format(
                                        mContext.getString(R.string.notification_category_moves_charge,
                                                chargeMoveName, chargeMoveTypeName, chargeMove.getPower()),
                                        symbols))
                        .addLine(EncounterFormat
                                .bold(mContext.getString(R.string.notification_categoty_catch_title)))
                        .addLine(EncounterFormat
                                .format(mContext.getString(R.string.notification_categoty_catch_content,
                                        pokeRate, greatRate, ultraRate), symbols))
                        .setSummaryText(getFooter(type1, type2, pokemonClass)))
                .setColor(ContextCompat.getColor(mContext, R.color.red_700)).setAutoCancel(true)
                .setVibrate(new long[] { 0 }).setPriority(Notification.PRIORITY_MAX)
                .setCategory(NotificationCompat.CATEGORY_ALARM).build();

        hideIcon(notification);

        mNotificationManager.notify(NotificationId.ID_ENCOUNTER, notification);
    });
}

From source file:com.ryan.ryanreader.activities.CommentEditActivity.java

@Override
public boolean onOptionsItemSelected(MenuItem item) {

    if (item.getTitle().equals(getString(R.string.comment_edit_save))) {

        final ProgressDialog progressDialog = new ProgressDialog(this);
        progressDialog.setTitle(getString(R.string.comment_reply_submitting_title));
        progressDialog.setMessage(getString(R.string.comment_reply_submitting_message));
        progressDialog.setIndeterminate(true);
        progressDialog.setCancelable(true);
        progressDialog.setCanceledOnTouchOutside(false);

        progressDialog.setOnCancelListener(new DialogInterface.OnCancelListener() {
            public void onCancel(final DialogInterface dialogInterface) {
                General.quickToast(CommentEditActivity.this, R.string.comment_reply_oncancel);
                progressDialog.dismiss();
            }//from w ww  .j  a  v a 2  s . c om
        });

        progressDialog.setOnKeyListener(new DialogInterface.OnKeyListener() {
            public boolean onKey(final DialogInterface dialogInterface, final int keyCode,
                    final KeyEvent keyEvent) {

                if (keyCode == KeyEvent.KEYCODE_BACK) {
                    General.quickToast(CommentEditActivity.this, R.string.comment_reply_oncancel);
                    progressDialog.dismiss();
                }

                return true;
            }
        });

        final APIResponseHandler.ActionResponseHandler handler = new APIResponseHandler.ActionResponseHandler(
                this) {
            @Override
            protected void onSuccess() {
                new Handler(Looper.getMainLooper()).post(new Runnable() {
                    public void run() {
                        if (progressDialog.isShowing())
                            progressDialog.dismiss();
                        General.quickToast(CommentEditActivity.this, R.string.comment_edit_done);
                        finish();
                    }
                });
            }

            @Override
            protected void onCallbackException(Throwable t) {
                BugReportActivity.handleGlobalError(CommentEditActivity.this, t);
            }

            @Override
            protected void onFailure(RequestFailureType type, Throwable t, StatusLine status,
                    String readableMessage) {

                final RRError error = General.getGeneralErrorForFailure(context, type, t, status);

                new Handler(Looper.getMainLooper()).post(new Runnable() {
                    public void run() {
                        General.showResultDialog(CommentEditActivity.this, error);
                        if (progressDialog.isShowing())
                            progressDialog.dismiss();
                    }
                });
            }

            @Override
            protected void onFailure(final APIFailureType type) {

                final RRError error = General.getGeneralErrorForFailure(context, type);

                new Handler(Looper.getMainLooper()).post(new Runnable() {
                    public void run() {
                        General.showResultDialog(CommentEditActivity.this, error);
                        if (progressDialog.isShowing())
                            progressDialog.dismiss();
                    }
                });
            }
        };

        final CacheManager cm = CacheManager.getInstance(this);
        final RedditAccount selectedAccount = RedditAccountManager.getInstance(this).getDefaultAccount();

        RedditAPI.editComment(cm, handler, selectedAccount, commentIdAndType, textEdit.getText().toString(),
                this);

        progressDialog.show();

    } else if (item.getTitle().equals(getString(R.string.comment_reply_preview))) {
        MarkdownPreviewDialog.newInstance(textEdit.getText().toString()).show(getSupportFragmentManager());
    }

    return true;
}