简体   繁体   English

无法访问JobIntentService内部的类字段值

[英]Trouble accessing class field values inside a JobIntentService

I'm trying to use the JobIntentService on Android and I'm having trouble accessing the class fields inside the onHandleWork method. 我正在尝试在Android上使用JobIntentService ,但无法访问onHandleWork方法内的类字段。 My discoverable field always seems to be null inside the onHandleWork method. 我的可discoverable字段在onHandleWork方法中似乎始终为null。

Here is my JobIntentService class: 这是我的JobIntentService类:

import android.content.Context;
import android.content.Intent;
import android.support.annotation.NonNull;
import android.support.v4.app.JobIntentService;
import com.orhanobut.logger.AndroidLogAdapter;
import com.orhanobut.logger.Logger;
import io.hypertrack.smart_scheduler.Job;
import io.hypertrack.smart_scheduler.SmartScheduler;

public class NetworkCheckService extends JobIntentService {
  private static final int jobId = 1;

  private Settings settings;
  private NetworkInformation networkInfo;
  private Networks networks;
  private Discoverable discoverable;

  {
    Logger.addLogAdapter(new AndroidLogAdapter());
  }

  // Needs an empty constructor for some reason.
  public NetworkCheckService() {
  }

  public NetworkCheckService(Context context) {
    this.settings = new Settings(context);
    this.networkInfo = new NetworkInformation(context);
    this.networks = new Networks(context, networkInfo);
    this.discoverable = new Discoverable(settings, networks);
  }

  private Discoverable getDiscoverable() {
    return discoverable;
  }

  static void enqueueWork(Context context, Intent work) {
    enqueueWork(context, NetworkCheckService.class, jobId, work);
  }

  public void onHandleWork(@NonNull Intent intent) {
    Logger.d(discoverable); // discoverable is null
    Discoverable foo = getDiscoverable(); // foo is null
  }

}

My main activity class: 我的主要活动课:

public class MainActivity extends AppCompatActivity {

  @Override
  protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    NetworkCheckService networkCheckService = new NetworkCheckService(this);
    networkCheckService.enqueueWork(this, new Intent());
  }

}

We should not create any constructor in service class . 我们不应该在服务类中创建任何构造函数 It does by the android system. 它由android系统执行。 This is the reason your member variables becoming null . 这就是您的成员变量变为null的原因。 Better to initialize them inside onHandleWork method. 最好在onHandleWork方法中对其进行初始化。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM