0

我想像队列一样一一上传文件。简而言之,假设有 10 个文件,我想上传所有文件,它应该检查网络连接是否可用,如果没有,那么这些文件应该进入队列并稍后尝试上传。它将继续尝试直到左队列中的任何单个文件。请帮帮我,我怎样才能在android中实现这一点。

这是我到目前为止尝试过的示例代码

final Thread thread = new Thread(){
        public void run() {
            try {
                while(true){
                    ThisCaching ic = new ThisCaching(getApplicationContext());
                    fileToUpload = ic.getDataFromCache("audiofiles", "SELECT * FROM audiofiles WHERE STATUS = '2' OR STATUS = '3' ORDER BY rowid DESC");
                    if(fileToUpload != null)
                    {
                        for (int i=0; i<fileToUpload.size(); i++) {
                            try {
                                System.out.println("Current position while uploading ::> " + i);
                                Thread.sleep(1000);
                                ConstantData.selectedFile = fileToUpload.get(i).toString();
                                ConstantData.position = i;
                                if(checkConnectivity()){
                                    new Uploading().execute();
                                    myApplication.getHttpClient().getConnectionManager().closeExpiredConnections();
                                }else{
                                    String[] status = {"STATUS"};
                                    String[] val = {"2"};
                                    try {
                                        SQLiteDatabase sd = ThisDataHelper.getInstance(getApplicationContext()).getDB();
                                        new ThisTable(sd, "audiofiles").updateRow(status,val, "FILENAME = " + "'"+ConstantData.selectedFile+"'");
                                    } catch (Exception e1) {
                                        e1.printStackTrace();
                                    }
                                }
                            } catch (Exception e) {
                                return;
                            }            
                        }
                    }
                }
            } catch (Exception e) {
                e.printStackTrace();
                return;
            }            
        }
    };


        String line = null;
        HttpClient httpClient = null;
        HttpContext localContext = null;
        HttpPost httpPost = null;
        MultipartEntity entity = null;
        HttpResponse response = null;
        HttpEntity httpEntity =null;
        SQLiteDatabase sd = ThisDataHelper.getInstance(getApplicationContext()).getDB();
        try {
            String strArray[]={"http://myurl.com","filename",ConstantData.selectedFile,"activityType",ConstantData.activityType,"patientId",ConstantData.patientId,"caseId",ConstantData.caseId,"doctorId",ConstantData.doctorId,"clinicCode",ConstantData.clinicCode,"documentType",ConstantData.documentType,"templateId",ConstantData.templateId};
            httpClient = new DefaultHttpClient();
            //httpClient.getConnectionManager().r
            localContext = new BasicHttpContext();
            httpPost = new HttpPost(strArray[0]);
            entity = new MultipartEntity(HttpMultipartMode.BROWSER_COMPATIBLE);
            File file = new File(ConstantData.selectedFile);
            String type = file.getAbsolutePath().substring(file.getAbsolutePath().lastIndexOf(".")+1);
            if(strArray.length>1)
            {
                for(int i=1;i<strArray.length;i=i+2)
                {
                    if(strArray[i]!=null){
                        if(!strArray[i].equalsIgnoreCase("")){
                            //                              System.out.println("i) : "+i +"  i+1) : "+(i+1));
                            Log.i(strArray[i], "::" + strArray[i+1]);
                            if(strArray[i].equalsIgnoreCase("filename")){
                                entity.addPart("filename", new FileBody(file,"audio/"+type));
                            }else{
                                entity.addPart(strArray[i], new StringBody(strArray[i+1]));
                            }
                        }
                    }
                }
            }
            httpPost.setEntity(entity);
            response = httpClient.execute(httpPost,localContext);// i m getting error at this line

            System.out.println("Response code is ::> " +response.getStatusLine().getStatusCode());
            code = response.getStatusLine().getStatusCode();
            httpEntity = response.getEntity();
            line = EntityUtils.toString(httpEntity, HTTP.UTF_8);
        } catch (UnsupportedEncodingException e) {
            code=100;
            e.printStackTrace();
            line = "<results status=\"error\"><msg>Can't connect to server</msg></results>";
            ConstantData.uploaded = false;
            String[] status = {"STATUS"};
            String[] val = {"3"};
            try {
                new ThisTable(sd, "audiofiles").updateRow(status,val, "FILENAME = " + "'"+ConstantData.selectedFile+"'");
            } catch (Exception e1) {
                e1.printStackTrace();
            }
        } catch (MalformedURLException e) {
            code=100;
            e.printStackTrace();
            line = "<results status=\"error\"><msg>Can't connect to server</msg></results>";
            ConstantData.uploaded = false;
            String[] status = {"STATUS"};
            String[] val = {"3"};
            try {
                new ThisTable(sd, "audiofiles").updateRow(status,val, "FILENAME = " + "'"+ConstantData.selectedFile+"'");
            } catch (Exception e1) {
                e1.printStackTrace();
            }
        } catch (IOException e) {
            code=100;
            e.printStackTrace();
            line = "<results status=\"error\"><msg>Can't connect to server</msg></results>";
            ConstantData.uploaded = false;
            String[] status = {"STATUS"};
            String[] val = {"3"};
            try {
                new ThisTable(sd, "audiofiles").updateRow(status,val, "FILENAME = " + "'"+ConstantData.selectedFile+"'");
            } catch (Exception e1) {
                e1.printStackTrace();
            }
        } catch (Exception e) {
            code=100;
            e.printStackTrace();
            ConstantData.uploaded = false;
            String[] status = {"STATUS"};
            String[] val = {"3"};
            try {
                new ThisTable(sd, "audiofiles").updateRow(status,val, "FILENAME = " + "'"+ConstantData.selectedFile+"'");
            } catch (Exception e1) {
                e1.printStackTrace();
            }
        }finally{
//  


try {
//                   System.out.println("&&&& while realeasing connection");
////                     if(httpClient != null){
////                         httpClient.getConnectionManager().releaseConnection((ManagedClientConnection) httpClient.getConnectionManager(), -1, TimeUnit.MINUTES);
////                     }
//                   if(httpPost.getEntity().getContent() != null){
//                       InputStream content = httpPost.getEntity().getContent();
//                       content.close(); 
//                   }
//              } catch (Exception e) {
//                  e.printStackTrace();
//              }
            }

            return line;


`
4

1 回答 1

0

据我所知,您是否使用普通线程(还看不到编辑)。从 Java 1.5 开始,有一个用于队列和多线程之类的包,这让生活变得更加容易。

出于队列的目的,您可以使用Executors.newSingleThreadExecutor(). 您将获得一个只有一个线程的 Threadpool,该线程submit(Runnable)按照您提交的顺序执行您的每项任务。Java 保证,Executor 总是有一个线程在队列上工作(如果线程死亡,Java 会自动重新创建线程)

您提交的每个任务都实现了一个Runnable. 因此,要实现您描述的三个重试,您只需要一个实现Runnable接口的类,该类对重试进行计数,并且 - 如果上传不成功 - 它会增加计数器并重新提交自身。

这是Executors 和 ExecutorService的指南教程参考。

于 2013-10-03T10:58:26.277 回答