我正在制作一个电视指南android项目,我想从他们的网站上获取不同电视频道的更新节目指南。如何以优化的方式访问和使用项目指南信息?
答案 0 :(得分:0)
如果您想从指定页面获取数据,可以下载这些页面,然后解析它们。
这是一个示例AsyncTask,它在后台完成这个工作人员,下载完成后,你可以在网页上找到:
public class DownloadManager extends AsyncTask<String, Integer, Integer> {
private Context context;
private ProgressDialog progressDialog;
/**
* @param context
* of application
* @param progressDialog
* which you want to show the download progress.
*/
public DownloadManager(Context context, ProgressDialog progressDialog, DownloadCallbackListener downloadListener) {
this.context = context;
this.progressDialog = progressDialog;
}
@Override
protected Integer doInBackground(String... args) {
String sUrl = args[0];
String fileName = args[1];
try {
URL url = new URL(sUrl);
URLConnection connection = url.openConnection();
connection.setDoInput(true);
connection.connect();
int contentLenght = connection.getContentLength();
byte[] buffer = new byte[10240];
InputStream inStream = connection.getInputStream();
OutputStream output = new FileHelper(fileName).getFileOutputStream();
int readCount = 0;
int totalRead = 0;
int failurTryCount = 0;
boolean downloadFinished = true;
while ((readCount = inStream.read(buffer)) != -1) {
try {
if (failurTryCount > 5) {
downloadFinished = false;
break;
}
downloadFinished = true;
output.write(buffer, 0, readCount);
output.flush();
totalRead += readCount;
onProgressUpdate(totalRead * 100 / contentLenght);
} catch (Exception e) {
++failurTryCount;
}
}
return downloadFinished ? 0 : -4;
} catch (MalformedURLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
return -1;
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
return -2;
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
return -3;
}
}
@Override
protected void onProgressUpdate(Integer... values) {
super.onProgressUpdate(values);
progressDialog.setProgress(values[0]);
}
@Override
protected void onPostExecute(Integer result) {
if (result == 0) {
// progressDialog.dismiss();
}
super.onPostExecute(result);
}
}
但如果这些网站有网络服务消费,那么最好选择使用它们。