Java 类android.os.Looper 实例源码

项目:Chorus-RF-Laptimer    文件:UDPService.java   
public void run () {
    if (mIsConnected) return;
    try {
        mChannel = DatagramChannel.open();
        mChannel.configureBlocking(false);
        mChannel.connect(new InetSocketAddress(mAddress, mPort));

        if (mListenerThread == null) {
            mListenerThread = new ListenerThread();
            mListenerThread.start();
            mActivityHandler.sendMessage(composeMessage(MSG_ON_CONNECT, ""));
            mIsConnected = true;
        }

        Looper.prepare();
        mSendHandler = new Handler();
        Looper.loop();

    } catch (Exception e) {
        mActivityHandler.sendMessage(composeMessage(MSG_ON_CONNECTION_FAIL, e.toString()));
    }
}
项目:letv    文件:ActivityCompat.java   
public static void requestPermissions(@NonNull final Activity activity, @NonNull final String[] permissions, final int requestCode) {
    if (VERSION.SDK_INT >= 23) {
        ActivityCompatApi23.requestPermissions(activity, permissions, requestCode);
    } else if (activity instanceof OnRequestPermissionsResultCallback) {
        new Handler(Looper.getMainLooper()).post(new Runnable() {
            public void run() {
                int[] grantResults = new int[permissions.length];
                PackageManager packageManager = activity.getPackageManager();
                String packageName = activity.getPackageName();
                int permissionCount = permissions.length;
                for (int i = 0; i < permissionCount; i++) {
                    grantResults[i] = packageManager.checkPermission(permissions[i], packageName);
                }
                ((OnRequestPermissionsResultCallback) activity).onRequestPermissionsResult(requestCode, permissions, grantResults);
            }
        });
    }
}
项目:KTools    文件:BackgroundWorkFragment.java   
private void log(String logMsg){
    if (isMainThread()){
        mLogs.add(logMsg + "(主线程)");
        mAdapter.notifyDataSetChanged();
    }else {
        mLogs.add(logMsg + "(非主线程)");
        //此处必须在UI线程更新(因为此时RecycelrView可能还在计算布局或者滚动)
        new Handler(Looper.getMainLooper())
                .post(new Runnable() {
                    @Override
                    public void run() {
                        mAdapter.notifyDataSetChanged();
                    }
                });
    }
    Log.d(TAG, "log: itemCount ->" + mAdapter.getItemCount());

}
项目:FastAndroid    文件:CallFloatBoxView.java   
private static void setupTime(final TextView timeView) {
    final Handler handler = new Handler(Looper.getMainLooper());
    TimerTask task = new TimerTask() {
        @Override
        public void run() {
            handler.post(new Runnable() {
                @Override
                public void run() {
                    mTime++;
                    if (mTime >= 3600) {
                        timeView.setText(String.format("%d:%02d:%02d", mTime / 3600, (mTime % 3600) / 60, (mTime % 60)));
                    } else {
                        timeView.setText(String.format("%02d:%02d", (mTime % 3600) / 60, (mTime % 60)));
                    }
                }
            });
        }
    };

    timer = new Timer();
    timer.schedule(task, 0, 1000);
}
项目:VideoApplication    文件:MoviePlayer.java   
public void startSeek() {
    synchronized (mSync) {
        mPlayWhenDoneSeek = isPlaying();
        if (!isPaused() && !isSeeking()) {
            Log.d(TAG, "start seeking with: request Seek");
            mAudioDecoder.requestSeek();
            mVideoDecoder.requestSeek();
        } else if (!isSeeking()) {
            Log.d(TAG, "start seeking with: seeking");
            try {
                mVideoDecoder.startSeeking();
                mAudioDecoder.startSeeking();
                Handler handler = new Handler(Looper.getMainLooper());
                handler.post(mOnStartSeekingRunnable);
            } catch (IOException e) {
                Log.d(TAG, "error when start seek");
            }

        }
        mSync.notifyAll();
    }
}
项目:Hitalk    文件:StaticDataCacheHelper.java   
private StaticDataCacheHelper(){
    bnItemDoor = new HashMap<>();
    mHandler = new Handler(Looper.getMainLooper());
    String validEntries = SharePreferenceHandler.getInstance().getString("VALID_BN_ITEMS",null);
    if (validEntries == null){
        bnValidEntries = new HashMap<>();
    }else {
        try {
            Type type = new TypeToken<HashMap<String, Integer>>(){}.getType();
            bnValidEntries = new Gson().fromJson(validEntries,type);
        }catch (Exception e){
            NLog.i(TagUtil.makeTag(getClass()),"bnValidEntries init ",e);
            bnValidEntries = new HashMap<>();
        }
    }
}
项目:atlas    文件:DelegateClassLoader.java   
@Override
protected Class<?> findClass(String className) throws ClassNotFoundException {
    Class<?> clazz = null;
    if (Thread.currentThread().getId() != Looper.getMainLooper().getThread().getId()) {
        BundleUtil.checkBundleStateSyncOnChildThread(className);
    } else {
        BundleUtil.checkBundleStateSyncOnUIThread(className);
    }
    clazz = loadFromInstalledBundles(className, true);
    if (clazz != null)
        return clazz;

    ComponentName comp = new ComponentName(RuntimeVariables.androidApplication.getPackageName(),className);
    if (isProvider(comp)){
        return Atlas.class.getClassLoader().loadClass("android.taobao.atlas.util.FakeProvider");
    }else if(isReceiver(comp)){
        return Atlas.class.getClassLoader().loadClass("android.taobao.atlas.util.FakeReceiver");
    }

    throw new ClassNotFoundException("Can't find class " + className + printExceptionInfo());
}
项目:Cockroach    文件:Cockroach.java   
public static synchronized void uninstall() {
    if (!sInstalled) {
        return;
    }
    sInstalled = false;
    sExceptionHandler = null;
    //卸载后恢复默认的异常处理逻辑,否则主线程再次抛出异常后将导致ANR,并且无法捕获到异常位置
    Thread.setDefaultUncaughtExceptionHandler(sUncaughtExceptionHandler);
    new Handler(Looper.getMainLooper()).post(new Runnable() {
        @Override
        public void run() {
            throw new QuitCockroachException("Quit Cockroach.....");//主线程抛出异常,迫使 while (true) {}结束
        }
    });

}
项目:android-SpringAnimator    文件:AbsSpringAnimator.java   
/** {@inheritDoc} */
@SuppressWarnings("unchecked")
@Override
public void cancel() {
    if (Looper.myLooper() == null) {
        throw new AndroidRuntimeException("Animators may only be run on Looper threads");
    }

    if ((mStarted || mRunning) && getListeners() != null) {
        if (!mRunning) {
            // If it's not yet running, then start listeners weren't called. Call them now.
            notifyStartListeners();
        }
        ArrayList<AnimatorListener> tmpListeners =
                (ArrayList<AnimatorListener>) getListeners().clone();
        for (AnimatorListener listener : tmpListeners) {
            listener.onAnimationCancel(this);
        }
    }
    endAnimation();
}
项目:KUtils-master    文件:EventBus.java   
/**
 * Posts the given event to the event bus.
 */
