我正在尝试编写一个间隔运行的服务。并且每次运行时,它都应该检索手机的当前位置。就看起来我的间隔运行正常。但是一旦我按下开始按钮,我就不能再使用停止按钮来停止它了。我已经尝试过使用一个线程,但是那个总是给我错误。我也尝试过使用while循环,但不知何故我的应用程序崩溃了。无论如何,这是我现在的代码:
public class Location extends Service {
LocationManager locMan;
LocationListener myLocListener;
int intervalTime = 1000 * 30;
int minTime = 0;
float minDistance = 0;
@Override
public IBinder onBind(Intent intent) {
// TODO Auto-generated method stub
return null;
}
@Override
public void onCreate() {
// TODO Auto-generated method stub
final Handler handler = new Handler();
final Runnable runnable = new Runnable() {
@Override
public void run() {
// TODO Auto-generated method stub
locMan = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
//check if GPS is on
if (!locMan.isProviderEnabled(LocationManager.GPS_PROVIDER)) {
Toast.makeText(
getApplicationContext(),
"Failed to start Location service! Please turn you GPS on!",
Toast.LENGTH_LONG).show();
stopSelf();
} else if (locMan.isProviderEnabled(LocationManager.GPS_PROVIDER)) {
Toast.makeText(getApplicationContext(),
"Service Started",
Toast.LENGTH_SHORT).show();
getLocation();
}
}
private void getLocation() {
// TODO Auto-generated method stub
try {
locMan = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
//while GPS remains on, run this script.
while (locMan.isProviderEnabled(LocationManager.GPS_PROVIDER)) {
myLocListener = new LocationListener() {
@Override
public void onStatusChanged(String provider,
int status, Bundle extras) {
// TODO Auto-generated method stub
}
@Override
public void onProviderEnabled(String provider) {
// TODO Auto-generated method stub
}
@Override
public void onProviderDisabled(String provider) {
// TODO Auto-generated method stub
}
@Override
public void onLocationChanged(
android.location.Location location) {
// TODO Auto-generated method stub
String loc = "Latitude is: "
+ location.getLatitude()
+ "Longitude is: "
+ location.getLongitude();
Toast.makeText(getApplicationContext(),
loc,
Toast.LENGTH_SHORT).show();
}
};
// Specify criteria for a gps provider and get the provider
Criteria criteria = new Criteria();
criteria.setPowerRequirement(Criteria.POWER_LOW);
criteria.setAccuracy(Criteria.ACCURACY_FINE);
criteria.setAltitudeRequired(false);
criteria.setBearingRequired(false);
criteria.setCostAllowed(true);
criteria.setSpeedRequired(false);
String BestProvider = locMan.getBestProvider(criteria,
false);
locMan.requestLocationUpdates(BestProvider,
minTime,
minDistance,
myLocListener);
Toast.makeText(getApplicationContext(),
"Location Retrieved",
Toast.LENGTH_SHORT).show();
handler.postDelayed(this, intervalTime);
}
stopSelf();
} catch (Exception e) {
e.printStackTrace();
}
}
};
handler.postDelayed(runnable, intervalTime);
}
@Override
public void onDestroy() {
// TODO Auto-generated method stub
if (myLocListener != null) {
locMan.removeUpdates(myLocListener);
}
Toast.makeText(getApplicationContext(),
"Service stopped",
Toast.LENGTH_LONG).show();
super.onDestroy();
}
}