使用Timer类来运行重复的任务
package com.example.androidtest; import java.net.MalformedURLException; import java.net.URL; import java.util.Timer; import java.util.TimerTask; import android.app.Service; import android.content.Intent; import android.os.AsyncTask; import android.os.IBinder; import android.util.Log; import android.widget.Toast; public class MyService1 extends Service { int counter = 0; static final int UPDATE_INTERVAL = 1000; private Timer timer = new Timer(); @Override public IBinder onBind(Intent intent) { // TODO Auto-generated method stub return null; } @Override public int onStartCommand(Intent intent, int flags, int startId){ doSomethingRepeatedly(); return START_STICKY; } @Override public void onDestroy(){ super.onDestroy(); if (timer != null){ timer.cancel(); } Toast.makeText(this, "Service Destroyed", Toast.LENGTH_LONG).show(); } private void doSomethingRepeatedly() { timer.scheduleAtFixedRate(new TimerTask(){ @Override public void run() {//工作者线程 Log.d("AndroidTest", String.valueOf(++counter)); } }, 0, UPDATE_INTERVAL); } }
运行效果