Java Code Examples for android.os.Looper#getMainLooper()

The following examples show how to use android.os.Looper#getMainLooper() . You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: IjkMediaPlayer.java    From IjkPlayerDemo with Apache License 2.0 6 votes vote down vote up
private void initPlayer(IjkLibLoader libLoader) {
    loadLibrariesOnce(libLoader);
    initNativeOnce();

    Looper looper;
    if ((looper = Looper.myLooper()) != null) {
        mEventHandler = new EventHandler(this, looper);
    } else if ((looper = Looper.getMainLooper()) != null) {
        mEventHandler = new EventHandler(this, looper);
    } else {
        mEventHandler = null;
    }

    /*
     * Native setup requires a weak reference to our object. It's easier to
     * create it here than in C++.
     */
    native_setup(new WeakReference<IjkMediaPlayer>(this));
}
 
Example 2
Source File: ArchiveUtil.java    From lrkFM with MIT License 6 votes vote down vote up
boolean doCreateZip(CopyOnWriteArrayList<FMFile> files, File destination) throws BlockingStuffOnMainThreadException {
    if (Looper.myLooper() == Looper.getMainLooper()) {
        throw new BlockingStuffOnMainThreadException();
    }
    try {
        FileOutputStream fos = new FileOutputStream(destination);
        ZipOutputStream zipOut = new ZipOutputStream(fos);
        for (FMFile f : files) {
            addFileToZip(f.getFile(), f.getName(), zipOut);
        }
        zipOut.close();
        fos.close();
        return true;
    } catch (IOException e) {
        Log.e(TAG, "unable to create zip file!", e);
    }
    return false;
}
 
Example 3
Source File: FFMpegPlayer.java    From letv with Apache License 2.0 6 votes vote down vote up
public FFMpegPlayer(Context context) {
    this.mStartPlayCounts = 0;
    this.mNativeData = 0;
    this.mWakeLock = null;
    this.mGlRenderControler = null;
    this.mSourceType = 0;
    this.mStartPlayCounts = 0;
    Looper looper = Looper.myLooper();
    if (looper != null) {
        this.mEventHandler = new EventHandler(this, looper);
    } else {
        looper = Looper.getMainLooper();
        if (looper != null) {
            this.mEventHandler = new EventHandler(this, looper);
        } else {
            this.mEventHandler = null;
        }
    }
    native_setup(new WeakReference(this));
    this.mContext = context;
    this.mSourceType = 0;
}
 
Example 4
Source File: OBRunnableUI.java    From GLEXP-Team-onebillion with Apache License 2.0 6 votes vote down vote up
@Override
public void run()
{
    if(Looper.myLooper() == Looper.getMainLooper())
        ex();
    else
    {
        new Handler(Looper.getMainLooper()).post(
                new Runnable()
                {
                    public void run()
                    {
                        ex();
                    }
                });
    }
}
 
Example 5
Source File: AgentWebX5Utils.java    From AgentWebX5 with Apache License 2.0 6 votes vote down vote up
public static final void clearWebView(WebView m) {

        if (m == null)
            return;
        if (Looper.myLooper() != Looper.getMainLooper())
            return;
        m.loadUrl("about:blank");
        m.stopLoading();
        if (m.getHandler() != null)
            m.getHandler().removeCallbacksAndMessages(null);
        m.removeAllViews();
        /*ViewGroup mViewGroup = null;
        if ((mViewGroup = ((ViewGroup) m.getParent())) != null)
            mViewGroup.removeView(m);*/
        m.setWebChromeClient(null);
        m.setWebViewClient(null);
        m.setTag(null);
        m.clearHistory();
        m.destroy();
        m = null;


    }
 
Example 6
Source File: MainThreadTasksHolder.java    From RairDemo with Apache License 2.0 5 votes vote down vote up
@Override
protected void notifyListeners(final T data) {
    if (Looper.myLooper() == Looper.getMainLooper()) {
        super.notifyListeners(data);
    } else {
        HANDLER.post(new Runnable() {
            @Override
            public void run() {
                MainThreadTasksHolder.super.notifyListeners(data);
            }
        });
    }
}
 
