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.drisoftie.action.async.AsyncAction.java

@Override
public void invokeRunnableOnUiThread(Runnable runnable) {
    new Handler(Looper.getMainLooper()).post(runnable);
}

From source file:org.lol.reddit.common.General.java

public static boolean isThisUIThread() {
    return Looper.getMainLooper().getThread() == Thread.currentThread();
}

From source file:com.networking.OkHttpResponseTestActivity.java

public void createAnUser(View view) {
    AndroidNetworking.post(ApiEndPoint.BASE_URL + ApiEndPoint.POST_CREATE_AN_USER)
            .addBodyParameter("firstname", "Suman").addBodyParameter("lastname", "Shekhar").setTag(this)
            .setPriority(Priority.LOW).build().setAnalyticsListener(new AnalyticsListener() {
                @Override//from www.j a  v  a  2 s.  c  o m
                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);
                }
            }).getAsOkHttpResponseAndJSONObject(new OkHttpResponseAndJSONObjectRequestListener() {
                @Override
                public void onResponse(Response okHttpResponse, JSONObject response) {
                    Log.d(TAG, "onResponse object : " + response.toString());
                    Log.d(TAG, "onResponse isMainThread : "
                            + String.valueOf(Looper.myLooper() == Looper.getMainLooper()));
                    if (okHttpResponse.isSuccessful()) {
                        Log.d(TAG, "onResponse success headers : " + okHttpResponse.headers().toString());
                    } else {
                        Log.d(TAG, "onResponse not success headers : " + okHttpResponse.headers().toString());
                    }
                }

                @Override
                public void onError(ANError anError) {
                    Utils.logError(TAG, anError);
                }
            });
}

From source file:com.albedinsky.android.support.universi.UniversiActivity.java

/**
 * Requests performing of data binding specific for this activity via {@link #onBindData()}.
 * If this activity has its view hierarchy already created {@link #onBindData()} will be invoked
 * immediately, otherwise will wait until {@link #onContentChanged()} is invoked.
 * <p>/*from  www.j  a  va  2  s.c om*/
 * <b>This method can be invoked from a background-thread</b>.
 */
protected void requestBindData() {
    // Check whether this call has been made on the UI thread, if not post on the UI thread the request runnable.
    if (Looper.getMainLooper().equals(Looper.myLooper())) {
        this.requestBindDataInner();
    } else {
        if (mRequestBindDataInner == null) {
            this.mRequestBindDataInner = new Runnable() {
                @Override
                public void run() {
                    requestBindDataInner();
                }
            };
        }
        runOnUiThread(mRequestBindDataInner);
    }
}

From source file:com.github.michalbednarski.intentslab.browser.ExtendedPackageInfo.java

public static void getAllPackageInfos(Context context, final AllCallback callback) {
    // Ensure this is called from main thread
    if (BuildConfig.DEBUG && Looper.myLooper() != Looper.getMainLooper()) {
        throw new AssertionError("getExtendedPackageInfo called off main thread");
    }//from w  w  w .  j av  a  2 s.co  m

    // Check for cached value
    if (sAllPackageInfos != null) {
        callback.onAllPackagesInfosAvailable(sAllPackageInfos);
        return;
    }

    // A closure...
    class L {
        int packagesToLoadLeft;
    }
    final L state = new L();

    // Get list of installed packages
    List<PackageInfo> installedPackages = context.getPackageManager().getInstalledPackages(0);
    state.packagesToLoadLeft = installedPackages.size();

    // Prepare result array
    final ExtendedPackageInfo[] allInfos = new ExtendedPackageInfo[installedPackages.size()];

    // Scan all packages
    int index = 0;
    for (PackageInfo installedPackage : installedPackages) {
        final int ii = index++;
        getExtendedPackageInfo(context, installedPackage.packageName, new Callback() {
            @Override
            public void onPackageInfoAvailable(ExtendedPackageInfo extendedPackageInfo) {
                // Fill in result array
                allInfos[ii] = extendedPackageInfo;

                // If all package infos are ready
                if (--state.packagesToLoadLeft == 0) {
                    // Save to cache
                    sAllPackageInfos = allInfos;

                    // Invoke callback
                    callback.onAllPackagesInfosAvailable(allInfos);
                }
            }
        });
    }
}

