jobFinisced 的空对象引用

Null object reference of jobFinisced

我正在构建一个带有 JobService 的应用程序。这个 JobService 应该每 1 分钟启动一次服务。

这是我的 JobService class:

public class BleJobService extends JobService {
    JobParameters params;
    DoItTask doIt;
    @Override
    public boolean onStartJob(JobParameters jobParameters) {
        this.params = params;
        Log.d("TestService", "Work to be called from here");
        startService(new Intent(this, BlePowerService_JobScheduler.class));

        /*doIt = new DoItTask();
        doIt.execute();*/
        jobFinished(params, false);
        return true;
    }

    @Override
    public boolean onStopJob(JobParameters jobParameters) {
        Log.d("TestService", "System calling to stop the job here");
        if (doIt != null)
            doIt.cancel(true);
        return false;
    }

    private class DoItTask extends AsyncTask<Void, Void, Void> {
        @Override
        protected void onPostExecute(Void aVoid) {
            Log.d("DoItTask", "Clean up the task here and call jobFinished...");

            jobFinished(params, false);
            super.onPostExecute(aVoid);
        }

        @Override
        protected Void doInBackground(Void... params) {
            Log.d("DoItTask", "Working here...");
            return null;
        }
    }
}

但是如果我尝试启动这个 JobService,我会遇到这个错误:

FATAL EXCEPTION: main
                  Process: com.eresult.diabesitycare.devicesensor, PID: 15938
                  java.lang.NullPointerException: Attempt to invoke virtual method 'android.app.job.IJobCallback android.app.job.JobParameters.getCallback()' on a null object reference
                      at android.app.job.JobService$JobHandler.handleMessage(JobService.java:161)
                      at android.os.Handler.dispatchMessage(Handler.java:102)
                      at android.os.Looper.loop(Looper.java:154)
                      at android.app.ActivityThread.main(ActivityThread.java:6776)
                      at java.lang.reflect.Method.invoke(Native Method)
                      at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1496)
                      at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1386)

问题出在这行代码:

 jobFinished(params, false);

参数为空

this.params = params(除非params来自其他地方)是一个自我赋值。

鉴于它最初没有被实例化,引用仍然是 null,因此 NPE

你的意思可能是

this.params = jobParameters;