我有一个Jobservice定期运行。我的活动仅是为了在应用程序上运行而启动作业。我可以使用UI手动停止或销毁应用程序,而JobService没有运行,jobservice为什么停止我不know.i附加了我的manifistfile和Jobdispatcher我还要做什么?
dispatcher = new FirebaseJobDispatcher(new GooglePlayDriver(getActivity()));
Bundle myExtrasBundle = new Bundle();
myExtrasBundle.putString("some_key", "some_value");
if (myJob == null) {
myJob = dispatcher.newJobBuilder()
// the JobService that will be called
.setService(ReminderService.class)
// uniquely identifies the job
.setTag("my-unique-tag")
// one-off job
.setRecurring(true)
// don't persist past a device reboot
.setLifetime(Lifetime.FOREVER)
// start between 0 and 60 seconds from now
.setTrigger(Trigger.executionWindow(0, 60))
// don't overwrite an existing job with the same tag
.setReplaceCurrent(true)
// retry with exponential backoff
.setRetryStrategy(RetryStrategy.DEFAULT_LINEAR)
// constraints that need to be satisfied for the job to run
.setConstraints(
// only run on an unmetered network
Constraint.ON_ANY_NETWORK
)
.setExtras(myExtrasBundle)
.build();
dispatcher.mustSchedule(myJob);
}
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
package="com.vvsugar">
<uses-permission android:name="${applicationId}.permission.C2D_MESSAGE" />
<permission
android:name="${applicationId}.permission.C2D_MESSAGE"
android:protectionLevel="signature" />
<uses-feature android:name="android.hardware.camera" />
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.CAMERA" />
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
<uses-permission android:name="com.google.android.providers.gsf.permission.READ_GSERVICES" />
<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" />
<uses-permission android:name="android.permission.SYSTEM_ALERT_WINDOW" />
<application
android:name=".AppController"
android:hardwareAccelerated="true"
android:icon="@mipmap/ic_launcher"
android:installLocation="internalOnly"
android:label="@string/app_name"
android:largeHeap="true"
android:roundIcon="@mipmap/ic_launcher_round"
android:supportsRtl="true"
android:theme="@style/AppTheme"
tools:replace="android:icon,android:theme">
<meta-data
android:name="DATABASE"
android:value="vvsugae.db" />
<meta-data
android:name="VERSION"
android:value="1.45" />
<meta-data
android:name="QUERY_LOG"
android:value="true" />
<meta-data
android:name="DOMAIN_PACKAGE_NAME"
android:value="com.vvsugar.dbview" />
<provider
android:name="android.support.v4.content.FileProvider"
android:authorities="${applicationId}.provider"
android:exported="false"
android:grantUriPermissions="true">
<meta-data
android:name="android.support.FILE_PROVIDER_PATHS"
android:resource="@xml/provider_paths" />
</provider>
<activity
android:name=".activity.LoginActivity"
android:screenOrientation="portrait">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<service
android:name="com.vvsugar.activity.ReminderService"
android:enabled="true"
android:exported="false"
android:permission="android.permission.RECEIVE_BOOT_COMPLETED">
<intent-filter>
<action android:name="com.firebase.jobdispatcher.ACTION_EXECUTE" />
<action android:name="android.intent.action.BOOT_COMPLETED" />
<action android:name="android.intent.action.QUICKBOOT_POWERON" />
<action android:name="android.intent.action.REBOOT"/>
<category android:name="android.intent.category.DEFAULT" />
</intent-filter>
</service>
<activity android:name=".activity.DashBoardActivity" />
<activity android:name=".base.BaseActivity" />
<activity
android:name=".activity.MainActivity"
android:configChanges="keyboard|keyboardHidden|screenLayout|screenSize|orientation"
android:windowSoftInputMode="stateAlwaysHidden|adjustResize" />
<activity android:name=".uicomponent.imagepicker.activities.AlbumSelectActivity" />
<activity android:name=".uicomponent.imagepicker.activities.HelperActivity" />
<activity android:name=".uicomponent.imagepicker.activities.ImageSelectActivity" />
<activity
android:name=".adapters.PaymentsAdapter"
android:label="@string/title_activity_payments_adapter"
android:theme="@style/AppTheme.NoActionBar" />
<meta-data
android:name="com.google.android.maps.v2.API_KEY"
android:value="AIzaSyBwdtoapVVM-Yg4VIKNuFaH8f3GqN7pd98" />
<!--
<meta-data android:name="com.google.android.gms.version"
android:value="@integer/google_play_services_version"/>
-->
<meta-data
android:name="io.fabric.ApiKey"
android:value="eab11ffa174990145b21fef7ed3fd2ddcf6ca4c8" />
<activity android:name=".activity.ActiveWindow"></activity>
</application>
</manifest>
答案 0 :(得分:0)
在您的Job服务上,在onStartJob上返回true
override fun onStartJob(jobParameters: JobParameters): Boolean {
return true
}
也像这样覆盖onStartCommand
override fun onStartCommand(intent: Intent, flags: Int, startId: Int): Int {
return Service.START_STICKY
}
为了清楚起见,编写这样的代码
<service
android:name=".JobServiceEx"
android:permission="android.permission.BIND_JOB_SERVICE"/>
科林代码
的服务如下所示class JobServiceEx : JobService() {
var startTime: Long = 0
val workHandler = Handler()
var workRunnable: Runnable? = null
// Called by the Android system when it's time to run the job
override fun onStartJob(jobParameters: JobParameters): Boolean {
Log.d(TAG, "Job started!")
workRunnable = object : Runnable {
override fun run() {
val millis = System.currentTimeMillis() - startTime
var seconds = (millis / 1000).toInt()
val minutes = seconds / 60
seconds %= 60
var curTime = "$seconds"
Toast.makeText(baseContext, "Current Sec : $curTime", Toast.LENGTH_SHORT).show()
Log.e("TAG", "Current Time : $curTime")
workHandler.postDelayed(this, 1000)
}
}
workHandler.post(workRunnable)
return true
}
override fun onStartCommand(intent: Intent, flags: Int, startId: Int): Int {
return Service.START_STICKY
}
// Called if the job was cancelled before being finished
override fun onStopJob(jobParameters: JobParameters): Boolean {
workHandler.removeCallbacks(workRunnable);
return false
}
companion object {
private val TAG = JobServiceEx::class.java.simpleName
}
}
并像这样启动和停止服务
R.id.buttonStart -> {
/**
* start job service to test
*/
var componentName = ComponentName(this, JobServiceEx::class.java)
var jobInfo: JobInfo? = null
jobInfo = JobInfo.Builder(JOB_ID, componentName)
.setRequiresCharging(true)
.setMinimumLatency(1)
.setOverrideDeadline(1)
.build()
var jobScheduler = getSystemService(JOB_SCHEDULER_SERVICE) as JobScheduler
var resultCode = jobScheduler.schedule(jobInfo);
if (resultCode == JobScheduler.RESULT_SUCCESS) {
Log.e("TAG", "Job scheduled!");
} else {
Log.e("TAG", "Job not scheduled");
}
}
R.id.buttonStop -> {
/**
* stop job service to test
*/
val jobScheduler = getSystemService(Context.JOB_SCHEDULER_SERVICE) as JobScheduler
jobScheduler.cancel(JOB_ID)
}