Android 用Handler Timer 做循环任务

项目场景:

     在做项目的过程,需要用到循环任务,属于整个功能的一个很小部分,真正急用的时候, 不能

一下子写出来,真是觉得android的基本功不扎实, 还是通过Demo的方式记录下来吧 文章内容比

较基础,仅记录一下,供参考

       

【Demo简单需求】:每隔5秒中, 弹出“正在执行循环任务”的Toast

解决方案:

        【方案一】:用Handler 来实现

public class MainActivity extends AppCompatActivity {


     private Button button;


    //利用Handler做一个循环任务
    @SuppressLint("HandlerLeak")
    private Handler mHandler = new Handler() {
        @Override
        public void handleMessage(@NonNull Message msg) {
            super.handleMessage(msg);
            if (msg.what == 2) {
                Toast.makeText(MainActivity.this, "正在执行循环任务", Toast.LENGTH_LONG).show();
                //然后过5秒后发送一次消息
                mHandler.sendEmptyMessageDelayed(2, 5000);
            }
        }
    };


 @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        button = (Button)findViewById(R.id.buttontest);

        button.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
              mHandler.sendEmptyMessage(2);
            }
        });

    }



  @Override
    protected void onDestroy() {
        super.onDestroy();
        //避免Handler内存泄漏
        mHandler.removeCallbacksAndMessages(null);
    }    
}

        【方案二】:用 Timer 来实现

public class MainActivity extends AppCompatActivity {


     private Timer timer;

     //这里注意一下,Timer.schedule()方法 是开启了一个子线程做的任务,如果在run()方法中
    //直接Toast.makeText().show() 会报如下错误:
    // AndroidRuntime: java.lang.RuntimeException: Can't toast on a thread that has not 
    //called Looper.prepare()  意思是toast需要在主线程显示,解决方法:通过 runOnUiThread 方法
    // post Runnable 到主线程中去显示Toast
     private TimerTask timerTask = new TimerTask() {
        @Override
        public void run() {
            runOnUiThread(new Runnable() {
                @Override
                public void run() {
                    Toast.makeText(MainActivity.this, "正在执行循环任务",     Toast.LENGTH_LONG).show();
                }
            });
        }
     };

    @Override
    protected void onResume() {
        super.onResume();
        // 每隔5秒显示
        timer.schedule(timerTask, 1000, 5000);

    }


     @Override
    protected void onDestroy() {
        super.onDestroy();
        //关闭定时器
        if (timer != null) {
            timer.cancel();
        }
    }

}

        【方案三】 用Handler + Timer 实现,其实原理一样,用好其中一个就可以

public class MainActivity extends AppCompatActivity {

    private Timer timer;

    private TimerTask timerTask = new TimerTask() {
        @Override
        public void run() {
             // 每隔 5秒发送一次消息
             mHandler.sendEmptyMessage(2);
        }
    };

    @SuppressLint("HandlerLeak")
    private Handler mHandler = new Handler() {
        @Override
        public void handleMessage(@NonNull Message msg) {
            super.handleMessage(msg);
            if (msg.what == 2) {
                Toast.makeText(MainActivity.this, "正在执行循环任务", Toast.LENGTH_LONG).show();
            }
        }
    };

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        timer = new Timer();
    }


    @Override
    protected void onDestroy() {
        super.onDestroy();
        mHandler.removeCallbacksAndMessages(null);
        if (timer != null) {
            timer.cancel();
        }
    }

    @Override
    protected void onResume() {
        super.onResume();
        /*
        *  @param task   task to be scheduled.
         * @param delay  delay in milliseconds before task is to be executed.
         * @param period time in milliseconds between successive task executions.
        * */
        timer.schedule(timerTask, 1000, 5000);
    }

}

你可能感兴趣的:(Android,App,android,Timer,循环任务,Handler)