API上的位置和GPS> 23

时间:2017-05-26 17:51:13

标签: java android api location locationmanager

你好我正在尝试实现一个我想跟踪GPS的应用程序。 这是我的代码,但遗憾的是它不适用于我正在使用的当前API。 我找到了一些代码,但这仅适用于活动。我正试图在服务中实现这一点。

public class TrackGPS extends Service {

GPSInformation gpsInfo;


private LocationManager locationManager = null;
private String selectedProvider = null;

@Override
public void onCreate() {
    locationManager = (LocationManager) this.getSystemService(LOCATION_SERVICE);

    Criteria criteria = new Criteria();
    criteria.setAccuracy(Criteria.ACCURACY_COARSE);
    criteria.setPowerRequirement(Criteria.POWER_LOW);
    selectedProvider = locationManager.getBestProvider(criteria,true);
}



@Override
public int onStartCommand(Intent intent, int flags, int startId) {

    SimpleDateFormat isoFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss", Locale.getDefault());
    Date date = new Date();
    String timestamp = isoFormat.format(date);

    gpsInfo = new GPSInformation();
    gpsInfo.setTimestamp(timestamp);


    if(locationManager.isProviderEnabled(LocationManager.GPS_PROVIDER)) {
   //THIS IS WHERE IT STARTS CRASHING AND I GET AN ERROR I NEED PERMISSION

       Location lastKnownLocation = locationManager.getLastKnownLocation(selectedProvider);


        if(lastKnownLocation != null) {
            gpsInfo.setLatitude(lastKnownLocation.getLatitude());
            gpsInfo.setLatitude(lastKnownLocation.getLongitude());
            gpsInfo.setValid(1);
        } else {
         .........
        }

    } else {
       ...........
    }

    HttpRequestTask task = new HttpRequestTask(gpsInfo);
    task.execute();

    stopSelf();
    return START_STICKY;
}


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


}

0 个答案:

没有答案