我已经使用了Asyntask,我正在尝试下载图像并将其保存到手机的SD卡中。 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();
}
}
答案 0 :(得分:2)
是的,您将获得“应用程序无响应”,因为
你正在打电话 new DownloadSavePics(context,url1,deviceId).execute();
在onPostExecute
中,所以它会再次执行DownloadSavePics
,当到达onPostExecute时,它会再次接到一个电话....所以没有结束。
连续通话DownlaodSavePics
来电ANR
答案 1 :(得分:0)
尝试通过runOnUIThread()从Runnable执行新实例。如果它没有帮助,请发布日志。
这是一个想法:也许你的任务 无法 来下载数据(例如WiFi已经腐烂),而然后你生成无限循环即时执行任务。尝试添加sleep(500)(在工作线程中)并查看是否有帮助。