我正在尝试创建一个应用程序,每10分钟收集10个位置更改。我目前要做的是有一个警报管理器,每10分钟启动一次服务。该服务将有一个LocationManager,它将启动一个LocationListener并在服务停止之前获取10次位置更新。但是,我不知道为什么我没有获得任何位置更新。任何人都可以帮我指出我的错误吗?
public class MainActivity extends Activity {
public static ArrayList <Location> mLocationList;
public static int counter;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
//Will add in the bits for the LocationList after fixing the location problem
mLocationList = new ArrayList<Location>();
counter = 0;
Intent intent = new Intent(MainActivity.this, TrackingService.class);
PendingIntent pintent = PendingIntent.getService(MainActivity.this, 0, intent,0);
AlarmManager alarm = (AlarmManager) getSystemService(Context.ALARM_SERVICE);
alarm.setRepeating(AlarmManager.RTC_WAKEUP, System.currentTimeMillis(),
1000 * 60 * 10, pintent);
}
}
以下是我的服务内容:
@Override
public int onStartCommand(Intent intent, int flags, int startId) {
Toast.makeText(this, "Service Started ", Toast.LENGTH_SHORT).show();
mlocationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
mlocationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER,
0, 0, this);
return START_STICKY;
}
@Override
public void onDestroy() {
// Unregistering listeners
mlocationManager.removeUpdates(this);
MainActivity.counter=0;
super.onDestroy();
Toast.makeText(this, "Service Stopped", Toast.LENGTH_SHORT).show();
}
@Override
public void onLocationChanged(Location location) {
// TODO Auto-generated method stub
if (location == null) {
return;
}
else {
MainActivity.mLocationList.add(location);
MainActivity.counter++;
double lat=location.getLatitude();
double lng=location.getLongitude();
Toast.makeText(this, "Location" + lat + lng, Toast.LENGTH_SHORT).show();
}
if (MainActivity.counter == 9){
this.stopSelf();
}
}