Android upload file to server with progressbar using service

后端 未结 2 1583
攒了一身酷
攒了一身酷 2021-01-17 01:31

I have already implement upload file with progress bar using asynctask but large files or uploading multiple files hang up my activity now i want to do the same but using se

相关标签:
2条回答
  • 2021-01-17 02:08

    Hey i finally did it here is the code

    public class UploadFile extends Service {
    
        NotificationManager mNotifyManager;
        NotificationCompat.Builder mBuilder;
        private static final String TAG = "HelloService";
    
        private boolean isRunning  = false;
    
        @Override
        public void onCreate() {
            Log.i(TAG, "Service onCreate");
    
            isRunning = true;
        }
    
        @Override
        public int onStartCommand(Intent intent, int flags, int startId) {
            mNotifyManager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
            mBuilder = new NotificationCompat.Builder(UploadFile.this);
            mBuilder.setContentTitle("File uploaded").setSmallIcon(
                    R.drawable.myicons);
            UpadtePost();
            return Service.START_STICKY;
        }
        private void UpadtePost() {
    
            new UploadFileToServer().execute();
        }
        private class UploadFileToServer extends AsyncTask<Void, Integer, String> {
    
            protected void onPreExecute() {
                // setting progress bar to zero
                mBuilder.setProgress(100, 0, false);
                mNotifyManager.notify(0, mBuilder.build());
                super.onPreExecute();
            }
    
            @Override
            protected void onProgressUpdate(Integer... progress) {
                mBuilder.setProgress(100,
                        Integer.parseInt(String.valueOf(progress[0])), false);
                mNotifyManager.notify(0, mBuilder.build());
            }
    
            @Override
            protected String doInBackground(Void... params) {
                return uploadFile();
            }
    
            private String uploadFile() {
                String responseString = null;
    
                HttpClient httpclient = new DefaultHttpClient();
                HttpPost httppost = new HttpPost(****);
    
                try {
                    AndroidMultiPartEntity entity = new AndroidMultiPartEntity(
                            new AndroidMultiPartEntity.ProgressListener() {
                                public void transferred(long num) {
                                    publishProgress((int) ((num / (float) totalSize) * 100));
                                }
                            });
    
                    File sourceFile = new File(orignal1);
                    entity.addPart("image", new FileBody(sourceFile));
                    totalSize = entity.getContentLength();
                    httppost.setEntity(entity);
    
                    // Making server call
                    HttpResponse response = httpclient.execute(httppost);
                    HttpEntity r_entity = response.getEntity();
    
                    int statusCode = response.getStatusLine().getStatusCode();
                    if (statusCode == 200) {
                        // Server response
                        responseString = EntityUtils.toString(r_entity);
                    } else {
                        responseString = "Error occurred! Http Status Code: "
                                + statusCode;
                    }
    
                } catch (ClientProtocolException e) {
                    responseString = e.toString();
                } catch (IOException e) {
                    responseString = e.toString();
    
    
                }
                return responseString;
    
            }
    
            @Override
            protected void onPostExecute(String result) {
                    session.showNot(result);
                    mBuilder.setContentText("Upload complete").setProgress(0, 0,false);
                    mNotifyManager.notify(6532365, mBuilder.build());
                    mNotifyManager.cancel(6532365);
                super.onPostExecute(result);
            }
        }
        @Override
        public IBinder onBind(Intent arg0) {
            Log.i(TAG, "Service onBind");
            return null;
        }
    
        @Override
        public void onDestroy() {
    
            isRunning = false;
    
            Log.i(TAG, "Service onDestroy");
        }
    }
    

    AndroidMultiPartEntity .java

    public class AndroidMultiPartEntity extends MultipartEntity
    
    {
    
        private final ProgressListener listener;
    
        public AndroidMultiPartEntity(final ProgressListener listener) {
            super();
            this.listener = listener;
        }
    
        public AndroidMultiPartEntity(final HttpMultipartMode mode,
                                      final ProgressListener listener) {
            super(mode);
            this.listener = listener;
        }
    
        public AndroidMultiPartEntity(HttpMultipartMode mode, final String boundary,
                                      final Charset charset, final ProgressListener listener) {
            super(mode, boundary, charset);
            this.listener = listener;
        }
    
        @Override
        public void writeTo(final OutputStream outstream) throws IOException {
            super.writeTo(new CountingOutputStream(outstream, this.listener));
        }
    
        public static interface ProgressListener {
            void transferred(long num);
        }
    
        public static class CountingOutputStream extends FilterOutputStream {
    
            private final ProgressListener listener;
            private long transferred;
    
            public CountingOutputStream(final OutputStream out,
                                        final ProgressListener listener) {
                super(out);
                this.listener = listener;
                this.transferred = 0;
            }
    
            public void write(byte[] b, int off, int len) throws IOException {
                out.write(b, off, len);
                this.transferred += len;
                this.listener.transferred(this.transferred);
            }
    
            public void write(int b) throws IOException {
                out.write(b);
                this.transferred++;
                this.listener.transferred(this.transferred);
            }
        }
    
    0 讨论(0)
  • 2021-01-17 02:31

    Use this Library

    https://github.com/gotev/android-upload-service

    With this service you can show current progress and it will run in background which will help you maintain the performance of your application.

    0 讨论(0)
提交回复
热议问题