Java Code Examples for android.os.Looper

The following are top voted examples for showing how to use android.os.Looper. These examples are extracted from open source projects. You can vote up the examples you like and your votes will be used in our system to generate more good examples.
Example 1
Project: letv   File: ActivityCompat.java   Source Code and License 7 votes vote down vote up
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);
            }
        });
    }
}
 
Example 2
Project: Chorus-RF-Laptimer   File: UDPService.java   Source Code and License 7 votes vote down vote up
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()));
    }
}
 
Example 3
Project: cwac-crossport   File: SnackbarManager.java   Source Code and License 6 votes vote down vote up
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;
            }
          });
}
 
Example 4
Project: KTools   File: BackgroundWorkFragment.java   Source Code and License 6 votes vote down vote up
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());

}
 
Example 5
Project: FastAndroid   File: CallFloatBoxView.java   Source Code and License 6 votes vote down vote up
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);
}
 
Example 6
Project: VideoApplication   File: MoviePlayer.java   Source Code and License 6 votes vote down vote up
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();
    }
}
 
Example 7
Project: Hitalk   File: StaticDataCacheHelper.java   Source Code and License 6 votes vote down vote up
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<>();
        }
    }
}
 
Example 8
Project: atlas   File: DelegateClassLoader.java   Source Code and License 6 votes vote down vote up
@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());
}
 
Example 9
Project: Cockroach   File: Cockroach.java   Source Code and License 6 votes vote down vote up
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) {}结束
        }
    });

}
 
Example 10
Project: android-SpringAnimator   File: AbsSpringAnimator.java   Source Code and License 6 votes vote down vote up
/** {@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();
}
 
Example 11
Project: KUtils-master   File: EventBus.java   Source Code and License 6 votes vote down vote up
/**
 * 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;
        }
    }
}
 
Example 12
Project: messenger   File: PeerTransmission.java   Source Code and License 6 votes vote down vote up
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();
    }
}
 
Example 13
Project: boohee_v5.6   File: ServiceTalker.java   Source Code and License 6 votes vote down vote up
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");
    }
}
 
Example 14
Project: DailyStudy   File: ImageLoader.java   Source Code and License 6 votes vote down vote up
/**
 * 加载网络图片缓存到磁盘中
 * @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;
}
 
Example 15
Project: container   File: VirtualCore.java   Source Code and License 6 votes vote down vote up
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;
        }
    }
}
 
Example 16
Project: Saiy-PS   File: SelfAware.java   Source Code and License 6 votes vote down vote up
@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");
                        }
                    }
                }
            }
    );
}
 
Example 17
Project: VirtualHook   File: VirtualCore.java   Source Code and License 6 votes vote down vote up
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;
        }
    }
}
 
Example 18
Project: Poetry   File: JsonPersister.java   Source Code and License 6 votes vote down vote up
/**
 * 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();
	}
}
 
Example 19
Project: GitHub   File: RxApiTestActivity.java   Source Code and License 5 votes vote down vote up
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);
                    }
                }
            });
}
 
Example 20
Project: UDOOBluLib-android   File: UdooBluManager.java   Source Code and License 5 votes vote down vote up
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();
}
 
Example 21
Project: DC-Actor   File: DcActor.java   Source Code and License 5 votes vote down vote up
@Override
public void dispatchMessage(Message msg) {
    switch (msg.what) {
        case MSG_REGISTOR:
            mUiThread = Thread.currentThread();
            Looper.getMainLooper().setMessageLogging(this);
            break;
    }
}
 
Example 22
Project: Hitalk   File: ToolKit.java   Source Code and License 5 votes vote down vote up
public static void runOnMainThreadSync(Runnable runnable) {
    if (Looper.myLooper() == Looper.getMainLooper()) {
        runnable.run();
        return;
    }
    SyncPost poster = new SyncPost(runnable);
    getMainPoster().sync(poster);
    poster.waitRun();
}
 
Example 23
Project: LiveGiftLayout   File: GlideCacheUtil.java   Source Code and License 5 votes vote down vote up
/**
 * 清除图片内存缓存
 */
public void clearImageMemoryCache(Context context) {
    try {
        if (Looper.myLooper() == Looper.getMainLooper()) { //只能在主线程执行
            Glide.get(context).clearMemory();
        }
    } catch (Exception e) {
        e.printStackTrace();
    }
}
 
Example 24
Project: android_arch_comp   File: MainActivity.java   Source Code and License 5 votes vote down vote up
public void set(Long value) {
    if (Looper.getMainLooper().equals(Looper.myLooper())) {
        // UI thread
        setValue(value);
    } else {
        // Non UI thread
        postValue(value);
    }
}
 
Example 25
Project: RLibrary   File: DecodeHandler.java   Source Code and License 5 votes vote down vote up
@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;
    }
}
 
Example 26
Project: ZeroKit-Android-SDK   File: InstrumentedTest.java   Source Code and License 5 votes vote down vote up
@Test
public void testThread() {
    threadTest(new Handler(Looper.getMainLooper()));
    HandlerThread handlerThread = new HandlerThread("Test Background Thread");
    handlerThread.start();
    threadTest(new Handler(handlerThread.getLooper()));
}
 
Example 27
Project: Android-Client   File: Task.java   Source Code and License 5 votes vote down vote up
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);
            }
        }
    });
}
 
Example 28
Project: boohee_v5.6   File: ViewAware.java   Source Code and License 5 votes vote down vote up
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;
}
 
Example 29
Project: Blockly   File: BlocklyTestCase.java   Source Code and License 5 votes vote down vote up
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);
}
 
Example 30
Project: XiaoHuaCharge   File: ThreadUtils.java   Source Code and License 5 votes vote down vote up
public static void runOnUiThread(Runnable runnable) {
    if (Looper.getMainLooper() == Looper.myLooper()) {     //如果是主线程
        runnable.run();
    } else {
        handler.post(runnable);
    }
}
 
Example 31
Project: https-github.com-hyb1996-NoRootScriptDroid   File: Loopers.java   Source Code and License 5 votes vote down vote up
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();
}
 
Example 32
Project: LiveNotes   File: SeeScoreView.java   Source Code and License 5 votes vote down vote up
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);
		}
	});
}
 
Example 33
Project: Auto.js   File: Floaty.java   Source Code and License 5 votes vote down vote up
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));
    }
}
 
Example 34
Project: GitHub   File: OkHttpHelper.java   Source Code and License 5 votes vote down vote up
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());

    }
 
Example 35
Project: LiveNotes   File: SeeScoreView.java   Source Code and License 5 votes vote down vote up
/**
 *  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();
}
 
Example 36
Project: DroidPlugin   File: MyContentProvider1.java   Source Code and License 5 votes vote down vote up
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);
}
 
Example 37
Project: Summer   File: ProtocolEventBus.java   Source Code and License 5 votes vote down vote up
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());
}
 
Example 38
Project: Farmacias   File: FindPresenter.java   Source Code and License 5 votes vote down vote up
public FindPresenter(Location location, LoaderManager loaderManager, LoaderProvider loaderProvider,
                     Geocoder geocoder) {
    mLocation = location;
    mLoaderManager = loaderManager;
    mLoaderProvider = loaderProvider;
    mGeocoder = geocoder;
    mainHandler = new Handler(Looper.getMainLooper());
}
 
Example 39
Project: BarcodeReaderView   File: DecodeHandler.java   Source Code and License 5 votes vote down vote up
@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;
    }
}
 
Example 40
Project: Android_watch_magpie   File: SensorHandler.java   Source Code and License 5 votes vote down vote up
/**
 * 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);
    }
}