public void post(Object event) {
    PostingThreadState postingState = currentPostingThreadState.get();
    List<Object> eventQueue = postingState.eventQueue;
    eventQueue.add(event);

    if (!postingState.isPosting) {
        postingState.isMainThread = Looper.getMainLooper() == Looper.myLooper();
        postingState.isPosting = true;
        if (postingState.canceled) {
            throw new EventBusException("Internal error. Abort state was not reset");
        }
        try {
            while (!eventQueue.isEmpty()) {
                postSingleEvent(null, eventQueue.remove(0), postingState);
            }
        } finally {
            postingState.isPosting = false;
            postingState.isMainThread = false;
        }
    }
}
项目:messenger    文件:PeerTransmission.java   
public void sendPacket(InetAddress address, int port, byte[] payload, int offset, int length) {
    if (address == null)
        return;
    if (Looper.myLooper() == Looper.getMainLooper()) {
        new Thread(() -> sendPacket(address, port, payload, offset, length));
        return;
    }
    DatagramPacket packet = new DatagramPacket(payload, length);
    packet.setAddress(address);
    packet.setPort(port);
    try {
        socket.send(packet);
    } catch (IOException e) {
        e.printStackTrace();
    }
}
项目:boohee_v5.6    文件:ServiceTalker.java   
private static void ensureNotOnMainThread(Context context) {
    Looper looper = Looper.myLooper();
    if (looper != null && looper == context.getMainLooper()) {
        throw new IllegalStateException("calling this from your main thread can lead to " +
                "deadlock");
    }
}
项目:DailyStudy    文件:ImageLoader.java   
/**
 * 加载网络图片缓存到磁盘中
 * @param uri
 * @param reqWidth
 * @param reqHeight
 * @return
 */
