package com.example.service_app01;



import android.app.Activity;
import android.app.ActivityManager;
import android.app.ActivityManager.RunningServiceInfo;
import android.content.Context;
import android.content.Intent;
import android.location.LocationManager;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.TextView;
import android.widget.Toast;
import android.view.View;

public class MainActivity extends Activity 
{

	static TextView tv_status;
	private LocationManager query_location   = null;
	
	String service_name = "com.example.service_app01.class_service";
	
	@Override
	protected void onCreate(Bundle savedInstanceState) 
	{
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_main);
		
		Button serviceBtn = (Button) findViewById(R.id.serviceBtn);
		Button btn_verif = (Button) findViewById(R.id.checkBtn);
		
		
	    final TextView tv_status = (TextView) findViewById(R.id.tv_status);

		 
		 serviceBtn.setOnClickListener( new OnClickListener()
		 {
		 
			 @Override
			 public void onClick(View actuelView)
			 {
				 
				 query_location = (LocationManager) getSystemService(Context.LOCATION_SERVICE);

				 boolean isGPSEnabled = query_location .isProviderEnabled(LocationManager.GPS_PROVIDER);
		          
				 if (isGPSEnabled ) 
				 {
					 tv_status.setText("GPS location : activated");
				 	 startService(new Intent(MainActivity.this, class_service.class));
				 }
			 }
		 });
		 
		 
		 btn_verif.setOnClickListener( new OnClickListener()
		 {
		 
			 @Override
			 public void onClick(View actuelView)
			 {
				 boolean test = isServiceRunning();  
				 if(test == true)
				 {
					 Toast.makeText(getApplicationContext(), "youpi", Toast.LENGTH_LONG).show(); 
				 }
				 else
				 {
					 Toast.makeText(getApplicationContext(), "No service !", Toast.LENGTH_LONG).show(); 
				 }
			 }
		 });
		
	}
	
	 @Override
	 public void onDestroy()
	 {
		 super.onDestroy();
		 Toast.makeText(getApplicationContext(), "Close ...", Toast.LENGTH_LONG).show();
		 stopService(new Intent(MainActivity.this, class_service.class));
		 
	 }

	@Override
	public boolean onCreateOptionsMenu(Menu menu) 
	{
		getMenuInflater().inflate(R.menu.main, menu);
		return true;
	}

	@Override
	public boolean onOptionsItemSelected(MenuItem item) 
	{
		
		int id = item.getItemId();
		
		if (id == R.id.action_settings)
		{
			return true;
		}
		return super.onOptionsItemSelected(item);
	}
	
	private boolean isServiceRunning() 
	{
		
		ActivityManager manager = (ActivityManager) getSystemService(ACTIVITY_SERVICE);
		for (RunningServiceInfo service : manager.getRunningServices(Integer.MAX_VALUE))
		{
//			if("com.example.service_app01.class_service".equals(service.service.getClassName())) 
			if(service_name.equals(service.service.getClassName())) 
			{
				return true;
			}
		}
	        return false;
	}
}
