在后台上传文件到服务器

时间:2014-04-25 00:50:13

标签: android video service upload progress-bar

我正在开发一个应用程序,允许用户将媒体文件(如图像,照片,视频)上传到服务器,我对大文件有点问题 - 等待和查看进度条太长在上传和其他问题的活动 - 如果应用程序死亡上传死亡,所以我需要将我的上传代码转移到服务。所以我的麻烦就开始了 - 如果我将上传代码转移到服务器,我如何将进度更新(%)发送给活动?

这是我上传方法的代码:

public static void uploadMovie(final HashMap<String, String> dataSource, final OnResponseListener finishedListener, final ProgressListener progressListener) {
    if (finishedListener != null) {
        new Thread(new Runnable() {
            public void run() {
                try {

                    //Prepare data-->

                    String boundary = getMD5(dataSource.size() + String.valueOf(System.currentTimeMillis()));
                    MultipartEntityBuilder multipartEntity = MultipartEntityBuilder.create();
                    multipartEntity.setMode(HttpMultipartMode.BROWSER_COMPATIBLE);
                    multipartEntity.setCharset(Charset.forName("UTF-8"));
                    for (String key : dataSource.keySet()) {
                        if (key.equals(MoviesFragmentAdd.USERFILE)) {
                            FileBody userFile = new FileBody(new File(dataSource.get(key)));
                            multipartEntity.addPart(key, userFile);
                            continue;
                        }
                        multipartEntity.addPart(key, new StringBody(dataSource.get(key), ContentType.APPLICATION_JSON));
                    }
                    HttpEntity entity = multipartEntity.build();
                    //<--

                    //Prepare Connection-->

                    trustAllHosts();
                    HttpsURLConnection conn = (HttpsURLConnection) new URL(SAKH_URL_API + "/video/addForm/").openConnection();
                    conn.setUseCaches(false);
                    conn.setDoOutput(true);
                    conn.setDoInput(true);
                    conn.setRequestMethod("POST");
                    conn.setRequestProperty("Accept-Charset", "UTF-8");
                    conn.setRequestProperty("Content-Type", "multipart/form-data;boundary=" + boundary);
                    conn.setRequestProperty("Content-length", entity.getContentLength() + "");
                    conn.setRequestProperty(entity.getContentType().getName(), entity.getContentType().getValue());
                    conn.connect();


                    //<--
                    // Upload-->


                    OutputStream os = conn.getOutputStream();
                    ByteArrayOutputStream baos = new ByteArrayOutputStream();
                    entity.writeTo(baos);
                    baos.close();
                    byte[] payload = baos.toByteArray();
                    baos = null;
                    int totalSize = payload.length;
                    int bytesTransferred = 0;
                    int chunkSize = 2000;

                    while (bytesTransferred < totalSize) {
                        int nextChunkSize = totalSize - bytesTransferred;
                        if (nextChunkSize > chunkSize) {
                            nextChunkSize = chunkSize;
                        }
                        os.write(payload, bytesTransferred, nextChunkSize);
                        bytesTransferred += nextChunkSize;

                        //Progress update-->
                        if (progressListener != null) {
                            progressListener.onProgressUpdate((100 * bytesTransferred / totalSize));
                        }
                        //<--

                    }

                    os.flush();

                    //<--
                    //Get server response-->
                    int status = conn.getResponseCode();
                    if (conn.getResponseCode() == HttpsURLConnection.HTTP_OK) {

                        BufferedReader in = new BufferedReader(new InputStreamReader(conn.getInputStream()));
                        JsonObject request = (JsonObject) gparser.parse(in.readLine());

                        if (!request.get("error").getAsBoolean()) {
                            finishedListener.onLoadFinished(new Object());
                        }
                    } else {
                        throw new IOException("Server returned non-OK status: " + status);
                    }

                    conn.disconnect();
                } catch (Exception e) {
                    e.printStackTrace();
                    finishedListener.onNotConnected();

                }
            }
        }).start();

    }
}   

2 个答案:

答案 0 :(得分:1)

1 - 创建可绑定服务并实现必要的Binder

在绑定之前启动您的服务,或者在其他情况下,如果您的应用已关闭,服务也将关闭

2 - 在您的服务上公开StartDownload(url,IUpdateTarget)等公共功能。

3 - 使用类似UpdateProgress(somevalues)的函数创建一个接口(IUpdateTarget);

4 - 在View中实现IUpdateTarget接口,该接口应该接收更新通知

5 - 绑定到服务并检索正在运行的服务的实例

6 - 现在您有了服务实例,请调用StartDownload传递URL和目标视图以进行通知。

7 - 每当您必须从传递给服务的IUpdateProgress实例(目标视图)的服务调用UpdateProgress更新接口时。

请注意跨线程调用,请记住必须始终更新主线程上的接口。

答案 1 :(得分:1)

使用处理程序发送进程

new Thread(new Runnable() {

    @Override
    public void run() {
        // TODO Auto-generated method stub
        android.os.Message msg = new android.os.Message();
        Bundle bundle = new Bundle();
        bundle.putInt("process", process);
        msg.setData(bundle);
        mHandler.sendMessage(msg);
    }
}).start();

Handler mHandler = new Handler() {
    public void handleMessage(android.os.Message msg) {
        int process = msg.getData().getInt("process");
    };
};