package net.ddns.mahaljsp.ch15_03_bindservice;

import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.ServiceConnection;
import android.os.IBinder;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
/**
 * Created by Thomas Wu(mahaljsp@gmail.com) on 2016/12/13.
 */
public class MainActivity extends AppCompatActivity {
    Button btnStart, btnStop;
    CountService service;
    Intent intent;
    ServiceConnection conn;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        processView();
        processControllers();
    }
    public void processView(){
        btnStart=(Button)findViewById(R.id.btnStart);
        btnStop=(Button)findViewById(R.id.btnStop);
        conn=new ServiceConnection() {
            @Override
            public void onServiceConnected(ComponentName componentName, IBinder iBinder) {
                service = ((CountService.CountBinder)iBinder).getService();
            }
            @Override
            public void onServiceDisconnected(ComponentName componentName) {
                service=null;
            }
        };
        intent=new Intent(this, CountService.class);
        bindService(intent, conn, Context.BIND_AUTO_CREATE);
    }
    public void processControllers(){
        btnStart.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                service.startCount();
            }
        });
        btnStop.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                service.stopCount();
            }
        });
    }
    @Override
    protected void onDestroy() {
        unbindService(conn);
        super.onDestroy();
    }
}