Example 7
Source File: FileScanner.java    From sketch with Apache License 2.0 5 votes vote down vote up
public boolean execute(File[] dirs) {
    if (running || dirs == null || dirs.length == 0 || fileChecker == null || scanListener == null) {
        return false;
    }

    this.running = true;
    this.canceled = false;
    if (callbackHandler == null) {
        callbackHandler = new CallbackHandler(Looper.getMainLooper());
    }

    callbackHandler.callbackStarted();
    new Thread(new MultiThreadScanTask(dirs, this, threadCount)).start();
    return true;
}
 
Example 8
Source File: CameraOld.java    From EvilsLive with MIT License 5 votes vote down vote up
private void runMainHanlder(final Camera.Size previewSize) {
    Handler mainHanlder = new Handler(Looper.getMainLooper());
    mainHanlder.post(new Runnable() {
        @Override
        public void run() {
            adjustViewSize(previewSize);
        }
    });
}
 
Example 9
Source File: HttpRequest.java    From Android with MIT License 5 votes vote down vote up
private HttpRequest() {
    OkHttpClient.Builder builder = new OkHttpClient.Builder()
            .connectTimeout(10000L, TimeUnit.MILLISECONDS)
            .readTimeout(10000L, TimeUnit.MILLISECONDS)
            .writeTimeout(10000L, TimeUnit.MILLISECONDS)
            .addInterceptor(new LoggerInterceptor(false))
            .hostnameVerifier(new HostnameVerifier() {
                @Override
                public boolean verify(String hostname, SSLSession session) {
                    return true;
                }
            });
    mOkHttpClient = builder.build();
    mDelivery = new Handler(Looper.getMainLooper());
}
 
Example 10
Source File: MainThreadTasksHolder.java    From RairDemo with Apache License 2.0 5 votes vote down vote up
@Override
protected void notifyErrorListener(final Task<Throwable> task) {
    if (Looper.myLooper() == Looper.getMainLooper()) {
        super.notifyErrorListener(task);
    } else {
        HANDLER.post(new Runnable() {
            @Override
            public void run() {
                MainThreadTasksHolder.super.notifyErrorListener(task);
            }
        });
    }
}
 
Example 11
Source File: MainActivity.java    From android_gisapp with GNU General Public License v3.0 5 votes vote down vote up
protected void stopRefresh(final MenuItem refreshItem) {
    Handler handler = new Handler(Looper.getMainLooper());
    final Runnable r = new Runnable() {
        public void run() {
            if (refreshItem != null && refreshItem.getActionView() != null) {
                refreshItem.getActionView().clearAnimation();
                refreshItem.setActionView(null);
            }
        }
    };
    handler.post(r);
}
 
Example 12
Source File: ExampleAdapter.java    From FlexibleAdapter with Apache License 2.0 5 votes vote down vote up
public ExampleAdapter(List<AbstractFlexibleItem> items, Object listeners) {
    // stableIds ? true = Items implement hashCode() so they can have stableIds!
    super(items, listeners, true);

    // In case you need a Handler, do this:
    // - Overrides the internal Handler with a custom callback that extends the internal one
    mHandler = new Handler(Looper.getMainLooper(), new MyHandlerCallback());
}
 
Example 13
Source File: VLCObject.java    From vlc-example-streamplayer with GNU General Public License v3.0 5 votes vote down vote up
/**
 * Set an event listener and an executor Handler
 * @param listener see {@link VLCEvent.Listener}
 * @param handler Handler in which events are sent. If null, a handler will be created running on the main thread
 */
protected synchronized void setEventListener(VLCEvent.Listener<T> listener, Handler handler) {
    if (mHandler != null)
        mHandler.removeCallbacksAndMessages(null);
    mEventListener = listener;
    if (mEventListener == null)
        mHandler = null;
    else if (mHandler == null)
        mHandler = handler != null ? handler : new Handler(Looper.getMainLooper());
}
 
