我正在从一个 android 服务启动一个线程,该服务使用 tcp 连接以恒定的时间间隔不断地将文件上传到服务器。该线程有一个执行此操作的 while(true) 循环。操作会执行一段时间,但随后会停止。我尝试使用 adb logcat 进行调试,并看到我在线程内打印的某些消息仅一段时间。之后他们也停了下来。此外,当我停止服务时,我得到了 NullPointerException,因为在服务的 onDestroy() 方法中我使用了线程对象。
只要服务运行,线程是否会被杀死并且不运行?我是否需要在服务类本身的 onStart() 中执行此 while(true) 操作而不生成新线程?
提供的任何解决方案都会有很大帮助。
代码如下:
public void run()
{
Log.d("TAG","Starting Thread");
String data = "";
updateServer();
while(flag)
{
String path = extStorageDirectory + "/" + appFolder + "/" + "SAT_pingLog_" + Long.toString(System.currentTimeMillis()) + ".txt";
createFile(path);
int count = 0;
while(flag && count < 32768)
{
data = "";
String result = Long.toString(getLatency(url));
data = Long.toString(System.currentTimeMillis()) + " " + gps[0] + " " + gps[1] + " " + strength + " " + result;
Log.d("DEBUGGING",data);
writeToLog(path,data);
try
{
Thread.sleep(sleepTime);
}
catch (InterruptedException e)
{
// TODO Auto-generated catch block
e.printStackTrace();
}
count++;
}
updateServer();
}
}public long getLatency(String Url)
{
long startTime = 0, endTime = 0, latency = 0;
try
{
HttpParams httpParameters = new BasicHttpParams();
// Set the timeout in milliseconds until a connection is established.
// The default value is zero, that means the timeout is not used.
int timeoutConnection = 10000;
HttpConnectionParams.setConnectionTimeout(httpParameters, timeoutConnection);
// Set the default socket timeout (SO_TIMEOUT)
// in milliseconds which is the timeout for waiting for data.
int timeoutSocket = 10000;
HttpConnectionParams.setSoTimeout(httpParameters, timeoutSocket);
DefaultHttpClient httpclient = new DefaultHttpClient(httpParameters);
HttpHead httphead = new HttpHead(Url);
//HttpParams httpParameters = new BasicHttpParams();
//HttpConnectionParams.setConnectionTimeout(httpParameters, 5000);
//HttpConnectionParams.setSoTimeout(httpParameters, 5000);
//HttpClient httpClient = new DefaultHttpClient(httpParameters);
//request.setURI(new URI("http://www.google.com"));
System.out.println("Executing request " + httphead.getURI());
Log.d("DEBUGGING","STARTING EXECUTE");
startTime = System.currentTimeMillis();
HttpResponse response = httpclient.execute(httphead);
endTime = System.currentTimeMillis();
Log.d("DEBUGGING","ENDING EXECUTE");
int status = response.getStatusLine().getStatusCode();
if (status == HttpStatus.SC_OK)
latency = endTime - startTime;
else
latency = 0;
}
catch(Exception e)
{
Log.d("DEBUGGING","EXCEPTION CAUGHT");
e.printStackTrace();
}
Log.d("DEBUGGING","LATENCY:"+Long.toString(latency));
return latency;
}
}