приложение было закрыто JobService периодически не работает - PullRequest
0 голосов
/ 05 марта 2019

У меня есть Jobservice, который запускается периодически каждый раз. Моя задача - только запуск задания для запуска в приложении. Я могу остановить или уничтожить приложение вручную с помощью пользовательского интерфейса, а JobService не запущен, jobservice, зачем останавливаться?знаете, я приложил мой манифест и 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>

1 Ответ

0 голосов
/ 05 марта 2019

В вашем сервисе Job верните true в onStartJob

 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)

        }
...