【问题标题】:Re- JobScheduler combined with FusedLocationProvider Api oftens gives null location valueRe- JobScheduler 结合 FusedLocationProvider Api 经常给出空位置值
【发布时间】:2018-03-29 21:51:55
【问题描述】:

我有一个带有 fusedLocationApi 提供程序的 jobScheduler。它可以正常工作,但有时它会为 no 提供 null 值。时间(连续 6-7 次)。我尝试了 onLocationChanged() 和 LocationServices.FusedLocationApi.requestLocationUpdates(),两者同时给出空值。我该如何改进它?我在设备设置中设置了高精度或 Gps、wifi 和移动网络作为定位方法。提前致谢。

还有一点,80%的null值是在没有wifi的时候收到的。我认为没有 wifi 的情况下 Fused Api 应该也能正常工作因为有 gps 可用,不是吗?

主类

public class LiveTrack extends AppCompatActivity {
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_live_track);
        Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
        setSupportActionBar(toolbar);

        jobScheduler = (JobScheduler)getSystemService(JOB_SCHEDULER_SERVICE);
        ComponentName jobService =
                        new ComponentName(getPackageName(), MyJobService.class.getName());
        JobInfo jobInfo =
                        new JobInfo.Builder(MYJOBID, jobService).setPeriodic(15 * 60 * 1000L)
                                .setExtras(bundle)
                                .build();
        int jobId = jobScheduler.schedule(jobInfo);

        if(jobScheduler.schedule(jobInfo)>0){
            Log.e("status","running");
        }else{
            Log.e("status","failed");
        }
    }
}

具有融合 Api Provider 的 JobService 类

