Help us understand the problem. What is going on with this article?

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

More than 1 year has passed since last update.

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

環境:
AndroidStudio 3.4.2
compileSdkVersion 28
minSdkVersion 21
targetSdkVersion 28

Design
ジョブスタートボタンと停止ボタンを設置
mojikyo45_640-2.gif

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>
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()

        }
    }
}
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
    }
}
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 回"
    }
}

何度か試したのですが、最初のジョブが10分後、その後が15分おきに処理されるっぽい
仕様上のものらしいですが。
mojikyo45_640-2.gif

2019_07_17-001.png

minimalist
趣味でやってる程度です。
Why not register and get more from Qiita?
  1. We will deliver articles that match you
    By following users and tags, you can catch up information on technical fields that you are interested in as a whole
  2. you can read useful information later efficiently
    By "stocking" the articles you like, you can search right away