Getter 和 Setter 在 JobScheduler 中不工作

Getter and Setter is not working in JobScheduler

我遇到了一个我无法弄清楚的问题。我已经使用 getter 和 setter 作为字符串类型的经度,它是在位置提供者的 onLocationChanged() 方法中设置的(正在按预期更改其值)并且 getter 应该是在 JobService 的 onStartJob() 中使用。但是 getter 始终为空,尽管 setter 部分中的值不断变化。

public class MyJobService extends JobService
        implements GoogleApiClient.ConnectionCallbacks, GoogleApiClient.OnConnectionFailedListener, LocationListener
{
    String latitude;
    String longitude;

    public void setLongitude(String longitude) {
        this.longitude = longitude;
    }

    public String getLongitude() {
        return longitude;
    }

        @Override
    public boolean onStartJob(JobParameters jobParameters) {
        Toast.makeText(this,"MyJobService.onStartJob()",Toast.LENGTH_SHORT).show();

        Log.e("token", "Start Job Called");
        setUpLocationClientIfNeeded();
        mLocationRequest = LocationRequest.create();
        mLocationRequest.setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY);
        mLocationRequest.setInterval(10000);
        mLocationRequest.setFastestInterval(10000);
        Log.e("longitude", getLongitude() + "zz"); // this value is always null

        return false;
    }

        @Override
    public void onLocationChanged(Location location) {
        Log.e("token",location.getLatitude()+""+location.getLongitude());
        Toast.makeText(this, location.getLatitude()+" "+location.getLongitude()+ "", Toast.LENGTH_SHORT).show();
        setLongitude(location.getLongitude() + "");
        Log.e("longitude inside location change", getLongitude() + "zz");
        // this value keeps changing, however it is not affecting the getLongitude method in onStartJob()
    }
}

我不太了解作业调度程序,但通过查看您的代码,如果您的 onLocationChanged 工作正常并且它正在正确更新经度值,那么您应该将变量设为静态。

而不是

String latitude;
String longitude;

使用

public static String latitude;
public static String longitude;

这样,您甚至不需要使用 getter 和 setter。还有一件事是你应该避免在 android 中使用 getter 和 setter。相反,您应该直接使变量 public 静态并直接访问它们以获得更好的性能。