package com.example.patrice.job_scheduler_03;

import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;

import android.app.Activity;
import android.app.job.JobInfo;
import android.app.job.JobScheduler;
import android.content.ComponentName;
import android.content.Context;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.Toast;

public class MainActivity extends Activity {

    private Button btnStart;
    private Button btnCancel;
    private JobScheduler jobScheduler;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        btnStart = (Button) findViewById(R.id.start);
        btnCancel = (Button) findViewById(R.id.stop);

        jobScheduler = (JobScheduler) getSystemService(Context.JOB_SCHEDULER_SERVICE);

        btnStart.setOnClickListener(onStartJobs());
        btnCancel.setOnClickListener(onStopJobs());
    }

    private OnClickListener onStartJobs() {
        return new OnClickListener() {

            @Override
            public void onClick(View v) {
                JobInfo.Builder builder = new JobInfo.Builder(1, new ComponentName(getPackageName(),
                        JOB.class.getName()));

                //run job service after every 5 seconds
                builder.setPeriodic(5000);
                jobScheduler.schedule(builder.build());
            }
        };
    }

    @Override
    protected void onPause() {
        super.onPause();
        jobScheduler.cancelAll(); //remove job service onPause
    }

    /**
     * Handle button cancel job event
     * Remove job service
     * @return
     */
    private OnClickListener onStopJobs() {
        return new OnClickListener() {

            @Override
            public void onClick(View v) {
                jobScheduler.cancelAll();
                Toast.makeText(MainActivity.this, "cancel job", Toast.LENGTH_SHORT).show();
            }
        };
    }
}