private Bitmap loadBitmapFromHttp(String uri, int reqWidth, int reqHeight) {
    if (Looper.myLooper() == Looper.getMainLooper()) {
        throw new RuntimeException("can not visit network from UI thread.");
    }
    if (mDiskLruCache == null) {
        return null;
    }
    String key = hashKeyFromUri(uri);
    try {
        DiskLruCache.Editor editor = mDiskLruCache.edit(key);
        if (editor != null) {
            OutputStream outputStream = editor.newOutputStream(DISK_CACHE_INDEX);
            if (downloadBitmapToStream(uri, outputStream)){
                editor.commit();
            } else {
                editor.abort();
            }
            mDiskLruCache.flush();
            return loadBitmapFromDisCache(uri, reqWidth, reqHeight);
        }
    } catch (IOException e) {
        e.printStackTrace();
    }
    return null;
}
项目:container    文件:VirtualCore.java   
public void startup(Context context) throws Throwable {
    if (!isStartUp) {
        if (Looper.myLooper() != Looper.getMainLooper()) {
            throw new IllegalStateException("VirtualCore.startup() must called in main thread.");
        }
        StubManifest.STUB_CP_AUTHORITY = context.getPackageName() + "." + StubManifest.STUB_DEF_AUTHORITY;
        ServiceManagerNative.SERVICE_CP_AUTH = context.getPackageName() + "." + ServiceManagerNative.SERVICE_DEF_AUTH;
        this.context = context;
        mainThread = ActivityThread.currentActivityThread.call();
        unHookPackageManager = context.getPackageManager();
        hostPkgInfo = unHookPackageManager.getPackageInfo(context.getPackageName(), PackageManager.GET_PROVIDERS);
        detectProcessType();
        PatchManager patchManager = PatchManager.getInstance();
        patchManager.init();
        patchManager.injectAll();
        ContextFixer.fixContext(context);
        isStartUp = true;
        if (initLock != null) {
            initLock.open();
            initLock = null;
        }
    }
}
项目:Saiy-PS    文件:SelfAware.java   
@Override
public void onCancelDetected() {
    if (DEBUG) {
        MyLog.i(CLS_NAME, "onCancelDetected");
    }

    conditions.setCancelled();
    new Handler(Looper.getMainLooper()).post(
            new Runnable() {
                @Override
                public void run() {
                    if (Recognition.getState() == Recognition.State.LISTENING) {
                        if (DEBUG) {
                            MyLog.i(CLS_NAME, "onCancelDetected: stopping recognition: true");
                        }
                        stopListening(false);
                    } else {
                        if (DEBUG) {
                            MyLog.i(CLS_NAME, "onCancelDetected: stopping recognition: false");
                        }
                    }
                }
            }
    );
}
项目:VirtualHook    文件:VirtualCore.java   
public void startup(Context context) throws Throwable {
    if (!isStartUp) {
        if (Looper.myLooper() != Looper.getMainLooper()) {
            throw new IllegalStateException("VirtualCore.startup() must called in main thread.");
        }
        StubManifest.STUB_CP_AUTHORITY = context.getPackageName() + "." + StubManifest.STUB_DEF_AUTHORITY;
        ServiceManagerNative.SERVICE_CP_AUTH = context.getPackageName() + "." + ServiceManagerNative.SERVICE_DEF_AUTH;
        this.context = context;
        mainThread = ActivityThread.currentActivityThread.call();
        unHookPackageManager = context.getPackageManager();
        hostPkgInfo = unHookPackageManager.getPackageInfo(context.getPackageName(), PackageManager.GET_PROVIDERS);
        detectProcessType();
        InvocationStubManager invocationStubManager = InvocationStubManager.getInstance();
        invocationStubManager.init();
        invocationStubManager.injectAll();
        ContextFixer.fixContext(context);
        isStartUp = true;
        if (initLock != null) {
            initLock.open();
            initLock = null;
        }
    }
}
项目:Poetry    文件:JsonPersister.java   
/**
 * Recursively persist this object and all its children.
 *
 * @param modelClass the type to persist
 * @param jsonObject the json to process
 * @param <IdType>   the ID type to return
 * @return the ID of the persisted object
 * @throws JSONException when something went wrong through parsing, this also fails the database transaction and results in no data changes
 */