From source file:com.example.android.wearable.runtimepermissions.MainPhoneActivity.java

private void logToUi(final String message) {

    boolean mainUiThread = (Looper.myLooper() == Looper.getMainLooper());

    if (mainUiThread) {

        if (!message.isEmpty()) {
            Log.d(TAG, message);/*from w  w w.  j  av  a 2 s. c  o  m*/
            mOutputTextView.setText(message);
        }

    } else {
        if (!message.isEmpty()) {

            runOnUiThread(new Runnable() {
                @Override
                public void run() {

                    Log.d(TAG, message);
                    mOutputTextView.setText(message);
                }
            });
        }
    }
}

From source file:com.facebook.Session.java

Session(Context context, String applicationId, TokenCachingStrategy tokenCachingStrategy,
        boolean loadTokenFromCache) {
    // if the application ID passed in is null, try to get it from the
    // meta-data in the manifest.
    if ((context != null) && (applicationId == null)) {
        applicationId = Utility.getMetadataApplicationId(context);
    }// w  ww .j  a va 2s  .c om

    Validate.notNull(applicationId, "applicationId");

    initializeStaticContext(context);

    if (tokenCachingStrategy == null) {
        tokenCachingStrategy = new SharedPreferencesTokenCachingStrategy(staticContext);
    }

    this.applicationId = applicationId;
    this.tokenCachingStrategy = tokenCachingStrategy;
    this.state = SessionState.CREATED;
    this.pendingAuthorizationRequest = null;
    this.callbacks = new ArrayList<StatusCallback>();
    this.handler = new Handler(Looper.getMainLooper());

    Bundle tokenState = loadTokenFromCache ? tokenCachingStrategy.load() : null;
    if (TokenCachingStrategy.hasTokenInformation(tokenState)) {
        Date cachedExpirationDate = TokenCachingStrategy.getDate(tokenState,
                TokenCachingStrategy.EXPIRATION_DATE_KEY);
        Date now = new Date();

        if ((cachedExpirationDate == null) || cachedExpirationDate.before(now)) {
            // If expired or we require new permissions, clear out the
            // current token cache.
            tokenCachingStrategy.clear();
            this.tokenInfo = AccessToken.createEmptyToken();
        } else {
            // Otherwise we have a valid token, so use it.
            this.tokenInfo = AccessToken.createFromCache(tokenState);
            this.state = SessionState.CREATED_TOKEN_LOADED;
        }
    } else {
        this.tokenInfo = AccessToken.createEmptyToken();
    }
}

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

@Override
public void onConnected(Bundle bundle) {
    Log.d(TAG, "onConnected");

    sm.setGoogleDriveSyncable(gapi, new DriveSettingsManager.GoogleDriveListener() {
        @Override//from ww  w  .  j  ava2 s  .com
        public void onActionFinished(boolean cloudToLocal) {
            Log.d(TAG, "Sync req after drive action");
            final String info = TvContract.buildInputId(ActivityUtils.TV_INPUT_SERVICE);
            SyncUtils.requestSync(mActivity, info);
            if (cloudToLocal) {
                Toast.makeText(getActivity(), R.string.download_complete, Toast.LENGTH_SHORT).show();
            } else {
                Toast.makeText(getActivity(), R.string.upload_complete, Toast.LENGTH_SHORT).show();
            }
        }
    }); //Enable GDrive
    Log.d(TAG, sm.getString(R.string.sm_google_drive_id) + "<< for onConnected");
    if (sm.getString(R.string.sm_google_drive_id).isEmpty()) {
        //We need a new file
        ActivityUtils.createDriveData(mActivity, gapi, driveContentsCallback);
    } else {
        //Great, user already has sync enabled, let's resync
        ActivityUtils.readDriveData(mActivity, gapi);
        Handler h = new Handler(Looper.getMainLooper()) {
            @Override
            public void handleMessage(Message msg) {
                super.handleMessage(msg);
                refreshUI();
            }
        };
        h.sendEmptyMessageDelayed(0, 4000);
    }
}

