当前位置:   article > 正文

Android 后台线程Thread调用前台线程Handler,延时线程,runOnUiThread使用,Timer延时,定时循环,倒计时_android thread延时不能再主活动里写吗

android thread延时不能再主活动里写吗

 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() {
    @Override
    public 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() {
    @Override
    public void run() {
        GlideUtil.setOrginalPic(App.getGameResponse.logo,logimg);
    }
});

SystemClock.sleep(800);
App.getInstance().getUIHandler().postDelayed(dataViewPresentation::show,1000);
  1. final Timer timer =new Timer();
  2. timer.schedule(new TimerTask() {//延时,定时循环
  3. @Override
  4. public void run() {
  5. LogPlus.e("lgq","收尾。。show。。");
  6. toast.show();
  7. timer.cancel();
  8. }
  9. },2000,3000);
  10. new Timer().schedule(new TimerTask() {//倒计时
  11. @Override
  12. public void run() {
  13. toast.cancel();
  14. timer.cancel();
  15. }
  16. }, cnt );

  1. Handler handler = new Handler();
  2. handler.postDelayed(new Runnable() {
  3. @Override
  4. public void run() {
  5. startActivity(PayBannerActivity.class);
  6. setResult(RESULT_OK);
  7. finish();
  8. }
  9. }, 1500);

new Handler(Looper.getMainLooper()).postDelayed(new Runnable() {
    public void run() {
        Log.e("lgq","延时。。。");
        Toast.makeText(MainActivity.this,"saa",1).show();

    }
}, 3000);

调用UI线程更新UI 

  1. private void setTips(String s) {
  2. if (this == null) {
  3. return;
  4. }
  5. // runOnUiThread(() -> {
  6. // textView.setText(s);
  7. // });
  8. runOnUiThread(new Runnable() {
  9. @Override
  10. public void run() {
  11. textView.setText(s);
  12. }
  13. });
  14. }

创建前台线程

  1. static final int REFRESH_COMPLETE = 0X1112;
  2. private Handler mHandler = new Handler() {
  3. public void handleMessage(android.os.Message msg) {
  4. switch (msg.what) {
  5. case REFRESH_COMPLETE:
  6. //todo...
  7. break;
  8. }
  9. }
  10. };

后台线程调用前台线程,循环线程

  1. new Thread() {
  2. @Override
  3. public void run() {
  4. super.run();
  5. running = true;
  6. int i = 0;
  7. while (running) {
  8. mHandler.sendEmptyMessageDelayed(REFRESH_COMPLETE, 1000);
  9. try {
  10. sleep(5000);
  11. } catch (InterruptedException e) {
  12. e.printStackTrace();
  13. }
  14. }
  15. }
  16. }.start();

  1. new Thread() {
  2. @Override
  3. public void run() {
  4. super.run();
  5. boolean running = true;
  6. int i = 0;
  7. while (running) {
  8. if (i<3){
  9. App.synthesizer.speak("请点击启动按钮");
  10. i++;
  11. }
  12. try {
  13. sleep(4000);
  14. } catch (InterruptedException e) {
  15. e.printStackTrace();
  16. }
  17. }
  18. }
  19. }.start();

延时线程

  1. new Thread(){
  2. @Override
  3. public void run() {
  4. try {
  5. Thread.sleep(5 * 100);
  6. } catch (InterruptedException e) {
  7. e.printStackTrace();
  8. }
  9. mHandler2=new Handler();
  10. Log.i("Lgq","s....e33.");
  11. }
  12. }.start();
private BaseActivity activity;
  1. public void setActivity(BaseActivity activity) {
  2. this.activity = activity;
  3. }
private Handler mHandler = new Handler();

  1. mHandler.post(new Runnable() {
  2. @Override
  3. public void run() {
  4. activity.dismissWaitingDialog();
  5. }
  6. });

  1. private void testSend(){
  2. new Thread(new Runnable() {
  3. @Override
  4. public void run() {
  5. int i=20;
  6. while (i>0){
  7. send_0A06();
  8. LogPlus.e("onSuccess---发送次数===" + i);
  9. i--;
  10. SystemClock.sleep(3000);
  11. }
  12. }
  13. }).start();
  14. }

定时延时

connect(5);//延时5秒
private Disposable mDisposable;
  1. private void connect(long delay) {
  2. disposable();
  3. mDisposable = Observable.timer(delay, TimeUnit.SECONDS).subscribeOn(Schedulers.newThread()).subscribe(new Consumer<Long>() {
  4. @Override
  5. public void accept(Long aLong) throws Exception {
  6. LogPlus.i("mqtt ======== Observable-->connect)()");
  7. // 开始连接
  8. connect();
  9. }
  10. });
  11. }
  1. private void disposable() {
  2. if (mDisposable != null && !mDisposable.isDisposed()) {
  3. mDisposable.dispose();
  4. }
  5. }

定时循环

  1. //开始延时5秒,每次间隔12秒
  2. Observable.interval(5, 12, TimeUnit.SECONDS).observeOn(AndroidSchedulers.mainThread()).subscribe(new Consumer<Long>() {
  3. @Override
  4. public void accept(Long aLong) {
  5. Log.d("lgqq温度===== ","");
  6. Log.i("lgq","bbh--33--- "+packageCode());
  7. }
  8. });

    /**
     * 倒计时,定时器
     */
    Handler handlerTime = new Handler(Looper.getMainLooper());
    private  long connectTime=33;//3分钟
    private long timeCount=0;
    private long delayMillis = 300;
    Runnable runnable=new Runnable() {
        @Override
        public 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;
}

声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/我家自动化/article/detail/240692
推荐阅读
相关标签
  

闽ICP备14008679号