package android.csoft.HomeWork6_iwasax;
import java.util.List;

import android.app.Activity;
import android.app.ActivityManager;
import android.content.Intent;
import android.graphics.Color;
import android.os.Bundle;
import android.view.View;
import android.view.Window;
import android.widget.Button;
import android.widget.LinearLayout;


public class HomeWork6_iwasaxActivity extends Activity 
	implements View.OnClickListener{
	private final static int WC = LinearLayout.LayoutParams.WRAP_CONTENT;
	
    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle bundle) {
        super.onCreate(bundle);
        requestWindowFeature(Window.FEATURE_NO_TITLE);
        
        //レイアウトの生成
        LinearLayout layout = new LinearLayout(this);
        layout.setBackgroundColor(Color.rgb(255,255,255));
        layout.setOrientation(LinearLayout.VERTICAL);
        setContentView(layout);
        
        //start，Endボタンの生成
        layout.addView(makeButton("Start"));
        layout.addView(makeButton("Close"));
    }
    
    //ボタンの生成
    private Button makeButton(String text){
    	Button button = new Button(this);
    	button.setTag(text);
    	button.setText(text);
    	button.setOnClickListener(this);
    	button.setLayoutParams(new LinearLayout.LayoutParams(WC,WC));
		return button;
    }
    
    //ボタン押下時に呼ばれる
    public void onClick(View v){
    	String tag = (String)v.getTag();
    	if(tag.equals("start")){
    		//サービスの開始
    		if(isServiceRunning("android.csoft.HomeWork6_iwasax.HomeWork6_iwasaxService")) return;
    		Intent intent=new Intent(this,android.csoft.HomeWork6_iwasax.HomeWork6_iwasaxService.class);
    		startService(intent);
     	}else if(tag.equals("Close")){
    		//画面クローズ
    		if(isServiceRunning("android.csoft.HomeWork6_iwasax.HomeWork6_iwasaxService_2")) return;
    		Intent intent=new Intent(this,android.csoft.HomeWork6_iwasax.HomeWork6_iwasaxService_2.class);
    		startService(intent);
    		this.moveTaskToBack(true); 
     	}
    }

    //サービスが起動中かどうか
	private boolean isServiceRunning(String className) {
		ActivityManager am=(ActivityManager)getSystemService(ACTIVITY_SERVICE);
		List<ActivityManager.RunningServiceInfo>serviceInfos=
				am.getRunningServices(Integer.MAX_VALUE);
		for(int i = 0;i<serviceInfos.size();i++){
			if(serviceInfos.get(i).service.getClassName().equals(className)){
				return true;
			}
		}
		return false;
	}
}