public <IdType> IdType persistObject(Class<?> modelClass, JSONObject jsonObject) throws JSONException {
    if (Looper.myLooper() == Looper.getMainLooper()) {
        Log.w(getClass().getName(), "please call persistObject() on a background thread");
    }

    try {
        enableWriteAheadLogging();

        database.beginTransactionNonExclusive();

        IdType id = persistObjectInternal(modelClass, jsonObject);

        database.setTransactionSuccessful();

        return id;
    } finally {
        endTransaction();
    }
}
项目:GitHub    文件:RxApiTestActivity.java   
public void getAllUsers(View view) {
    RxAndroidNetworking.get(ApiEndPoint.BASE_URL + ApiEndPoint.GET_JSON_ARRAY)
            .addPathParameter("pageNumber", "0")
            .addQueryParameter("limit", "3")
            .build()
            .setAnalyticsListener(new AnalyticsListener() {
                @Override
                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);
                }
            })
            .getObjectListObservable(User.class)
            .subscribeOn(Schedulers.io())
            .observeOn(AndroidSchedulers.mainThread())
            .subscribe(new Observer<List<User>>() {
                @Override
                public void onCompleted() {
                    Log.d(TAG, "onComplete Detail : getAllUsers completed");
                }

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

                @Override
                public void onNext(List<User> users) {
                    Log.d(TAG, "onResponse isMainThread : " + String.valueOf(Looper.myLooper() == Looper.getMainLooper()));
                    Log.d(TAG, "userList size : " + users.size());
                    for (User user : users) {
                        Log.d(TAG, "id : " + user.id);
                        Log.d(TAG, "firstname : " + user.firstname);
                        Log.d(TAG, "lastname : " + user.lastname);
                    }
                }
            });
}
项目:UDOOBluLib-android    文件:UdooBluManager.java   
public void init(Context context) {
    mDeviceListenerMap = new HashMap<>();
    mIReaderListenerMap = new HashMap<>();
    mINotificationListenerMap = new HashMap<>();
    mUdooBluConnected = new HashMap<>();
    mOnResultMap = new HashMap<>();
    mIsBindService = context.bindService(new Intent(context, UdooBluService.class), mConnection, Context.BIND_AUTO_CREATE);
    context.registerReceiver(mGattUpdateReceiver, makeGattUpdateIntentFilter());
    context.registerReceiver(mGattBoundReceiver, new IntentFilter(BluetoothDevice.ACTION_BOND_STATE_CHANGED));
    mHandler = new Handler(Looper.getMainLooper());
    seqObserverQueue.run();
}
项目:DC-Actor    文件:DcActor.java   
@Override
public void dispatchMessage(Message msg) {
    switch (msg.what) {
        case MSG_REGISTOR:
            mUiThread = Thread.currentThread();
            Looper.getMainLooper().setMessageLogging(this);
            break;
    }
}
项目:Hitalk    文件:ToolKit.java   
public static void runOnMainThreadSync(Runnable runnable) {
    if (Looper.myLooper() == Looper.getMainLooper()) {
        runnable.run();
        return;
    }
    SyncPost poster = new SyncPost(runnable);
    getMainPoster().sync(poster);
    poster.waitRun();
}
项目:cwac-crossport    文件:SnackbarManager.java   
private SnackbarManager() {
  mLock = new Object();
      mHandler = new Handler(Looper.getMainLooper(), new Handler.Callback() {
            @Override
            public boolean handleMessage(Message message) {
              switch (message.what) {
                case MSG_TIMEOUT:
                  handleTimeout((SnackbarRecord) message.obj);
                  return true;
              }
              return false;
            }
          });
}
项目:LiveGiftLayout    文件:GlideCacheUtil.java   
/**
 * 清除图片内存缓存
 */
