Расширен от lx222 ответа, я реализовал для AsyncTask, ProgressDialog.Поздно, но я надеюсь, что это может быть полезно с кем-то: D
public class OpenXMLFileOperator extends AsyncTask<Void, Integer, Void>{
private ProgressDialog progressDialog;
private String filePath;
private Context context;
public OpenFileOperator(Context context,String filePath){
this.context = context;
this.filePath = filePath;
}
@Override
protected Void doInBackground(Void... arg0) {
try {
if (filePath != null) {
File file = new File(filePath);
if (file.exists()) {
InputStream stream = new FileInputStream(file);
ProgressFilterInputStream pfis = new ProgressFilterInputStream(stream,file.length());
Reader reader = new InputStreamReader(pfis, "UTF-8");
YourXMLHandle yourHandle = new YourXMLHandle();
android.util.Xml.parse(reader,yourHandle);
stream.close();
reader.close();
pfis.close();
}
}
}catch (Exception e) {
if (BuildConfig.DEBUG) Log.e(TAG, "Exception", e);
}
return null;
}
@Override
protected void onPreExecute() {
try{
progressDialog = new ProgressDialog(context);
progressDialog.setMessage("Loading file");
progressDialog.setCancelable(false);
progressDialog.setIndeterminate(false);
progressDialog.setMax(100);
progressDialog.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
progressDialog.show();
}catch(Exception e){
if (BuildConfig.DEBUG) Log.e(TAG,"onPostExecute",e);
}
super.onPreExecute();
}
@Override
protected void onCancelled() {
try{
if (progressDialog!=null && progressDialog.isShowing()){
progressDialog.dismiss();
}
}catch(Exception e){
if (BuildConfig.DEBUG) Log.e(TAG,"onPostExecute",e);
}
super.onCancelled();
}
@Override
protected void onPostExecute(Void result) {
try{
if (progressDialog!=null && progressDialog.isShowing()){
progressDialog.dismiss();
}
}catch(Exception e){
if (BuildConfig.DEBUG) Log.e(TAG,"onPostExecute",e);
}
//TODO: to do something after file loaded
super.onPostExecute(result);
}
@Override
protected void onProgressUpdate(Integer... values) {
int progress = values[0];
if (progressDialog!=null) {
progressDialog.setProgress(progress);
}
super.onProgressUpdate(values);
}
private class ProgressFilterInputStream extends FilterInputStream {
private int counter = 0;
private long fileLength;
private int maximum = 100;
public ProgressFilterInputStream(InputStream in, long fileLength) {
super(in);
this.fileLength = fileLength;
}
@Override
public int read(byte[] buffer, int offset, int count) throws IOException {
if (counter==0){
maximum = (int)(fileLength/buffer.length);
}
publishProgress((counter++)*100/maximum);
return super.read(buffer, offset, count);
}
}
}