我有以下代码从我的网站加载文件
class DownloadTT4FileTask extends AsyncTask<String, String, String> {
private Context mContext;
private String mFilename;
private ProgressDialog progressDialog;
String retString="";
public DownloadTT4FileTask(Context context, String filename) {
mContext=context;
mFilename=filename;
}
@Override
protected void onPreExecute() {
Log.d("DownloadTT4FileTask", "onPreExecute");
progressDialog = ProgressDialog.show(mContext, mFilename, "Loading. Please wait...");
}
protected String doInBackground(String... args) {
URL url;
try {
url = new URL(args[0]);
java.net.URLConnection con = url.openConnection();
con.connect();
//Log.d("DownloadTT4FileTask", "con.connect ok ");
java.io.BufferedReader in = new java.io.BufferedReader(new java.io.InputStreamReader(con.getInputStream()));
String line;
for (; (line = in.readLine()) != null; ) {
// just read the line and save it
retString += line+"\n";
}
} catch (MalformedURLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return retString;
}
protected void onPostExecute(String result) {
Log.d("DownloadTT4FileTask", "onPreExecute");
progressDialog.dismiss();
}
};
// loading from website
filename = "http://2112design.com/tabs/"+band+"/"+song+".tt4";
String fileContents = new DownloadTT4FileTask(context, filename).execute(filename).get(15L, TimeUnit.SECONDS);
br = new BufferedReader(new StringReader(fileContents));
它加载正常(加载大约 5 秒),但进度对话框有点偏离。它不会在下载开始时出现在屏幕上。任务结束时它会在屏幕上短暂闪烁。
我已经看过很多关于如何使用它的例子,看起来这是很正常的代码。
也许上下文是问题?我从一个在不是主要活动的片段中运行的 onChildClick 中得到它。我尝试使用主要活动上下文,但这只是崩溃了。
@Override
public boolean onChildClick(ExpandableListView parent, View v, int groupPosition, int childPosition, long id) {
Globals.mDoc.OpenTT4Document(parent.getContext(), band, song, mRemoteFilesThis==null ? Doc.SDCARD : Doc.WEBSITE);
return false;
}
有任何想法吗?谢谢