我如何将这个AppCompatActivity转换为服务或可以在另一个实例上运行的东西,我试图在Kotlin中学习android编程,但是我很努力,我能够在AppCompatActivity中创建Job,但是现在我需要它不使用UI当我将其添加到我的应用程序时,我有2个屏幕,这是空白。
class MainApp : AppCompatActivity() {
private val TAG = "MyService"
private val REFRESH_INTERVAL = (15 * 1000 * 60).toLong() // 15 minutes
private var jobId = 0
lateinit private var serviceComponent: ComponentName
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
serviceComponent = ComponentName(this, UploadJobService::class.java)
val dispatcher = FirebaseJobDispatcher(GooglePlayDriver(applicationContext))
val job = dispatcher.newJobBuilder()
.setService(JobService::class.java)
.setTag(TAG)
.setRecurring(true)
.setTrigger(Trigger.executionWindow(0, 60))
.setTrigger(Trigger.contentUriTrigger( Arrays.asList(
ObservedUri(Uri.parse(Environment.getExternalStorageDirectory().absolutePath), ObservedUri.Flags.FLAG_NOTIFY_FOR_DESCENDANTS))
))
.setLifetime(Lifetime.FOREVER)
.setReplaceCurrent(false)
.setConstraints(
Constraint.ON_UNMETERED_NETWORK
)
.build()
dispatcher.mustSchedule(job)
scheduleJob()
}
private fun scheduleJob() {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
val jobInfo: JobInfo
val builder = JobInfo.Builder(jobId++, serviceComponent)
builder.setPeriodic(REFRESH_INTERVAL)
builder.setPersisted(true)
//builder.setMinimumLatency(1000)
//builder.setOverrideDeadline(10000)
builder.setRequiredNetworkType(JobInfo.NETWORK_TYPE_UNMETERED)
// Extras, work duration.
val extras = PersistableBundle()
extras.putLong(WORK_DURATION_KEY, 60000)
// Finish configuring the builder
builder.run {
setRequiresDeviceIdle(false)
setRequiresCharging(false)
setExtras(extras)
}
// Schedule job
Log.d(TAG, "Scheduling job")
(getSystemService(Context.JOB_SCHEDULER_SERVICE) as JobScheduler).schedule(builder.build())
} else {
if(!isServiceRunning()){
val intent = Intent(this, BackupService::class.java)
startService(intent)
Log.i(TAG,"Service started!")
} else {
Log.i(TAG,"Service already started!")
}
}
}
private fun isServiceRunning(): Boolean {
val manager = getSystemService(Context.ACTIVITY_SERVICE) as ActivityManager
for(service in manager.getRunningServices(Integer.MAX_VALUE)) {
if (BackupService::class.java.name == service.service.className) {
return true
}
}
return false
}
}