ServiceでTimer を動かす

2011/06/17

Service で Timer を動かしてみました。 常駐アプリが作成できるAndroidの“サービス”とはを参考に作りました。

public class TimerService extends Service {
    
    class TimerServiceBinder extends Binder {
        TimerService getService() {
            return TimerService.this;
        }
    }
    
    public static final String ACTION = "TimerService";
    private Timer timer;
    
    @Override
    public void onCreate() {
        super.onCreate();
    }
    
    @Override
    public void onStart(Intent intent, int startId) {
        super.onStart(intent, startId);
    }
    
    @Override
    public void onDestroy() {
        super.onDestroy();
        if (timer != null) {
            timer.cancel();
            timer = null;
        }
    }
    
    @Override
    public IBinder onBind(Intent intent) {
        return new TimerServiceBinder();
    }
    
    @Override
    public void onRebind(Intent intent) {
    }
    
    @Override
    public boolean onUnbind(Intent intent) {
        return true;
    }
    
    public void schedule() {
        if (timer != null) {
            timer.cancel();
        }
        timer = new Timer();
        TimerTask timerTask = new TimerTask() {
            public void run() {
                sendBroadcast(new Intent(ACTION));
            }
        };
        
        //int delay = 1000 * 60 * 60 * 24;
        //int delay = 1000 * 60;
        int delay = 1000;
        Date now = new Date();
        now.setSeconds(0);
        timer.scheduleAtFixedRate(timerTask, now, delay);
    }

}
public class TimerActivity extends Activity {
    protected Intent intentAlerm;
    protected TextView timerLabel;
    protected TextView dateLabel;
    private TimerService timerService;
    private final TimerReceiver timerReceiver = new TimerReceiver()

    private class TimerReceiver extends BroadcastReceiver {
        @Override
        public void onReceive(Context context, Intent intent) {
            Date now = new Date();
            int nowHour = now.getHours();
            int nowMinute = now.getMinutes();
            int nowSecond = now.getSeconds();

            updateTimer(now);
    }

    private ServiceConnection serviceConnection = new ServiceConnection() {
        public void onServiceConnected(ComponentName className, IBinder service) {
            timerService = ((TimerService.TimerServiceBinder)service).getService();
            timerService.schedule();
        }
        
        public void onServiceDisconnected(ComponentName className) {
            timerService = null;
        }
    };

        @Override
        public void onCreate(Bundle savedInstanceState) {
                requestWindowFeature(Window.FEATURE_NO_TITLE);
        
                setContentView(R.layout.main);
        
        timerLabel = (TextView) findViewById(R.id.timerLabel);
        dateLabel = (TextView) findViewById(R.id.dateLabel);
        
                intentAlerm = new Intent(getApplicationContext(), TimerActivity.class);
                intentAlerm.setFlags(Intent.FLAG_ACTIVITY_RESET_TASK_IF_NEEDED);
                intentAlerm.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        
        Intent intent = new Intent(this, TimerService.class);
        startService(intent);
        
        IntentFilter filter = new IntentFilter(TimerService.ACTION);
        registerReceiver(receiver, filter);
        
        bindService(intent, serviceConnection, Context.BIND_AUTO_CREATE);

        unbindService(serviceConnection);
        bindService(intent, serviceConnection, Context.BIND_AUTO_CREATE);
        }

    @Override
    protected void onResume() {
        super.onResume();
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        if  (serviceConnection != null) {
            unbindService(serviceConnection);
            unregisterReceiver(receiver);
            wrestlingTimer.stopSelf();
        }
        Toast toast = Toast.makeText(this, "解除しました。", Toast.LENGTH_LONG);
        toast.setGravity(Gravity.CENTER, 0, 0);
        toast.show();
    }

    public void updateTimer(Date date) {
        SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy/MM/dd (E)");
        SimpleDateFormat timeFormat = new SimpleDateFormat("HH:mm:ss");
        dateLabel.setText(dateFormat.format(date));
        timerLabel.setText(timeFormat.format(date));
    }

}

常駐アプリが作成できるAndroidの“サービス”とはのサンプルだと、タイマーをセットする度にmoveTaskToBack(true) してメインのActivity が見えなくなります。

上記のサンプルは、serviceConnection が作成された時に一気にタイマーを登録しました。