Getter和Setter在JobScheduler中不起作用

时间:2017-09-11 15:35:58

标签: android getter-setter android-jobscheduler

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

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()
    }
}

1 个答案:

答案 0 :(得分:0)

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

而不是

String latitude;
String longitude;

使用

public static String latitude;
public static String longitude;

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