package net.ddns.mahaljsp.ch15_05_handlerservice;

import android.app.Notification;
import android.app.Service;
import android.content.Intent;
import android.os.IBinder;
import android.os.Message;
import android.support.annotation.Nullable;

/**
 * Created by Thomas Wu on 2016/12/13.
 */

public class CountService extends Service {
    boolean flag=true;
    @Nullable
    @Override
    public IBinder onBind(Intent intent) {
        return null;
    }
    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {
        new Thread(new Runnable() {
            @Override
            public void run() {
                while(flag) {
                    try {
                        Thread.sleep(1000);
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                    Message msg=new Message();
                    msg.what=0;
                    MainActivity.handler.sendMessage(msg);
                    //也可以使用下面較簡單的寫法
                    // MainActivity.handler.sendEmptyMessage(0);
                }
            }
        }).start();
        return super.onStartCommand(intent, flags, startId);
    }
    @Override
    public void onDestroy() {
        flag=false;
        super.onDestroy();
    }
}