Example 14
Source File: BaseEncoder.java    From ScreenCapture with MIT License 5 votes vote down vote up
/**
 * Must call in a worker handler thread!
 */
@Override
public void prepare() throws IOException {
    if (Looper.myLooper() == null
            || Looper.myLooper() == Looper.getMainLooper()) {
        throw new IllegalStateException("should run in a HandlerThread");
    }
    if (mEncoder != null) {
        throw new IllegalStateException("prepared!");
    }
    MediaFormat format = createMediaFormat();
    Log.d("Encoder", "Create media format: " + format);

    String mimeType = format.getString(MediaFormat.KEY_MIME);
    final MediaCodec encoder = createEncoder(mimeType);
    try {
        if (this.mCallback != null) {
            // NOTE: MediaCodec maybe crash on some devices due to null callback
            encoder.setCallback(mCodecCallback);
        }
        encoder.configure(format, null, null, MediaCodec.CONFIGURE_FLAG_ENCODE);
        onEncoderConfigured(encoder);
        encoder.start();
    } catch (MediaCodec.CodecException e) {
        Log.e("Encoder", "Configure codec failure!\n  with format" + format, e);
        throw e;
    }
    mEncoder = encoder;
}
 
Example 15
Source File: Falcon.java    From incubator-weex-playground with Apache License 2.0 4 votes vote down vote up
private static Bitmap takeBitmapUnchecked(Activity activity) throws InterruptedException {
    final List<ViewRootData> viewRoots = getRootViews(activity);
    int statusBarHeight = ScreenShot.getStatusBarHeight1(activity);
    int actionBarHeight = ScreenShot.getActionBarHeight(activity);

    View main = activity.getWindow().getDecorView();
    int mainWidth = main.getWidth();
    int mainHeight = main.getHeight();

    int baseWidth = 750;
    float widthScale = ((float) baseWidth) / mainWidth;

    // 新建立矩阵 按照宽度缩放因子自适应缩放
    Matrix matrix = new Matrix();
    matrix.postScale(widthScale, widthScale);

    Bitmap bitmap1 = Bitmap.createBitmap(main.getWidth(), main.getHeight(), ARGB_8888);
    final Bitmap bitmap = Bitmap.createBitmap(bitmap1, 0, statusBarHeight + actionBarHeight,
            mainWidth, mainHeight - statusBarHeight - actionBarHeight, matrix, true);


    // We need to do it in main thread
    if (Looper.myLooper() == Looper.getMainLooper()) {
        drawRootsToBitmap(viewRoots, bitmap);
    } else {
        final CountDownLatch latch = new CountDownLatch(1);
        activity.runOnUiThread(new Runnable() {
            @Override
            public void run() {
                try {
                    drawRootsToBitmap(viewRoots, bitmap);
                }
                finally {
                    latch.countDown();
                }
            }
        });

        latch.await();
    }

    return bitmap;
}
 
Example 16
Source File: MediaPlayer.java    From video-player with MIT License 4 votes vote down vote up
public MediaPlayer(Context ctx, boolean preferHWDecoder) {
   mContext = ctx;

   String LIB_ROOT;
if(VERSION.SDK_INT > 23) {
   	LIB_ROOT = Vitamio.getLibraryPath();
   }
   else if(VERSION.SDK_INT > 20) {
       LIB_ROOT = "";
   }
   else{
   	LIB_ROOT = Vitamio.getLibraryPath();
   }

   if (preferHWDecoder) {
     if (!NATIVE_OMX_LOADED.get()) {
       if (Build.VERSION.SDK_INT > 17)
       	load_omxnative_lib( LIB_ROOT , "libOMX.18.so");
       
       else if (Build.VERSION.SDK_INT > 13)
       	load_omxnative_lib( LIB_ROOT ,  "libOMX.14.so");
       else if (Build.VERSION.SDK_INT > 10)
       	load_omxnative_lib( LIB_ROOT , "libOMX.11.so");
       else
       	load_omxnative_lib( LIB_ROOT ,  "libOMX.9.so");
       NATIVE_OMX_LOADED.set(true);
     }
   } else {
     try {
       unloadOMX_native();
     } catch (UnsatisfiedLinkError e) {
       Log.e("unloadOMX failed %s", e.toString());
     }
     NATIVE_OMX_LOADED.set(false);
   }

   Looper looper;
   if ((looper = Looper.myLooper()) != null)
     mEventHandler = new EventHandler(this, looper);
   else if ((looper = Looper.getMainLooper()) != null)
     mEventHandler = new EventHandler(this, looper);
   else
     mEventHandler = null;

   native_init();
 }
 
