我试图通过后台服务每隔 1 分钟向服务器发送一次 GPS 坐标。它第一次为你调用服务,但不会重复。
设置闹钟的代码:
Intent gpsIntent = new Intent(CheckInActivity.this, GoogleMapService.class);
gpsPendingIntent = PendingIntent.getService(CheckInActivity.this, 0, gpsIntent, 0);
AlarmManager alarmManager_gps = (AlarmManager)getSystemService(ALARM_SERVICE);
Calendar calendar_gps = Calendar.getInstance();
calendar_gps.add(Calendar.SECOND, 20);
alarmManager_gps.setRepeating(AlarmManager.RTC_WAKEUP, calendar_gps.getTimeInMillis(), TimeUnit.MINUTES.toMillis(1), gpsPendingIntent);
服务
public class GoogleMapService extends Service {
private boolean gps_enabled = false;
private boolean network_enabled = false;
private static Location sLocation;
private LocationManager locManager;
private LocationListener locListener = new MyLocationListener();
private CallBack callback;
@Override
public void onCreate() {
}
@Override
public IBinder onBind(Intent intent) {
Log.w(null,"GPS Service called");
locManager = (LocationManager) this.getSystemService(Context.LOCATION_SERVICE);
try {
gps_enabled = locManager.isProviderEnabled(LocationManager.GPS_PROVIDER);
} catch (Exception ex) {
}
try {
network_enabled = locManager.isProviderEnabled(LocationManager.NETWORK_PROVIDER);
} catch (Exception ex) {
}
if (gps_enabled) {
locManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 0, 0, locListener);
}
if (network_enabled) {
locManager.requestLocationUpdates(LocationManager.NETWORK_PROVIDER, 0, 0, locListener);
}
callback = new CallBack() {
public void onResult(Boolean result) {
// TODO Auto-generated method stub
}
public void onProgress() {
// TODO Auto-generated method stub
}
};
return null;
}
@Override
public void onDestroy() {
super.onDestroy();
}
@Override
public void onStart(Intent intent, int startId) {
super.onStart(intent, startId);
}
@Override
public boolean onUnbind(Intent intent) {
return super.onUnbind(intent);
}
class MyLocationListener implements LocationListener {
public void onLocationChanged(Location location) {
if (location != null) {
// This needs to stop getting the location data and save the battery power.
locManager.removeUpdates(locListener);
sLocation = location;
Model.coordinates = location.getLatitude() + "," + location.getLongitude();
try{
SendGPSCoordinatesOperation task = new SendGPSCoordinatesOperation(callback);
task.execute("");
Log.w(null,"Sent");
}
catch(Exception e){
Log.w(null,"Couldn't be sent");
}
Log.w(null,"The coordinates are"+Model.coordinates);
}
}
public void onProviderDisabled(String provider) {
// TODO Auto-generated method stub
}
public void onProviderEnabled(String provider) {
// TODO Auto-generated method stub
}
public void onStatusChanged(String provider, int status, Bundle extras) {
// TODO Auto-generated method stub
}
}
}
编辑:AndroidManifest 代码