国产探花免费观看_亚洲丰满少妇自慰呻吟_97日韩有码在线_资源在线日韩欧美_一区二区精品毛片,辰东完美世界有声小说,欢乐颂第一季,yy玄幻小说排行榜完本

首頁 > 系統 > Android > 正文

Android定時器Timer的停止和重啟實現代碼

2019-10-22 18:31:17
字體:
來源:轉載
供稿:網友

本文介紹了Android定時器Timer的停止和重啟實現代碼,分享給大家,具體如下:

7月份做了一個項目,利用自定義控件呈現一幅動畫,當時使用定時器來控制時間,但是當停止開啟時總是出現問題。一直在尋找合理的方法解決這個問題,一直沒有找到,最近終于找到了合理的方法來解決這個問題。

大家如何查詢有關資料,一定知道timer,timertask取消的方式是采用Timer.cancel()和mTimerTask.cancel(),可是大家發現這種發式取消后,再次開始timer時,會報錯

 FATAL EXCEPTION: main         Process: com.example.zhongzhi.gate_control_scheme, PID: 2472         java.lang.IllegalStateException: Timer already cancelled.           at java.util.Timer.sched(Timer.java:397)           at java.util.Timer.schedule(Timer.java:248)           at com.example.zhongzhi.gate_control_scheme.MainActivity.onClick(MainActivity.java:401)           at android.view.View.performClick(View.java:5637)           at android.view.View$PerformClick.run(View.java:22429)           at android.os.Handler.handleCallback(Handler.java:751)           at android.os.Handler.dispatchMessage(Handler.java:95)           at android.os.Looper.loop(Looper.java:154)           at android.app.ActivityThread.main(ActivityThread.java:6119)           at java.lang.reflect.Method.invoke(Native Method)           at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:886)           at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:776)

 這個問題的解決采用cancle(),取消timer后,還需要清空timer。合理的代碼應該是這樣的:

mTimer.cancel();mTimer = null;mTimerTask.cancel();mTimerTask = null;

關鍵的問題解決完了,下面給出我的案例代碼Mainactivity.Java:

public class MainActivity extends AppCompatActivity {  private static String TAG = "TimerDemo";  private TextView mTextView = null;  private Button mButton_start = null;  private Button mButton_pause = null;  private Timer mTimer = null;  private TimerTask mTimerTask = null;  private Handler mHandler = null;  private static int count = 0;  private boolean isPause = false;  private boolean isStop = true;  private static int delay = 1000; //1s  private static int period = 1000; //1s  private static final int UPDATE_TEXTVIEW = 0;  @Override  public void onCreate(Bundle savedInstanceState) {    super.onCreate(savedInstanceState);    setContentView(R.layout.activity_main);    mTextView = (TextView)findViewById(R.id.mytextview);    mButton_start = (Button)findViewById(R.id.mybutton_start);    mButton_pause = (Button)findViewById(R.id.mybutton_pause);    mButton_start.setOnClickListener(new Button.OnClickListener() {      public void onClick(View v) {        if (isStop) {          Log.i(TAG, "Start");        } else {          Log.i(TAG, "Stop");        }        isStop = !isStop;        if (!isStop) {          startTimer();        }else {          stopTimer();        }        if (isStop) {          mButton_start.setText(R.string.start);        } else {          mButton_start.setText(R.string.stop);        }      }    });    mButton_pause.setOnClickListener(new Button.OnClickListener() {      public void onClick(View v) {        if (isPause) {          Log.i(TAG, "Resume");        } else {          Log.i(TAG, "Pause");        }        isPause = !isPause;        if (isPause) {          mButton_pause.setText(R.string.resume);        } else {          mButton_pause.setText(R.string.pause);        }      }    });    mHandler = new Handler(){      @Override      public void handleMessage(Message msg) {        switch (msg.what) {          case UPDATE_TEXTVIEW:            updateTextView();            break;          default:            break;        }      }    };  }  private void updateTextView(){    mTextView.setText(String.valueOf(count));  }  private void startTimer(){    if (mTimer == null) {      mTimer = new Timer();    }    if (mTimerTask == null) {      mTimerTask = new TimerTask() {        @Override        public void run() {          Log.i(TAG, "count: "+String.valueOf(count));          sendMessage(UPDATE_TEXTVIEW);          do {            try {              Log.i(TAG, "sleep(1000)...");              Thread.sleep(1000);            } catch (InterruptedException e) {            }          } while (isPause);          count ++;        }      };    }    if(mTimer != null && mTimerTask != null )      mTimer.schedule(mTimerTask, delay, period);  }  private void stopTimer(){    if (mTimer != null) {      mTimer.cancel();      mTimer = null;    }    if (mTimerTask != null) {      mTimerTask.cancel();      mTimerTask = null;    }    count = 0;  }  public void sendMessage(int id){    if (mHandler != null) {      Message message = Message.obtain(mHandler, id);      mHandler.sendMessage(message);    }  }}

xml部分代碼:

<?xml version="1.0" encoding="utf-8"?><LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"  android:layout_width="fill_parent"  android:layout_height="fill_parent"  android:orientation="vertical" >  <TextView    android:id="@+id/mytextview"    android:layout_width="fill_parent"    android:layout_height="wrap_content"    android:gravity="center"    android:text="@string/number" />  <LinearLayout    android:layout_width="fill_parent"    android:layout_height="wrap_content"    android:gravity="center"    android:orientation="horizontal" >    <Button      android:id="@+id/mybutton_start"      android:layout_width="wrap_content"      android:layout_height="wrap_content"      android:text="@string/start" />    <Button      android:id="@+id/mybutton_pause"      android:layout_width="wrap_content"      android:layout_height="wrap_content"      android:text="@string/pause" />  </LinearLayout></LinearLayout>

string部分代碼:

<?xml version="1.0" encoding="utf-8"?><resources>  <string name="app_name">TimerDemo</string>  <string name="number">0</string>  <string name="start">start</string>  <string name="stop">stop</string>  <string name="pause">pause</string>  <string name="resume">resume</string></resources>

上面就是我的源代碼,如果大家有什么問題可以留言進行探討。

以上就是本文的全部內容,希望對大家的學習有所幫助,也希望大家多多支持VEVB武林網。


注:相關教程知識閱讀請移步到Android開發頻道。
發表評論 共有條評論
用戶名: 密碼:
驗證碼: 匿名發表
主站蜘蛛池模板: 多伦县| 桐乡市| 凤凰县| 磐安县| 乌鲁木齐县| 西和县| 徐闻县| 吴旗县| 和平区| 循化| 临潭县| 宾川县| 逊克县| 阿荣旗| 绍兴市| 堆龙德庆县| 手机| 额敏县| 云浮市| 河东区| 即墨市| 洛川县| 巩留县| 北安市| 周宁县| 雷波县| 惠水县| 柯坪县| 巩留县| 昂仁县| 北川| 安塞县| 石屏县| 沾化县| 青岛市| 乌鲁木齐市| 驻马店市| 台安县| 叙永县| 洛南县| 北川|