package com.example.service_gps01;

import android.app.Service;
import android.content.Context;
import android.content.Intent;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.os.Bundle;
import android.os.IBinder;
import android.provider.Settings;
import android.support.annotation.Nullable;


//https://github.com/miskoajkula/GPS_service
// https://www.youtube.com/watch?v=lvcGh2ZgHeA&t=1s

// https://github.com/miskoajkula/GPS_service/blob/master/app/src/main/java/testing/gps_service/MainActivity.java

// https://github.com/miskoajkula/GPS_service/tree/master/app/src/main/java/testing/gps_service

public class GPS_Service extends Service 
{

    static  LocationListener listener;
    static  LocationManager locationManager;

    @Nullable
    @Override
    public IBinder onBind(Intent intent)
    {
        return null;
    }

    @Override
    public void onCreate() 
    {

	            listener = new LocationListener() 
	            {
		                @Override
		                public void onLocationChanged(Location location) 
		                {
		                    Intent i = new Intent("location_update");
		                    i.putExtra("coordinates",location.getLongitude()+" "+location.getLatitude());
		                    sendBroadcast(i);
		                }
		
		                @Override
		                public void onStatusChanged(String s, int i, Bundle bundle) 
		                {
		
		                }
		
		                @Override
		                public void onProviderEnabled(String s) 
		                {
		
		                }
		
		                @Override
		                public void onProviderDisabled(String s)
		                {
		                    Intent i = new Intent(Settings.ACTION_LOCATION_SOURCE_SETTINGS);
		                    i.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
		                    startActivity(i);
		                }
	            };
	
	            locationManager = (LocationManager) getApplicationContext().getSystemService(Context.LOCATION_SERVICE);
	
	            //noinspection MissingPermission
	            locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER,10000,0,listener); // 3000
    }

    @Override
    public void onDestroy()
    {
	        super.onDestroy();
	    
	        if(locationManager != null)
	        {
	            //noinspection MissingPermission
	            locationManager.removeUpdates(listener);
	        }
    }
}