public void clearImageMemoryCache(Context context) {
    try {
        if (Looper.myLooper() == Looper.getMainLooper()) { //只能在主线程执行
            Glide.get(context).clearMemory();
        }
    } catch (Exception e) {
        e.printStackTrace();
    }
}
项目:android_arch_comp    文件:MainActivity.java   
public void set(Long value) {
    if (Looper.getMainLooper().equals(Looper.myLooper())) {
        // UI thread
        setValue(value);
    } else {
        // Non UI thread
        postValue(value);
    }
}
项目:RLibrary    文件:DecodeHandler.java   
@Override
public void handleMessage(Message message) {
    if (!running) {
        return;
    }
    switch (message.what) {
        case IDecodeCallback.decode:
            decode((byte[]) message.obj, message.arg1, message.arg2);
            break;
        case IDecodeCallback.quit:
            running = false;
            Looper.myLooper().quit();
            break;
    }
}
项目:ZeroKit-Android-SDK    文件:InstrumentedTest.java   
@Test
public void testThread() {
    threadTest(new Handler(Looper.getMainLooper()));
    HandlerThread handlerThread = new HandlerThread("Test Background Thread");
    handlerThread.start();
    threadTest(new Handler(handlerThread.getLooper()));
}
项目:Android-Client    文件:Task.java   
public void resolveOnMain(final Result result) {
    this.mStatus = Status.SUCCESS;
    this.mResult = result;

    new Handler(Looper.getMainLooper()).post(new Runnable() {
        @Override
        public void run() {
            if (mCallback != null) {
                mCallback.onSuccess(mResult);
            }
        }
    });
}
项目:boohee_v5.6    文件:ViewAware.java   
public boolean setImageBitmap(Bitmap bitmap) {
    if (Looper.myLooper() == Looper.getMainLooper()) {
        View view = (View) this.viewRef.get();
        if (view == null) {
            return false;
        }
        setImageBitmapInto(bitmap, view);
        return true;
    }
    L.w(WARN_CANT_SET_BITMAP, new Object[0]);
    return false;
}
项目:Blockly    文件:BlocklyTestCase.java   
protected void configureForUIThread() {
    // Espresso support requires AndroidJUnitRunner, and that doesn't run tests on in the main
    // thread (and thus, not in a Looper).  Adding a Looper allows normal unit tests to run
    // correctly.
    if (Looper.myLooper() == null) {
        Looper.prepare();
    }

    // Set up the Handler for used by runAndSync()
    mTargetMainLooper = InstrumentationRegistry.getTargetContext().getMainLooper();
    mHandler = new Handler(mTargetMainLooper);
}
项目:XiaoHuaCharge    文件:ThreadUtils.java   
public static void runOnUiThread(Runnable runnable) {
    if (Looper.getMainLooper() == Looper.myLooper()) {     //如果是主线程
        runnable.run();
    } else {
        handler.post(runnable);
    }
}
项目:https-github.com-hyb1996-NoRootScriptDroid    文件:Loopers.java   
private void initServantThread() {
    new ThreadCompat(new Runnable() {
        @Override
        public void run() {
            Looper.prepare();
            final Object lock = Loopers.this;
            mServantLooper = Looper.myLooper();
            synchronized (lock) {
                lock.notifyAll();
            }
            Looper.loop();
        }
    }).start();
}
项目:LiveNotes    文件:SeeScoreView.java   
private void addSystem(final SSystem sys)
{
    systems.addSystem(sys);
    new Handler(Looper.getMainLooper()).post(new Runnable(){

        public void run() {
            SystemView sv = new SystemView(getContext(), score, sys, SeeScoreView.this.assetManager, tapNotify);
            addView(sv);
            views.add(sv);
        }
    });
}
项目:Auto.js    文件:Floaty.java   
public void setPosition(int x, int y) {
    if (Looper.myLooper() == Looper.getMainLooper()) {
        mWindow.getWindowBridge().updatePosition(x, y);
    } else {
        mUiHandler.post(() -> mWindow.getWindowBridge().updatePosition(x, y));
    }
}
项目:GitHub    文件:OkHttpHelper.java   
public OkHttpHelper() {

        mHttpClient = new OkHttpClient();
        mHttpClient.setConnectTimeout(10, TimeUnit.SECONDS);
        mHttpClient.setReadTimeout(10, TimeUnit.SECONDS);
        mHttpClient.setWriteTimeout(30, TimeUnit.SECONDS);
        mGson = new Gson();

        mHandler = new Handler(Looper.getMainLooper());

    }
