我正在尝试创建一个应用程序,该应用程序将每 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();
}
}