Example 17
Source File: JobProxy.java    From android-job with Apache License 2.0 4 votes vote down vote up
@NonNull
public Job.Result executeJobRequest(@NonNull JobRequest request, @Nullable Bundle transientExtras) {
    long waited = System.currentTimeMillis() - request.getScheduledAt();
    String timeWindow;
    if (request.isPeriodic()) {
        timeWindow = String.format(Locale.US, "interval %s, flex %s", JobUtil.timeToString(request.getIntervalMs()),
                JobUtil.timeToString(request.getFlexMs()));
    } else if (request.getJobApi().supportsExecutionWindow()) {
        timeWindow = String.format(Locale.US, "start %s, end %s", JobUtil.timeToString(getStartMs(request)),
                JobUtil.timeToString(getEndMs(request)));
    } else {
        timeWindow = "delay " + JobUtil.timeToString(getAverageDelayMs(request));
    }

    if (Looper.myLooper() == Looper.getMainLooper()) {
        mCat.w("Running JobRequest on a main thread, this could cause stutter or ANR in your app.");
    }

    mCat.d("Run job, %s, waited %s, %s", request, JobUtil.timeToString(waited), timeWindow);
    JobExecutor jobExecutor = mJobManager.getJobExecutor();
    Job job = null;

    try {
        // create job first before setting it started, avoids a race condition while rescheduling jobs
        job = mJobManager.getJobCreatorHolder().createJob(request.getTag());

        if (!request.isPeriodic()) {
            request.setStarted(true);
        }

        if (transientExtras == null) {
            transientExtras = Bundle.EMPTY;
        }

        Future<Job.Result> future = jobExecutor.execute(mContext, request, job, transientExtras);
        if (future == null) {
            return Job.Result.FAILURE;
        }

        // wait until done
        Job.Result result = future.get();
        mCat.d("Finished job, %s %s", request, result);
        return result;

    } catch (InterruptedException | ExecutionException e) {
        mCat.e(e);

        if (job != null) {
            job.cancel();
            mCat.e("Canceled %s", request);
        }

        return Job.Result.FAILURE;

    } finally {
        if (job == null) {
            mJobManager.getJobStorage().remove(request);

        } else if (!request.isPeriodic()) {
            mJobManager.getJobStorage().remove(request);

        } else if (request.isFlexSupport() && !job.isDeleted()) {
            mJobManager.getJobStorage().remove(request); // remove, we store the new job in JobManager.schedule()
            request.reschedule(false, false);
        }
    }
}
 
Example 18
Source File: ZoneVisionAPI.java    From DNSHero with GNU General Public License v3.0 4 votes vote down vote up
private ZoneVisionAPI() {
    executorService = Executors.newSingleThreadExecutor();
    client = new OkHttpClient();
    handler = new LifecycleAwareHandler(new Handler(Looper.getMainLooper()));
}
 
Example 19
Source File: ToastStrategy.java    From ToastUtils with Apache License 2.0 4 votes vote down vote up
public ToastStrategy() {
    super(Looper.getMainLooper());
    mQueue = getToastQueue();
}
 
Example 20
Source File: Daemon.java    From MiniThunder with Apache License 2.0 4 votes vote down vote up
public static Looper looper() {
    if (looper == null) {
        start();
    }
    return looper == null ? Looper.getMainLooper() : looper;
}