我已经实现了一个 Asyntask,我正在尝试使用它来下载图像并将其保存到手机的 sdcard 中。OnPostExecute 我再次调用 asyntask,这一直持续。但是大约一个小时后,应用程序开始说 ANR ,我应该如何处理这个场景。
public class DownloadSavePics extends AsyncTask<Void, Void, String> {
Context context;
String Tag = "DownloadSavePics";
String res;
QVSEngine qvsEngine;
String IID;
String url1 = "";
String deviceId ="";
String FileName ="";
/*
* Pass all data required to log in and handle the result here.
*/
public DownloadSavePics(Context context,String url1,String deviceId) {
this.context = context;
this.deviceId = deviceId;
this.url1 = url1;
qvsEngine = new QVSEngine(context,null);
}
@Override
protected void onPreExecute() {
Log.i(Tag, "inside pre execute");
}
/*
* Do all the network IO and time-consuming parsing in here, this method
* will be invoked in its own thread, not blocking the UI.
*/
protected String doInBackground(Void... params) {
/*
* the background thread calls the method CallService
*
*/
if (qvsEngine.checkInternetConnection()){
CallService();
}
return FileName;
}
public void CallService (){
/*
* downloading the file
*/
try {
if(qvsEngine.checkInternetConnection()){
/*
* requested for connection so set the led1 as amber
*/
try {
URL imgURL = new URL(url1);
Log.e(Tag,"Downloading from hotspot "+url1);
URLConnection ucon = imgURL.openConnection();
InputStream is = ucon.getInputStream();
BufferedInputStream bis = new BufferedInputStream(is);
ByteArrayBuffer baf = new ByteArrayBuffer(50);
int current = 0;
while ((current = bis.read()) != -1) {
baf.append((byte) current);
}
/*saving the file in the sdcard
*/
String FileName = deviceId.trim()+".jpg";
String path = Environment.getExternalStorageDirectory().toString()+"/school/snaps/"+FileName;;
FileOutputStream fos = new FileOutputStream(path);
fos.write(baf.toByteArray());
fos.close();
}catch(Exception e){
Log.e(Tag,""+e);
}
}
}catch(Exception e){
Log.e(Tag,""+e);
}
}
@Override
protected void onPostExecute(String result) {
try {
qvsEngine.database.RunQuery("insert into webcam values (null,'"+FileName+"','0')");
Log.e(Tag,"webcame table has : "+ qvsEngine.RunQuery("select count(imgid) from webcam where path ='"+FileName+"'") );
}catch(Exception e){
Log.e(Tag,""+e);
}
new DownloadSavePics(context,url1,deviceId).execute();
}
}