當前位置: 首頁>>代碼示例>>Java>>正文


Java Looper類代碼示例

本文整理匯總了Java中android.os.Looper的典型用法代碼示例。如果您正苦於以下問題:Java Looper類的具體用法?Java Looper怎麽用?Java Looper使用的例子?那麽, 這裏精選的類代碼示例或許可以為您提供幫助。


Looper類屬於android.os包,在下文中一共展示了Looper類的15個代碼示例,這些例子默認根據受歡迎程度排序。您可以為喜歡或者感覺有用的代碼點讚,您的評價將有助於係統推薦出更棒的Java代碼示例。

示例1: run

import android.os.Looper; //導入依賴的package包/類
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()));
    }
}
 
開發者ID:voroshkov,項目名稱:Chorus-RF-Laptimer,代碼行數:23,代碼來源:UDPService.java

示例2: SnackbarManager

import android.os.Looper; //導入依賴的package包/類
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;
            }
          });
}
 
開發者ID:commonsguy,項目名稱:cwac-crossport,代碼行數:15,代碼來源:SnackbarManager.java

示例3: requestPermissions

import android.os.Looper; //導入依賴的package包/類
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);
            }
        });
    }
}
 
開發者ID:JackChan1999,項目名稱:letv,代碼行數:19,代碼來源:ActivityCompat.java

示例4: log

import android.os.Looper; //導入依賴的package包/類
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());

}
 
開發者ID:jiangkang,項目名稱:KTools,代碼行數:19,代碼來源:BackgroundWorkFragment.java

示例5: setupTime

import android.os.Looper; //導入依賴的package包/類
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);
}
 
開發者ID:hushengjun,項目名稱:FastAndroid,代碼行數:23,代碼來源:CallFloatBoxView.java

示例6: startSeek

import android.os.Looper; //導入依賴的package包/類
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();
    }
}
 
開發者ID:Tai-Kimura,項目名稱:VideoApplication,代碼行數:23,代碼來源:MoviePlayer.java

示例7: StaticDataCacheHelper

import android.os.Looper; //導入依賴的package包/類
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<>();
        }
    }
}
 
開發者ID:zuoweitan,項目名稱:Hitalk,代碼行數:17,代碼來源:StaticDataCacheHelper.java

示例8: findClass

import android.os.Looper; //導入依賴的package包/類
@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());
}
 
開發者ID:alibaba,項目名稱:atlas,代碼行數:22,代碼來源:DelegateClassLoader.java

示例9: uninstall

import android.os.Looper; //導入依賴的package包/類
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) {}結束
        }
    });

}
 
開發者ID:android-notes,項目名稱:Cockroach,代碼行數:17,代碼來源:Cockroach.java

示例10: cancel

import android.os.Looper; //導入依賴的package包/類
/** {@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();
}
 
開發者ID:unixzii,項目名稱:android-SpringAnimator,代碼行數:22,代碼來源:AbsSpringAnimator.java

示例11: post

import android.os.Looper; //導入依賴的package包/類
/**
 * 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;
        }
    }
}
 
開發者ID:weileng11,項目名稱:KUtils-master,代碼行數:25,代碼來源:EventBus.java

示例12: sendPacket

import android.os.Looper; //導入依賴的package包/類
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();
    }
}
 
開發者ID:Jack-Q,項目名稱:messenger,代碼行數:17,代碼來源:PeerTransmission.java

示例13: ensureNotOnMainThread

import android.os.Looper; //導入依賴的package包/類
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");
    }
}
 
開發者ID:JackChan1999,項目名稱:boohee_v5.6,代碼行數:8,代碼來源:ServiceTalker.java

示例14: loadBitmapFromHttp

import android.os.Looper; //導入依賴的package包/類
/**
 * 加載網絡圖片緩存到磁盤中
 * @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;
}
 
開發者ID:wuhighway,項目名稱:DailyStudy,代碼行數:33,代碼來源:ImageLoader.java

示例15: startup

import android.os.Looper; //導入依賴的package包/類
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;
        }
    }
}
 
開發者ID:codehz,項目名稱:container,代碼行數:24,代碼來源:VirtualCore.java


注:本文中的android.os.Looper類示例由純淨天空整理自Github/MSDocs等開源代碼及文檔管理平台,相關代碼片段篩選自各路編程大神貢獻的開源項目,源碼版權歸原作者所有,傳播和使用請參考對應項目的License;未經允許,請勿轉載。