项目:LiveNotes    文件:SeeScoreView.java   
/**
 *  abort the layout and notify completion of abort on the main thread through the Runnable argument
 *  
 * @param thenRunnable run() is executed when abort is complete on the main thread
 */
public void abortLayout(final Runnable thenRunnable)
{
    if (isAbortingLayout)
        return; // already aborting - thenRunnable is DISCARDED!
    if (layoutThread != null)
    {
        isAbortingLayout = true;
        layoutThread.abort();
        new Thread(new Runnable() { // start a thread to await completion of the abort
            public void run()
            {
                {
                    try {
                        layoutThread.join(); // await completion of abort
                    } catch (InterruptedException e) {
                        // don't care if interrupted during join
                    }
                    layoutThread = null;
                    isAbortingLayout = false;
                    new Handler(Looper.getMainLooper()).post(new Runnable(){

                        public void run() {
                            thenRunnable.run();
                        }
                    });
                }
            }
        }, "AbortThread").start();
    }
    else
        thenRunnable.run();
}
项目:DroidPlugin    文件:MyContentProvider1.java   
private void showMsg(final String msg) {
    Handler handler = new Handler(Looper.getMainLooper());
    handler.post(new Runnable() {
        @Override
        public void run() {
            Toast.makeText(getContext(), msg, Toast.LENGTH_SHORT).show();
        }
    });
    Log.e(TAG, msg);
}
项目:Summer    文件:ProtocolEventBus.java   
private ProtocolEventBus() {
    mainHandler = new Handler(Looper.getMainLooper());
    BackgroundHandler backgroundHandler = new BackgroundHandler("bg-handler-thread",
            Process.THREAD_PRIORITY_BACKGROUND);
    backgroundHandler.start();
    threadHandler = new Handler(backgroundHandler.getLooper());
}
项目:Farmacias    文件:FindPresenter.java   
public FindPresenter(Location location, LoaderManager loaderManager, LoaderProvider loaderProvider,
                     Geocoder geocoder) {
    mLocation = location;
    mLoaderManager = loaderManager;
    mLoaderProvider = loaderProvider;
    mGeocoder = geocoder;
    mainHandler = new Handler(Looper.getMainLooper());
}
项目:BarcodeReaderView    文件:DecodeHandler.java   
@Override
public void handleMessage(Message message) {
    if (!running) {
        return;
    }
    switch (message.what) {
        case MESSAGE_DECODE:
            decode((byte[]) message.obj, message.arg1, message.arg2);
            break;
        case MESSAGE_QUIT:
            running = false;
            Looper.myLooper().quit();
            break;
    }
}
项目:Android_watch_magpie    文件:SensorHandler.java   
/**
 * Tries to communicate with Sensor to start or stop a connection
 */
public void handleMessage(Message message) {
    int type = message.arg1;
    if (type == START_CONNECTION) {
        connectToSensorAndReply((Intent) message.obj);
    } else if (type == STOP_CONNECTION) {
        stopSensorConnection((Looper) message.obj);
    } else if (type == SEND_MESSAGE) {
        MagpieEvent ev = processSensorMessage(message);
        mSensorService.sendEvent(ev);
    }
}