[英]error: unreported exception InterruptedException; must be caught or declared to be thrown (calling AsyncTask)
這是我擴展AsyncTask的類
public class JSONFunctions extends AsyncTask<Void, Void, String> {
@Override
protected String doInBackground(Void... urls) {
String line = "";
HttpClient httpclient = new DefaultHttpClient();
HttpGet httpget = new HttpGet("http://appDev.milasevicius.com/server/homeresults.php");
try {
HttpResponse response = httpclient.execute(httpget);
if(response != null) {
InputStream inputstream = response.getEntity().getContent();
line = convertStreamToString(inputstream);
} else {
line = "Unable to complete your request";
}
} catch (ClientProtocolException e) {
line = "Caught ClientProtocolException";
} catch (IOException e) {
line = "Caught IOException";
} catch (Exception e) {
line = "Caught Exception";
}
return line;
}
protected void onProgressUpdate(Integer... progress) {
}
protected void onPostExecute(String result) {
}
}
這是我的電話:
String output = new JSONFunctions().execute().get();
但是編譯器說
error: unreported exception InterruptedException; must be caught or declared to be thrown
對不起,我的問題很笨拙,但是如何解決呢? 我在正確地打電話以取得結果嗎?
public final Result get ()
Added in API level 3
Waits if necessary for the computation to complete, and then retrieves its result.
Returns
The computed result.
Throws
CancellationException If the computation was cancelled.
ExecutionException If the computation threw an exception.
InterruptedException If the current thread was interrupted while waiting.
get()
拋出InterrruptedException
。 您的日志說您需要抓住那些。
另外,您不應調用get()
因為它阻塞了ui線程等待結果。 您不應該阻止ui線程。
刪除get()
並作為new JSONFunctions().execute()
調用。
要在活動中獲取結果,請使用界面
范例@
從.get()引發的裸露InterruptedException表示當前執行線程(調用.get()的當前線程)在調用get()之前或在.get()中被阻塞時被中斷。 這與執行程序線程或其被中斷的任務之一不同。 某人或某物正在中斷您的“主”線程-或至少是調用.get()的線程。
采用
new JSONFunctions().execute()
代替
new JSONFunctions().execute().get();
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.