下面列出了android.os.Looper#getMainLooper ( ) 实例代码,或者点击链接到github查看源代码,也可以在右侧发表评论。
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;
}
@Override
public void run()
{
if(Looper.myLooper() == Looper.getMainLooper())
ex();
else
{
new Handler(Looper.getMainLooper()).post(
new Runnable()
{
public void run()
{
ex();
}
});
}
}
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;
}
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;
}
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));
}
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());
}
/**
* 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;
}
/**
* 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());
}
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());
}
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);
}
@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);
}
});
}
}
@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);
}
});
}
}
private void runMainHanlder(final Camera.Size previewSize) {
Handler mainHanlder = new Handler(Looper.getMainLooper());
mainHanlder.post(new Runnable() {
@Override
public void run() {
adjustViewSize(previewSize);
}
});
}
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;
}
public ToastStrategy() {
super(Looper.getMainLooper());
mQueue = getToastQueue();
}
private ZoneVisionAPI() {
executorService = Executors.newSingleThreadExecutor();
client = new OkHttpClient();
handler = new LifecycleAwareHandler(new Handler(Looper.getMainLooper()));
}
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;
}
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();
}
@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);
}
}
}
public static Looper looper() {
if (looper == null) {
start();
}
return looper == null ? Looper.getMainLooper() : looper;
}