package gr.mybook.mystartedservice;

import android.app.Service;
import android.content.Intent;
import android.os.Handler;
import android.os.HandlerThread;
import android.os.IBinder;
import android.os.Looper;
import android.os.Message;
import android.util.Log;
import android.widget.Toast;

public class myService extends Service {
	   private Looper mServiceLooper;
	   private ServiceHandler mServiceHandler;
	   private static final String TAG = "gr.mybook.mystartedservice";

	   // Handler that receives messages from the new service thread
	   private final class ServiceHandler extends Handler {
	      public ServiceHandler(Looper looper) {
	         super(looper);
	      }

	      @Override
	      public void handleMessage(Message msg) {
	                 // Service job
	    	  		 int serviceId = msg.arg1;
	  	   	         Log.d(TAG, "Service thread: "+serviceId);
	                 
	                 try{
	     				Thread.sleep(10000);
	     			} catch (Exception e){
	     				e.printStackTrace();
	     			}

	                 // Stop the service using the startId
	                 stopSelf(msg.arg1);
	  	   	         Log.d(TAG, "Stop Service thread: "+serviceId);
	      }
	   }

	   @Override
	   public void onCreate() {
	           // Start the new thread for the service
	           HandlerThread thread = new HandlerThread("ServiceStartArguments");
	           thread.start();
	           // Get the looper and use it for Handler
	           mServiceLooper = thread.getLooper();
	           mServiceHandler = new ServiceHandler(mServiceLooper);
	   	       Log.d(TAG, "Service is onCreate method");
	   	       Toast.makeText(this, "ONCREATE", Toast.LENGTH_SHORT).show();
	   }

	   @Override
	   public int onStartCommand (Intent intent, int flags, int startId) {
   	           Log.d(TAG, "Service is onStartCommand method: "+startId);
	   	       Toast.makeText(this, "ONSTART: "+startId, Toast.LENGTH_SHORT).show();

	           // For each start request, send a message to start a job and deliver the start
	           // ID so that the corresponding job to be stopped when finishes
	           Message msg = mServiceHandler.obtainMessage();
	           msg.arg1 = startId;
	           mServiceHandler.sendMessage(msg);
	           return START_STICKY;
	     }

	@Override
	public IBinder onBind(Intent intent) {
	    Log.d(TAG, "Service is onBind method - Return null");
		return null;
	}
	
	   @Override
	   public void onDestroy() {
	      // Clean resources
	      Log.d(TAG, "Service is onDestroy method");
	   }
}