From source file:com.example.rx.ui.OnePlusNLayoutActivity.java

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.main_activity2);

    mFirstText = (TextView) findViewById(R.id.first);
    mLastText = (TextView) findViewById(R.id.last);
    mCountText = (TextView) findViewById(R.id.count);
    mTotalOffsetText = (TextView) findViewById(R.id.total_offset);

    final RecyclerView recyclerView = (RecyclerView) findViewById(R.id.main_view);

    findViewById(R.id.jump).setOnClickListener(new View.OnClickListener() {
        @Override/*from  w w  w  . j  av  a2  s .co  m*/
        public void onClick(View v) {
            EditText position = (EditText) findViewById(R.id.position);
            if (!TextUtils.isEmpty(position.getText())) {
                try {
                    int pos = Integer.parseInt(position.getText().toString());
                    recyclerView.scrollToPosition(pos);
                } catch (Exception e) {
                    Log.e("VlayoutActivity", e.getMessage(), e);
                }
            } else {
                recyclerView.requestLayout();
            }
        }
    });

    final VirtualLayoutManager layoutManager = new VirtualLayoutManager(this);

    recyclerView.setOnScrollListener(new RecyclerView.OnScrollListener() {
        @Override
        public void onScrollStateChanged(RecyclerView recyclerView, int scrollState) {

        }

        @Override
        public void onScrolled(RecyclerView recyclerView, int i, int i2) {
            mFirstText.setText("First: " + layoutManager.findFirstVisibleItemPosition());
            mLastText.setText(
                    "Existing: " + MainViewHolder.existing + " Created: " + MainViewHolder.createdTimes);
            mCountText.setText("Count: " + recyclerView.getChildCount());
            mTotalOffsetText.setText("Total Offset: " + layoutManager.getOffsetToStart());
        }
    });

    recyclerView.setLayoutManager(layoutManager);

    // layoutManager.setReverseLayout(true);

    RecyclerView.ItemDecoration itemDecoration = new RecyclerView.ItemDecoration() {
        public void getItemOffsets(Rect outRect, View view, RecyclerView parent, RecyclerView.State state) {
            int position = ((LayoutParams) view.getLayoutParams()).getViewPosition();
            outRect.set(4, 4, 4, 4);
        }
    };

    final RecyclerView.RecycledViewPool viewPool = new RecyclerView.RecycledViewPool();

    recyclerView.setRecycledViewPool(viewPool);

    // recyclerView.addItemDecoration(itemDecoration);

    viewPool.setMaxRecycledViews(0, 20);

    final DelegateAdapter delegateAdapter = new DelegateAdapter(layoutManager, true);

    recyclerView.setAdapter(delegateAdapter);

    List<DelegateAdapter.Adapter> adapters = new LinkedList<>();

    if (BANNER_LAYOUT) {
        adapters.add(new SubAdapter(this, new LinearLayoutHelper(), 1) {

            @Override
            public void onViewRecycled(MainViewHolder holder) {
                if (holder.itemView instanceof ViewPager) {
                    ((ViewPager) holder.itemView).setAdapter(null);
                }
            }

            @Override
            public MainViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
                if (viewType == 1)
                    return new MainViewHolder(LayoutInflater.from(OnePlusNLayoutActivity.this)
                            .inflate(R.layout.view_pager, parent, false));

                return super.onCreateViewHolder(parent, viewType);
            }

            @Override
            public int getItemViewType(int position) {
                return 1;
            }

            @Override
            protected void onBindViewHolderWithOffset(MainViewHolder holder, int position, int offsetTotal) {

            }

            @Override
            public void onBindViewHolder(MainViewHolder holder, int position) {
                if (holder.itemView instanceof ViewPager) {
                    ViewPager viewPager = (ViewPager) holder.itemView;

                    viewPager.setLayoutParams(new LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, 200));

                    // from position to get adapter
                    viewPager.setAdapter(new PagerAdapter(this, viewPool));
                }
            }
        });
    }

    if (GRID_LAYOUT) {
        GridLayoutHelper layoutHelper;
        layoutHelper = new GridLayoutHelper(4);
        layoutHelper.setMargin(0, 10, 0, 10);
        layoutHelper.setHGap(3);
        layoutHelper.setAspectRatio(4f);
        adapters.add(new SubAdapter(this, layoutHelper, 8));
    }

    if (HORIZONTAL_SCROLL_LAYOUT) {

    }

    if (GRID_LAYOUT) {
        GridLayoutHelper layoutHelper;
        layoutHelper = new GridLayoutHelper(2);
        layoutHelper.setMargin(0, 10, 0, 10);
        layoutHelper.setHGap(3);
        layoutHelper.setAspectRatio(3f);
        adapters.add(new SubAdapter(this, layoutHelper, 2));
    }

    if (ONEN_LAYOUT) {
        OnePlusNLayoutHelper helper = new OnePlusNLayoutHelper();
        helper.setBgColor(0xff876384);
        helper.setMargin(10, 10, 10, 10);
        helper.setPadding(10, 10, 10, 10);
        adapters.add(new SubAdapter(this, helper, 3) {
            @Override
            public void onBindViewHolder(MainViewHolder holder, int position) {
                super.onBindViewHolder(holder, position);
                //                    LayoutParams layoutParams = new LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, 300);
                //                    layoutParams.leftMargin = 10;
                //                    layoutParams.topMargin = 10;
                //                    layoutParams.rightMargin = 10;
                //                    layoutParams.bottomMargin = 10;
                //                    holder.itemView.setLayoutParams(layoutParams);
            }
        });
    }

    if (ONEN_LAYOUT) {
        OnePlusNLayoutHelper helper = new OnePlusNLayoutHelper();
        helper.setBgColor(0xff876384);
        helper.setMargin(0, 10, 0, 10);
        adapters.add(new SubAdapter(this, helper, 4));
    }

    if (ONEN_LAYOUT) {
        OnePlusNLayoutHelper helper = new OnePlusNLayoutHelper();
        helper.setBgColor(0xff876384);
        helper.setMargin(0, 10, 0, 10);
        adapters.add(new SubAdapter(this, helper, 5));
    }

    if (ONEN_LAYOUT) {
        OnePlusNLayoutHelperEx helper = new OnePlusNLayoutHelperEx();
        helper.setBgColor(0xff876384);
        helper.setMargin(0, 10, 0, 10);
        adapters.add(new SubAdapter(this, helper, 5));
    }

    if (ONEN_LAYOUT) {
        OnePlusNLayoutHelperEx helper = new OnePlusNLayoutHelperEx();
        helper.setBgColor(0xff876384);
        helper.setMargin(0, 10, 0, 10);
        helper.setColWeights(new float[] { 40f, 45f, 15f, 60f, 0f });
        adapters.add(new SubAdapter(this, helper, 5));
    }

    if (ONEN_LAYOUT) {
        OnePlusNLayoutHelperEx helper = new OnePlusNLayoutHelperEx();
        helper.setBgColor(0xff876384);
        helper.setMargin(0, 10, 0, 10);
        helper.setColWeights(new float[] { 20f, 80f, 0f, 60f, 20f });
        helper.setAspectRatio(4);
        adapters.add(new SubAdapter(this, helper, 5));
    }

    if (ONEN_LAYOUT) {
        OnePlusNLayoutHelperEx helper = new OnePlusNLayoutHelperEx();
        helper.setBgColor(0xff876384);
        helper.setMargin(0, 10, 0, 10);
        adapters.add(new SubAdapter(this, helper, 6));
    }

    if (ONEN_LAYOUT) {
        OnePlusNLayoutHelperEx helper = new OnePlusNLayoutHelperEx();
        helper.setBgColor(0xff876384);
        helper.setMargin(0, 10, 0, 10);
        adapters.add(new SubAdapter(this, helper, 7));
    }

    if (ONEN_LAYOUT) {
        OnePlusNLayoutHelperEx helper = new OnePlusNLayoutHelperEx();
        helper.setBgColor(0xff876384);
        helper.setMargin(0, 10, 0, 10);
        helper.setColWeights(new float[] { 40f, 45f, 15f, 60f, 0f, 30f, 30f });
        adapters.add(new SubAdapter(this, helper, 7));
    }

    if (ONEN_LAYOUT) {
        OnePlusNLayoutHelperEx helper = new OnePlusNLayoutHelperEx();
        helper.setBgColor(0xffed7612);
        //            helper.setMargin(10, 10, 10, 10);
        //            helper.setPadding(10, 10, 10, 10);
        helper.setColWeights(new float[] { 30f, 20f, 50f, 40f, 30f, 35f, 35f });
        adapters.add(new SubAdapter(this, helper, 7) {
            @Override
            public void onBindViewHolder(MainViewHolder holder, int position) {
                super.onBindViewHolder(holder, position);
                //                    LayoutParams layoutParams = new LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, 300);
                //                    layoutParams.leftMargin = 10;
                //                    layoutParams.topMargin = 10;
                //                    layoutParams.rightMargin = 10;
                //                    layoutParams.bottomMargin = 10;
                //                    holder.itemView.setLayoutParams(layoutParams);
            }
        });
    }

    if (STICKY_LAYOUT) {
        StickyLayoutHelper layoutHelper = new StickyLayoutHelper();
        layoutHelper.setAspectRatio(4);
        adapters.add(new SubAdapter(this, layoutHelper, 1,
                new LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, 100)));
    }

    if (SCROLL_FIX_LAYOUT) {
        ScrollFixLayoutHelper layoutHelper = new ScrollFixLayoutHelper(FixLayoutHelper.BOTTOM_RIGHT, 20, 20);
        layoutHelper.setShowType(ScrollFixLayoutHelper.SHOW_ON_LEAVE);
        adapters.add(new SubAdapter(this, layoutHelper, 1) {
            @Override
            public void onBindViewHolder(MainViewHolder holder, int position) {
                super.onBindViewHolder(holder, position);
                LayoutParams layoutParams = new LayoutParams(50, 50);
                holder.itemView.setLayoutParams(layoutParams);
            }
        });
    }

    if (LINEAR_LAYOUT)
        adapters.add(new SubAdapter(this, new LinearLayoutHelper(), 100));

    delegateAdapter.setAdapters(adapters);

    final Handler mainHandler = new Handler(Looper.getMainLooper());

    trigger = new Runnable() {
        @Override
        public void run() {
            // recyclerView.scrollToPosition(22);
            // recyclerView.getAdapter().notifyDataSetChanged();
            recyclerView.requestLayout();
            // mainHandler.postDelayed(trigger, 1000);
        }
    };

    mainHandler.postDelayed(trigger, 1000);
}

