我是Android编程新手。我有一个线程,我已请求位置更新。问题是onLocationChanged(Location loc)
中的代码永远不会被执行。请解释我如何纠正这个问题。
public void run() {
Looper.prepare();
while (isMyServiceRunning()) {
try {
Thread.sleep(3000);
} catch (InterruptedException e) {
e.printStackTrace();
}
try {
Log.d("spt", "read status started");
if ((Connectivity.isConnected(getApplicationContext()))) {
URL urlreadstatus = new URL("http://asd.fgh.com/status.txt");
// Log.d("spt",String.valueOf(URLUtil.isValidUrl("http://asd.fgh.com/status.txt")));
BufferedReader in = new BufferedReader( new InputStreamReader(urlreadstatus.openStream()));
str = in.readLine();
if(!str.equals(null)){
Log.d("spt", str);
}
in.close();
Log.d("spt", "read status complete");
} else {
Log.d("spt", "not connected");
break;
}
} catch (MalformedURLException e1) {
e1.printStackTrace();
} catch (IOException e) {
Log.d("spt", "IO exception");
str = "11";
e.printStackTrace();
} catch(NullPointerException e){
str="11";
}
if (str.equals(null)) {
str = "11";
}
if (str.length() == 1) {
loststatus++;
LocationManager l;
l=(LocationManager) getSystemService(Context.LOCATION_SERVICE);
Criteria criteria = new Criteria();
provider = l.getBestProvider(criteria, false);
l.requestLocationUpdates("gps", 400, 1, this);
Log.d("spt", "lost status=1 requesting location updates");
} else {
loststatus = 0;
}
}
}
@Override
public void onLocationChanged(Location loc) {
// TODO Auto-generated method stub
Log.d("spt", "in loc changed");
double longi = loc.getLongitude();
double lati = loc.getLatitude();
double acc=loc.getAccuracy();
Log.d("spt", String.valueOf(acc));
if (loststatus > 0) {
HttpPost httpPost = new HttpPost(
"http://asd.fgh.com/writegps.php?value="
+ String.valueOf(lati) + ","
+ String.valueOf(longi));
// output is the variable you used in your program
try {
DefaultHttpClient httpClient = new DefaultHttpClient();
httpClient.execute(httpPost);
Log.d("spt", "writing coord to file");
} catch (ClientProtocolException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
Toast.makeText(this, String.valueOf(lati) + String.valueOf(longi),
Toast.LENGTH_SHORT).show();
}
}
答案 0 :(得分:0)
尝试按照以下方式设置位置监听器,就像在课堂上实现一个位置一样(假设您在视线范围内执行了该操作):
private void setupLocationUpdates() {
// Acquire a reference to the system Location Manager
mLocationManager = (LocationManager) this.getSystemService(Context.LOCATION_SERVICE);
// Define a listener that responds to location updates
mLocationListener = new LocationListener() {
// Called when the location has changed.
public void onLocationChanged(Location location) {
mLocation = location;
// DO SOMETHING HERE
}
};
mlocationProvider = LocationManager.GPS_PROVIDER;
// Register for location updates
mLocationManager.requestLocationUpdates(mlocationProvider, 0, 0, mLocationListener);
}