2016年8月11日 星期四

create a timer ,need multi thread,which type?

17 create a timer ,need multi thread,which type?



the background thred need to use Handler to communicate to the UI thread

use Timer task and Handler task to buid a simple time

package pom.poly.com.simpletimer;

import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;
import android.widget.Button;
import android.widget.TextView;

import java.util.Timer;
import java.util.TimerTask;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;

public class MainActivity extends AppCompatActivity {
   @BindView(R.id.tvTime)
   TextView tvTime;
   @BindView(R.id.btStart)
   Button btStart;

   private Timer timer;
   private Handler mHandler;


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

       tvTime = (TextView) findViewById(R.id.tvTime);
       mHandler = new Handler() {
           @Override
           public void handleMessage(Message msg) {
               super.handleMessage(msg);
               if (msg.what == 1) {
                   tvTime.setText(msg.arg1 + "");
               }
           }
       };


   }

   @Override
   protected void onPause() {
       super.onPause();
       timer.cancel();
   }

   @OnClick(R.id.btStart)
   public void onClick() {
       timer = new Timer(true);
       timer.schedule(new MyTimerTask(), 0, 1000);
   }

   private class MyTimerTask extends TimerTask {
       private int second = 0;

       @Override
       public void run() {
           second++;
           Log.d("second", second + "");
           Message message = new Message();
           message.what = 1;
           message.arg1 = second;
           mHandler.sendMessage(message);

       }
   }
}



however,it can’t not pause and restart

so,Timer is not a good way to create a task to Create a Background Thread task

example

make by sharepreference,Timer task.