package com.example.svc.activities;

import android.app.Activity;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.ServiceConnection;
import android.os.Bundle;
import android.os.IBinder;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;

import com.example.svc.R;
import com.example.svc.services.DownloadService3;

public class BoundServicesActivity extends Activity {
    private boolean isBound;
    private DownloadService3.DownloadBinder binder;
    private ServiceConnection conn = new DownloadServiceConnection();

    class DownloadServiceConnection implements ServiceConnection {
        @Override
        public void onServiceConnected(ComponentName c, IBinder svc) {
            binder = (DownloadService3.DownloadBinder) svc;
            isBound = true;
        }

        @Override
        public void onServiceDisconnected(ComponentName c) {
            isBound = false;
        }
    }
    
    @Override
    protected void onStart() {
        super.onStart();
        Intent intent = new Intent(BoundServicesActivity.this,
                DownloadService3.class);
        bindService(intent, conn, Context.BIND_AUTO_CREATE);
    }

    @Override
    protected void onStop() {
        super.onStop();
        if (isBound) {
            unbindService(conn);
            isBound = false;
        }
    }
    
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.bound);

        Button startDownload = (Button) findViewById(R.id.start);
        startDownload.setOnClickListener(new OnClickListener() {
            public void onClick(View v) {
                if (isBound) {
                    EditText url = (EditText) findViewById(R.id.url);
                    binder.download(url.getText().toString());
                }
            }
        });
        Button stopDownload = (Button) findViewById(R.id.stop);
        stopDownload.setOnClickListener(new OnClickListener() {
            public void onClick(View v) {
                if (isBound) {
                    binder.stopDownload();
                }
            }
        });
    }
}