在 android 中启用 GPS

Getting GPS in service in android

我的问题并不新鲜,但 Whosebug 中的 none 个答案对我很有帮助。

情况:我有一项与警报配合使用的服务。它每 1 分钟重复一次,运行 为我提供服务。在该服务中,我需要将 GPS 数据发送到网络服务器。

代码如下:

import android.app.Service;
import android.content.Intent;
import android.location.Location;
import android.os.AsyncTask;
import android.os.IBinder;
import bliksund.taxitracking.tools.Cachepref;
import bliksund.taxitracking.tools.PostData;


public class SendData extends Service {
Cachepref cachepref;
GET_GPS gps;

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

@Override
public int onStartCommand(Intent intent, int flags, int startId) {
    cachepref = new Cachepref(this);
    gps = new GET_GPS(this);
    new getloc().execute();
    return super.onStartCommand(intent, flags, startId);
}

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

private class getloc extends AsyncTask<Void, Void, Void> {
    String username;
    Double lt;
    Double lg;
    Location location;
    @Override
    protected Void doInBackground(Void... params) {
        username = cachepref.getUsername();
         location = gps.getLocation();
         lt = location.getLatitude();
        lg = location.getLongitude();
        return null;
    }

    @Override
    protected void onPostExecute(Void aVoid) {


        PostData postData = new PostData(username, 1, lt, lg);
        super.onPostExecute(aVoid);
    }
}
}
这是我的服务。
+ PostData 将Post 参数传给网页。
+ Cachepref 保存用户会话的用户名。

问题:当代码去获取 GPS 位置时。它会出错:

location = gps.getLocation(); // will cause to below line error
Can't create handler inside thread that has not called Looper.prepare()

我用AsynTask解决了这个问题,但还是存在

GET_GPS代码如下:

import android.app.Service;
import android.content.Context;
import android.content.Intent;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.os.Bundle;
import android.os.IBinder;
import android.util.Log;


public class GET_GPS extends Service implements LocationListener {

private final Context mContext;

// flag for GPS status
boolean isGPSEnabled = false;

// flag for network status
boolean isNetworkEnabled = false;

// flag for GPS status
boolean canGetLocation = false;

Location location; // location
double latitude; // latitude
double longitude; // longitude

private static final long MIN_TIME_BW_UPDATES = 1000 * 60 * 1; // 1 minute
private static final long MIN_DISTANCE_CHANGE_FOR_UPDATES = 10; // 10 meters
protected LocationManager locationManager;
public GET_GPS(Context mContext) {
    this.mContext = mContext;
}
public Location getLocation() {
    try {
        locationManager = (LocationManager) mContext
                .getSystemService(LOCATION_SERVICE);

        // getting GPS status
        isGPSEnabled = locationManager
                .isProviderEnabled(LocationManager.GPS_PROVIDER);

        // getting network status
        isNetworkEnabled = locationManager
                .isProviderEnabled(LocationManager.NETWORK_PROVIDER);

        if (!isGPSEnabled && !isNetworkEnabled) {
            // no network provider is enabled
        } else {
            this.canGetLocation = true;
            // First get location from Network Provider
            if (isNetworkEnabled) {
                locationManager.requestLocationUpdates(
                        LocationManager.NETWORK_PROVIDER,
                        MIN_TIME_BW_UPDATES,
                        MIN_DISTANCE_CHANGE_FOR_UPDATES, this);
                Log.d("Network", "Network");
                if (locationManager != null) {
                    location = locationManager
                            .getLastKnownLocation(LocationManager.NETWORK_PROVIDER);
                    if (location != null) {
                        latitude = location.getLatitude();
                        longitude = location.getLongitude();
                    }
                }
            }
            // if GPS Enabled get lat/long using GPS Services
            if (isGPSEnabled) {
                if (location == null) {
                    locationManager.requestLocationUpdates(
                            LocationManager.GPS_PROVIDER,
                            MIN_TIME_BW_UPDATES,
                            MIN_DISTANCE_CHANGE_FOR_UPDATES, this);
                    Log.d("GPS Enabled", "GPS Enabled");
                    if (locationManager != null) {
                        location = locationManager
                                .getLastKnownLocation(LocationManager.GPS_PROVIDER);
                        if (location != null) {
                            latitude = location.getLatitude();
                            longitude = location.getLongitude();
                        }
                    }
                }
            }
        }

    } catch (Exception e) {
        e.printStackTrace();
    }

    return location;
}
public void stopUsingGPS(){
    if(locationManager != null){
        locationManager.removeUpdates(GET_GPS.this);
    }
}
/**
 * Function to get latitude
 * */
public double getLatitude(){
    if(location != null){
        latitude = location.getLatitude();
    }

    // return latitude
    return latitude;
}

/**
 * Function to get longitude
 * */
public double getLongitude(){
    if(location != null){
        longitude = location.getLongitude();
    }

    // return longitude
    return longitude;
}

/**
 * Function to check GPS/wifi enabled
 * @return boolean
 * */
public boolean canGetLocation() {
    return this.canGetLocation;
}


@Override
public IBinder onBind(Intent intent) {
    // TODO: Return the communication channel to the service.
    throw new UnsupportedOperationException("Not yet implemented");
}

@Override
public void onLocationChanged(Location location) {

}

@Override
public void onStatusChanged(String provider, int status, Bundle extras) {

}

@Override
public void onProviderEnabled(String provider) {

}

@Override
public void onProviderDisabled(String provider) {

}
}

在 ρяσѕρєя K 的帮助下。他说要将这些代码移动到 PostExecute,结果是 运行,PostData 出现了问题。我用下面的方式解决了。我希望它能帮助别人。

private class getloc extends AsyncTask<Void, Void, Void> {
    String username;
    Double lt;
    Double lg;
    Location location;
    @Override
    protected Void doInBackground(Void... params) {

        return null;
    }

    @Override
    protected void onPostExecute(Void aVoid) {
        username = cachepref.getUsername();
        location = gps.getLocation();
        lt = location.getLatitude();
        lg = location.getLongitude();
        new Thread(new Runnable() {
            @Override
            public void run() {
                PostData postData = new PostData(username, 1, lt, lg);
            }
        }).start();

        super.onPostExecute(aVoid);
    }
}