我从一个android服务启动一个线程,该服务不断地使用tcp连接将文件上传到服务器。该线程有一个执行此操作的while(true)循环。操作会在某个时间执行,但随后会停止。我尝试使用adb logcat进行调试,并查看我在线程中打印的某些消息只有一段时间。之后他们也停了下来。此外,当我停止服务时,我得到了一个NullPointerException,因为在我使用线程对象的服务的onDestroy()方法中。
只要服务运行,线程是否会被杀死并且不会运行?我是否需要在服务类本身的onStart()中执行(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;
}
}
答案 0 :(得分:3)
只要服务运行,线程是否会被杀死并且不会运行?
Android组件无视他们未创建的线程。因此,虽然IntentService
将处理它为onHandleIntent()
使用而创建的线程,但是常规Service
将不会关注您自己分叉的任何线程。
一旦服务被销毁,它泄漏的任何线程将继续运行,直到Android终止该过程为止。
如果您的线程意外停止,那与Service
无关 - 再次,Service
对您自己的线程一无所知。确保你没有通过空catch
块来静默地吃异常,因为我的猜测是某些东西引发异常,导致你退出循环,但是你没有因某种原因记录它。 / p>