public class MyJobService extends JobService
        implements GoogleApiClient.ConnectionCallbacks, GoogleApiClient.OnConnectionFailedListener
        , LocationListener {

    private GoogleApiClient mGoogleApiClient;
    LocationRequest mLocationRequest;
    private Location mLastLocation;



    public static String latitude;
    public static String latitudeIfNull;
    public static String longitude;
    public static String longitudeIfNull;

    @Override
    public boolean onStartJob(JobParameters jobParameters) {
        setUpLocationClientIfNeeded();

        mLocationRequest = LocationRequest.create();
        mLocationRequest.setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY);

        mLocationRequest.setInterval(30000);
        mLocationRequest.setFastestInterval(30000);
        return false;
    }


    @Override
    public boolean onStopJob(JobParameters jobParameters) {
        Toast.makeText(this,
                "App has stopped working. Please open the app again. Thankyou",
                Toast.LENGTH_LONG).show();
        return false;
    }

    @Override
    public void onConnected(@Nullable Bundle bundle) {
        if (ActivityCompat.checkSelfPermission(this, android.Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(this, android.Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
            return;
        }

        LocationServices.FusedLocationApi.requestLocationUpdates(this.mGoogleApiClient,mLocationRequest, this); 
        createLocationRequest();

        mLastLocation = LocationServices.FusedLocationApi.getLastLocation(mGoogleApiClient);

    }

    @Override
    public void onConnectionSuspended(int i) {

    }

    @Override
    public void onConnectionFailed(@NonNull ConnectionResult connectionResult) {

    }

    private void setUpLocationClientIfNeeded()
    {
        if(mGoogleApiClient == null)
            buildGoogleApiClient();
    }

    protected synchronized void buildGoogleApiClient() {
        this.mGoogleApiClient = new GoogleApiClient.Builder(this)
                .addConnectionCallbacks(this)
                .addOnConnectionFailedListener(this)
                .addApi(LocationServices.API)
                .build();
        this.mGoogleApiClient.connect();
    }

    @Override
    public void onLocationChanged(Location location) {
        latitudeIfNull = location.getLatitude() + "";
        longitudeIfNull = location.getLongitude() + "";
        Log.e("gps longitude",longitudeIfNull);
    }

    protected void createLocationRequest() {

        mLocationRequest = new LocationRequest();
        mLocationRequest.setInterval(60000);
        mLocationRequest.setFastestInterval(50000);
        mLocationRequest.setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY);
        if (ActivityCompat.checkSelfPermission(this, android.Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(this, android.Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
            return;
        }
        LocationServices.FusedLocationApi.requestLocationUpdates(mGoogleApiClient, mLocationRequest, new LocationCallback() {
            @Override
            public void onLocationResult(final LocationResult locationResult) {
                latitude = locationResult.getLastLocation().getLatitude() + "";
                longitude = locationResult.getLastLocation().getLongitude() + "";
                Log.i("latitude ", latitude + "");
                Log.i("longitude ", longitude + "");
            }

            @Override
            public void onLocationAvailability(LocationAvailability locationAvailability) {
                Log.i("onLocationAvailability", "onLocationAvailability: isLocationAvailable =  " + locationAvailability.isLocationAvailable());
            }
        }, null);
    }
}
                                                     .

【问题讨论】:

  • 获取 null 或不获取位置与在 Activity 中使用 JosSchduler、Service 或 FusedLocationApi 无关。最好的测试方法是使用带有 GPS 和 GpsStatusListener 的 LocationManager 在视图上显示卫星,并用于卫星的定位和 SNR。有时卫星无法使用,它可能会返回 null,但您应该使用 FLP 进行测试以自己查看。它使用 GPS 的方式与 LocationManager 使用它的方式相同。
  • 对不起,我没有得到你。 “使用 FLP 测试以亲自查看”是什么意思?
  • FusedLocationApi 有问题,有时会给出空位置。

标签: android fusedlocationproviderapi android-fusedlocation


【解决方案1】:

试试这个

像这样创建一个后台服务类

public class LocationBackGroundService extends Service implements LocationListener,
        GoogleApiClient.ConnectionCallbacks,
        GoogleApiClient.OnConnectionFailedListener {

    private static final String TAG = "LocationBackGroundService";
    private static final long INTERVAL = 100;
    private static final long FASTEST_INTERVAL = 100;

    LocationRequest mLocationRequest;
    GoogleApiClient mGoogleApiClient;
    Location mCurrentLocation;
    Context mCOntext;

    public void LocationBackGroundService(Context mContext) {
        this.mCOntext = mContext;
    }

    protected void createLocationRequest() {
        mLocationRequest = new LocationRequest();
        mLocationRequest.setInterval(INTERVAL);
        mLocationRequest.setFastestInterval(FASTEST_INTERVAL);
        mLocationRequest.setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY);
    }

    @Override
    public void onStart(Intent intent, int startId) {
        super.onStart(intent, startId);
        mGoogleApiClient.connect();
    }

    @Override
    public void onCreate() {
        super.onCreate();

        if (!isGooglePlayServicesAvailable()) {
            // finish();
        }
        createLocationRequest();
        mGoogleApiClient = new GoogleApiClient.Builder(this)
                .addApi(LocationServices.API)
                .addConnectionCallbacks(this)
                .addOnConnectionFailedListener(this)
                .build();

        if (mGoogleApiClient.isConnected()) {
            startLocationUpdates();
        }
    }

    private boolean isGooglePlayServicesAvailable() {
        int status = GooglePlayServicesUtil.isGooglePlayServicesAvailable(this);
        if (ConnectionResult.SUCCESS == status) {
            return true;
        } else {
            return false;
        }
    }

    @Nullable
    @Override
    public IBinder onBind(Intent intent) {
        return null;
    }

    @Override
    public void onConnected(Bundle bundle) {
        startLocationUpdates();
    }


    protected void startLocationUpdates() {
        PendingResult<Status> pendingResult = LocationServices.FusedLocationApi.requestLocationUpdates(
                mGoogleApiClient, mLocationRequest, this);

        Log.d(TAG, "Location update started ..............: ");
    }

    @Override
    public void onConnectionSuspended(int i) {

        Toast.makeText(this, "OnConnection Suspended", Toast.LENGTH_SHORT).show();
    }

    @Override
    public void onConnectionFailed(ConnectionResult connectionResult) {
        Toast.makeText(this, "OnConnection Failed", Toast.LENGTH_SHORT).show();
    }

    @Override
    public void onLocationChanged(Location location) {

        if (null != mCurrentLocation) {
            mCurrentLocation = location;
            String lat = String.valueOf(mCurrentLocation.getLatitude());
            String lng = String.valueOf(mCurrentLocation.getLongitude());

        }
    }
}

当活动像这样开始时调用

startService(new Intent(this, yourBackgroundServiceName.class));

在清单中

<service android:name=".yourBackgroundServiceName"></service>

并且不要忘记在声明服务之前添加运行时权限

【讨论】:

    猜你喜欢
    • 2019-08-20
    • 1970-01-01
    • 2017-09-30
    • 1970-01-01
    • 1970-01-01
    • 2016-06-30
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多