UI线程
/*** 发送message*/
public static void sendMessage(int what, Object obj, Handler mHandler) {Message msg = new Message();msg.what = what;if (obj != null) {msg.obj = obj;}mHandler.sendMessage(msg);
} 
发送
AppUtils.sendMessage(1, object, mHandler);
接收
Handler mHandler = new Handler(Looper.getMainLooper()) {public void handleMessage(Message msg) {switch (msg.what) {case 1://获取设备录音列表mListAudio = (ListAudioDto) msg.obj;updateUI(mListAudio);break;case 2://Toast处理AppToast.showNetWrong(F01RecodeListActivity.this, String.valueOf(msg.obj));break;case 3:List<String> filesSuccess=(List<String>) msg.obj;addRecode(filesSuccess);break;default:break;}}}; 
全局延时
Handler mHandler=new Handler(Looper.getMainLooper());
mHandler.postDelayed(new Runnable() {@Overridepublic void run() {setRecodeViews(2);}
},WavMergeUtil.getWavLength(getFilename())); 
清空
mHandler.removeCallbacksAndMessages(null);
间隔时间
long exitTime = 0;
if ((System.currentTimeMillis() - exitTime) > 5500) {exitTime = System.currentTimeMillis();startActivity(new Intent(MainActivity.this,ViewActivity.class));}else {return;
} 
延时
try {Thread.sleep(1000);
} catch (InterruptedException e) {e.printStackTrace();
} 
 
//延时3秒
new Handler(Looper.getMainLooper()).postDelayed(new Runnable() {public void run() {PetfunAddDevSuccess();}}, 3 * 1000); 
 
App.getInstance().runOnUiThread(new Runnable() {@Overridepublic void run() {GlideUtil.setOrginalPic(App.getGameResponse.logo,logimg);}
}); 
 
SystemClock.sleep(800);App.getInstance().getUIHandler().postDelayed(dataViewPresentation::show,1000);
final Timer timer =new Timer();
timer.schedule(new TimerTask() {//延时,定时循环@Overridepublic void run() {LogPlus.e("lgq","收尾。。show。。");toast.show();timer.cancel();}
},2000,3000);
new Timer().schedule(new TimerTask() {//倒计时@Overridepublic void run() {toast.cancel();timer.cancel();}
}, cnt );Handler handler = new Handler();
handler.postDelayed(new Runnable() {@Overridepublic void run() {startActivity(PayBannerActivity.class);setResult(RESULT_OK);finish();}
}, 1500);new Handler(Looper.getMainLooper()).postDelayed(new Runnable() {public void run() {Log.e("lgq","延时。。。");Toast.makeText(MainActivity.this,"saa",1).show();}
}, 3000); 
调用UI线程更新UI
   private void setTips(String s) {if (this == null) {return;}//        runOnUiThread(() -> {
//            textView.setText(s);
//        });runOnUiThread(new Runnable() {@Overridepublic void run() {textView.setText(s);}});}创建前台线程
    static final int REFRESH_COMPLETE = 0X1112;private Handler mHandler = new Handler() {public void handleMessage(android.os.Message msg) {switch (msg.what) {case REFRESH_COMPLETE:
//todo...break;}}};后台线程调用前台线程,循环线程
new Thread() {@Overridepublic void run() {super.run();running = true;int i = 0;while (running) {mHandler.sendEmptyMessageDelayed(REFRESH_COMPLETE, 1000);try {sleep(5000);} catch (InterruptedException e) {e.printStackTrace();}}}
}.start();new Thread() {@Overridepublic void run() {super.run();boolean running = true;int i = 0;while (running) {if (i<3){App.synthesizer.speak("请点击启动按钮");i++;}try {sleep(4000);} catch (InterruptedException e) {e.printStackTrace();}}}
}.start();延时线程
new Thread(){@Overridepublic void run() {try {Thread.sleep(5 * 100);} catch (InterruptedException e) {e.printStackTrace();}mHandler2=new Handler();Log.i("Lgq","s....e33.");}
}.start();private BaseActivity activity;public void setActivity(BaseActivity activity) {this.activity = activity;
}private Handler mHandler = new Handler();mHandler.post(new Runnable() {@Overridepublic void run() {activity.dismissWaitingDialog();}
});private void testSend(){new Thread(new Runnable() {@Overridepublic void run() {int i=20;while (i>0){send_0A06();LogPlus.e("onSuccess---发送次数===" + i);i--;SystemClock.sleep(3000);}}}).start();}定时延时
connect(5);//延时5秒private Disposable mDisposable;private void connect(long delay) {disposable();mDisposable = Observable.timer(delay, TimeUnit.SECONDS).subscribeOn(Schedulers.newThread()).subscribe(new Consumer<Long>() {@Overridepublic void accept(Long aLong) throws Exception {LogPlus.i("mqtt ========   Observable-->connect)()");// 开始连接connect();}});
}private void disposable() {if (mDisposable != null && !mDisposable.isDisposed()) {mDisposable.dispose();}
}定时循环
//开始延时5秒,每次间隔12秒Observable.interval(5, 12, TimeUnit.SECONDS).observeOn(AndroidSchedulers.mainThread()).subscribe(new Consumer<Long>() {@Overridepublic void accept(Long aLong) {Log.d("lgqq温度=====  ","");Log.i("lgq","bbh--33---  "+packageCode());}});    /*** 倒计时,定时器*/Handler handlerTime = new Handler(Looper.getMainLooper());private  long connectTime=33;//3分钟private long timeCount=0;private long delayMillis = 300;Runnable runnable=new Runnable() {@Overridepublic void run() {timeCount++;if(timeCount < connectTime*6){double f = (double) timeCount/(double) (connectTime*6);int progress = (int) (f*100);
//                baifebnte.setText(progress+"%");baifebnte.setText(progress+"%");horizontalProgressBar.setProgress(progress);}else{//重新}if(handlerTime!=null){handlerTime.postDelayed(this, delayMillis);}}}; 
 
if(handlerTime!=null){handlerTime.removeCallbacks(runnable);handlerTime=null;
} 
handlerTime.removeCallbacks(runnable);
if(handlerTime!=null){handlerTime.postDelayed(runnable, delayMillis);//每1秒执行一次runnable.
} 
在baseactivity 里调用
@Override
protected void onResume() {super.onResume();Log.e("lgq","随机数==== "+isAppInBackground(this));
}@Override
protected void onStop() {super.onPause();Log.e("lgq","随机数==== "+isAppInBackground(this));
} 
 
public  boolean isAppInBackground(Context context) {boolean isInBackground = true;ActivityManager am = (ActivityManager) context.getSystemService(Context.ACTIVITY_SERVICE);if (Build.VERSION.SDK_INT > Build.VERSION_CODES.KITKAT_WATCH) { // Android5.0及以后的检测方法List<ActivityManager.RunningAppProcessInfo> runningProcesses = am.getRunningAppProcesses();for (ActivityManager.RunningAppProcessInfo processInfo : runningProcesses) {//前台程序if (processInfo.importance == ActivityManager.RunningAppProcessInfo.IMPORTANCE_FOREGROUND) {for (String activeProcess : processInfo.pkgList) {if (activeProcess.equals(context.getPackageName())) {isInBackground = false;}}}}} else {List<ActivityManager.RunningTaskInfo> taskInfo = am.getRunningTasks(1);ComponentName componentInfo = taskInfo.get(0).topActivity;if (componentInfo.getPackageName().equals(context.getPackageName())) {isInBackground = false;}}return isInBackground;
}