From source file:it.mb.whatshare.Dialogs.java

/**
 * Shows a prompt to the user to rename the argument <tt>device</tt>.
 * //from  w ww.  j a  v  a2s.c  om
 * @param device
 *            the device to be renamed
 * @param activity
 *            the parent activity
 */
public static void promptForNewDeviceName(final PairedDevice device, final MainActivity activity) {
    Handler handler = new Handler(Looper.getMainLooper());
    handler.post(new Runnable() {

        @Override
        public void run() {
            DialogFragment prompt = new PatchedDialogFragment() {
                public Dialog onCreateDialog(Bundle savedInstanceState) {
                    AlertDialog.Builder builder = getBuilder(activity);

                    final EditText input = new EditText(getContext());
                    input.setInputType(InputType.TYPE_CLASS_TEXT);
                    input.setText(device.name);
                    input.setSelection(device.name.length());

                    // @formatter:off
                    builder.setTitle(R.string.device_name_chooser_title).setView(input)
                            .setPositiveButton(android.R.string.ok, null);
                    // @formatter:on

                    final AlertDialog alertDialog = builder.create();
                    alertDialog.setOnShowListener(
                            new DeviceNameChooserPrompt(alertDialog, input, activity, new Callback<String>() {

                                @Override
                                public void run() {
                                    // @formatter:off
                                    device.rename(getParam());
                                    activity.onSelectedDeviceRenamed();

                                    ((InputMethodManager) activity
                                            .getSystemService(Context.INPUT_METHOD_SERVICE))
                                                    .hideSoftInputFromWindow(input.getWindowToken(), 0);
                                    // @formatter:on
                                }
                            }));
                    return alertDialog;
                }
            };
            prompt.show(activity.getSupportFragmentManager(), "chooseName");
        }
    });
}