package com.my.android.test;
import java.util.Timer;
import java.util.TimerTask;
import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.TimeUnit;
import android.app.Service;
import android.content.Intent;
import android.os.Handler;
import android.os.IBinder;
import android.util.Log;
public class MainService extends Service {
private Timer timer;
private ScheduledExecutorService service;
@Override
public IBinder onBind(Intent intent) {
// TODO Auto-generated method stub
return null;
}
@Override
public void onCreate() {
super.onCreate();
Log.d("TAG", "onCreate");
}
@Override
//onStartは2.0以降は非推奨でonStartCommandを使うことが推奨されている
//public void onStart(Intent intent, int startId) {
public int onStartCommand(Intent intent, int flags, int startId) {
final Handler handler = new Handler();
service = Executors.newSingleThreadScheduledExecutor();
service.scheduleAtFixedRate( new TimerTask() {
@Override
public void run() {
handler.post(new Runnable() {
public void run() {
Log.d("TAG", "onStartCommand");
}
});
}
}, 1000, 3000, TimeUnit.MILLISECONDS);//遅延、3秒間隔、単位時間
//super.onStart(intent, startId);
return START_STICKY;
}
@Override
public void onDestroy() {
super.onDestroy();
if(timer != null){
timer.cancel();
}
Log.d("TAG", "onDestroy");
}
}
2011年12月24日土曜日
Executorsクラスで繰り返し
端末起動時にサービスを実行:タイマーで繰り返しの記事の一部を修正
関連記事
登録:
コメントの投稿 (Atom)
0 件のコメント:
コメントを投稿