[英]Multithreading android application
我的Android应用程序中有两个线程,一个线程每1/2秒增加一次速度值,另一个线程从该数组列表中获取平均值,以减少波动,问题是只有一个线程正在启动,我不知道为什么。 这是代码:
Runnable r = new Runnable() {
public void run() {
while (flag) {
isConnected = activeNetwork != null && activeNetwork.isConnectedOrConnecting();
if(isConnected)
{
gps.getLocation();
time2 = System.currentTimeMillis();
latitude_temp = gps.getLatitude();
longitude_temp = gps.getLongitude();
if (!initial_position.flag)
{
double distance_m = gps.location.distanceTo(initial_position.location);
double distance_km = gps.calculateDistance(initial_position);
Log.i(TAG, "Diff between gps locations in meters:" + Double.toString(distance_m)
+ " in km:" + Double.toString(distance_km));
if (distance_m >= 10.0) {
average = false;
storeLocation(vehicle_id, latitude_temp, longitude_temp, time2);
double time_s = (time2 - time1);
double time_hr = time_s / 3600;
double speed3 = (gps.location.getSpeed() * 3600) / 1000;
speed = averageSpeed();
speed1 = (distance_km) / (time_hr);
double speed2 = (distance_m * 3600) / (time_s * 1000);
storeSpeed(vehicle_id, speed3, time2);
storeSpeed(vehicle_id, speed, time2);
storeSpeed(vehicle_id, speed1, time2);
storeSpeed(vehicle_id, speed2, time2);
time1 = time2;
initial_position.location = new Location(gps.location);
speeds.clear();
average = true;
}
}
else {
storeLocation(vehicle_id, latitude_temp, longitude_temp, time2); /*added*/
initial_position.flag = false;
initial_position.location = new Location(gps.location); /*added*/
initial_position.latitude = latitude_temp;
initial_position.longitude = longitude_temp;
time1 = time2;
}
}
try {
Thread.sleep(10000);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
};
Runnable r1 = new Runnable() {
public void run() {
boolean isConnected1 = activeNetwork != null && activeNetwork.isConnectedOrConnecting();
if (isConnected1)
{
Log.i(TAG, "runnable r1 is starting");
while (average)
{
Log.i(TAG, "runnable r1 is in the loop");
gps_temp.getLocation();
if (gps_temp.location.hasSpeed())
{
double s = (gps_temp.location.getSpeed()*3600)/1000;
speeds.add(s);
Log.i(TAG, "adding speed");
}
try
{
Thread.sleep(500);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
}
};
Thread myThread1 = new Thread(r1);
myThread1.start();
Thread myThread = new Thread(r);
myThread.start();
您正在两个线程的开头设置isConnected
的值。 尝试将其置于两者之外并进行调试。 由于另一个线程中设置的isConnected
的值,可能是一个线程退出了。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.