【Kotlin】ジョブスケジューラーでバックグラウンド処理を行う【AndroidStudio】

作っているアプリにバックグラウンド処理させたかったので、いろいろ試してみた。

環境：
AndroidStudio 3.4.2
compileSdkVersion 28
minSdkVersion 21
targetSdkVersion 28

Design
ジョブスタートボタンと停止ボタンを設置
<img width="500" alt="mojikyo45_640-2.gif" src="https://qiita-image-store.s3.ap-northeast-1.amazonaws.com/0/456227/5215c5f3-b9bf-83ca-230a-fef7fc9f8dc4.png">


```xml:AndroidManifest.xml
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
          package="com.example.myapplication001">


    <uses-permission android:name="android.permission.RECEIVE_BOOT_COMPLETED"/>
    <uses-permission android:name="android.permission.ACCESS_NETWORK_STATE"/>

    <application
            android:allowBackup="true"
            android:icon="@mipmap/ic_launcher"
            android:label="@string/app_name"
            android:roundIcon="@mipmap/ic_launcher_round"
            android:supportsRtl="true"
            android:theme="@style/AppTheme">
        <activity android:name=".MainActivity">
            <intent-filter>
                <action android:name="android.intent.action.MAIN"/>

                <category android:name="android.intent.category.LAUNCHER"/>
            </intent-filter>
        </activity>
        <service android:name=".MJobScheduler"
                 android:permission="android.permission.BIND_JOB_SERVICE"
                 android:exported="true"/>

    </application>

</manifest>
```


```kotlin:MainActivity.kt
package com.example.myapplication001

import android.app.job.JobInfo
import android.app.job.JobScheduler
import android.content.ComponentName
import android.content.Context
import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import android.widget.Button
import android.widget.Toast

class MainActivity : AppCompatActivity() {

    companion object{

        val JOB_ID : Int = 101
        var counter : Int = 0

        fun countSeconds(){
            counter++

        }

    }

    private lateinit var JobScheduler : JobScheduler
    private lateinit var JobInfo : JobInfo

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)
        val startButton: Button = findViewById(R.id.startButton)
        val stopButton: Button = findViewById(R.id.stopButton)

        var cn : ComponentName = ComponentName(this,MJobScheduler::class.java)
        var builder : JobInfo.Builder = android.app.job.JobInfo.Builder(JOB_ID,cn)
        builder.setPeriodic(5000)
        builder.setRequiredNetworkType(android.app.job.JobInfo.NETWORK_TYPE_ANY)
        builder.setPersisted(true)
        JobInfo = builder.build()
        JobScheduler = getSystemService(Context.JOB_SCHEDULER_SERVICE) as JobScheduler


        startButton.setOnClickListener {
            System.out.println("スタート")
            JobScheduler.schedule(JobInfo)
            Toast.makeText(this,"ジョブスケジュール開始",Toast.LENGTH_LONG).show()

        }

        stopButton.setOnClickListener {
            System.out.println("ストップ")
            JobScheduler.cancel(JOB_ID)
            Toast.makeText(this,"ジョブキャンセル",Toast.LENGTH_LONG).show()

        }
    }
}
```

```kotlin:MJobScheduler.kt
package com.example.myapplication001

import android.app.job.JobParameters
import android.app.job.JobService
import android.widget.Toast

class MJobScheduler : JobService() {

    private lateinit var MJobExecuter : MJobExecuter

    override fun onStopJob(p0: JobParameters?): Boolean {

        MJobExecuter.cancel(true)
        return false
    }

    override fun onStartJob(params: JobParameters?): Boolean {

        MJobExecuter = object : MJobExecuter(){

            override fun onPostExecute(result: String?) {
                super.onPostExecute(result)
                Toast.makeText(applicationContext,result,Toast.LENGTH_LONG).show()
                System.out.println("ジョブ実行")
                jobFinished(params,false)
            }
        }
        MJobExecuter.execute()
        return true
    }
}
```

```kotlin:MJobExecuter.kt
package com.example.myapplication001

import android.os.AsyncTask
import com.example.myapplication001.MainActivity.Companion.counter

open class MJobExecuter : AsyncTask<Void, Void, String>() {
    override fun doInBackground(vararg p0: Void?): String {

        MainActivity.countSeconds()
        return "バックグラウンドでの実行：$counter 回"
    }
}
```

何度か試したのですが、最初のジョブが１０分後、その後が１５分おきに処理されるっぽい
仕様上のものらしいですが。
<img width="500" alt="mojikyo45_640-2.gif" src="https://qiita-image-store.s3.ap-northeast-1.amazonaws.com/0/456227/85b08f88-5af4-1e17-b727-7ce5e9fc71d9.png">



![2019_07_17-001.png](https://qiita-image-store.s3.ap-northeast-1.amazonaws.com/0/456227/6f049195-cb64-554c-bcc0-ab00b7c28c4f.png)