在服务中执行重复的任务

作者:追风剑情 发布于:2015-7-29 21:17 分类:Android

使用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);
	}
}

运行效果

1111111111.png

标签: Android

Powered by emlog  蜀ICP备18021003号   sitemap

川公网安备 51019002001593号