更新百分比到reclyerview

时间:2016-11-17 14:09:30

标签: android retrofit2 intentservice

我正在使用XMPP(SAMCK)开发聊天应用程序。我使用reclycerview显示了对话。我想在图像上传到服务器时显示百分比(使用rest api)。所以我使用了intentservice并通过localbroastreceiver更新百分比。但我无法滚动reclycerview。我也无法显示图像的百分比。

        Please give comments.    

        ProgressRequestBody.java   
      To get percentage I have used this class.





     public class ProgressRequestBody extends RequestBody {
            private File mFile;
            private String mPath;
            private String stanzaId;
            private UploadCallbacks mListener;

            private static final int DEFAULT_BUFFER_SIZE = 2048;

            public interface UploadCallbacks {
                void onProgressUpdate(int percentage,String StandzId);
                void onError();
                void onFinish();
            }

            public ProgressRequestBody(final File file, String stanzaID, final UploadCallbacks listener) {
                mFile = file;
                mListener = listener;
                this.stanzaId=stanzaID;
            }

            @Override
            public MediaType contentType() {
                // i want to upload only images
                return MediaType.parse("image/*");
            }

            @Override
            public long contentLength() throws IOException {
              return mFile.length();
            }

            @Override
            public void writeTo(BufferedSink sink) throws IOException {
                long fileLength = mFile.length();
                byte[] buffer = new byte[DEFAULT_BUFFER_SIZE];
                FileInputStream in = new FileInputStream(mFile);
                long uploaded = 0;

                try {
                    int read;
                    Handler handler = new Handler(Looper.getMainLooper());
                    while ((read = in.read(buffer)) != -1) {

                        // update progress on UI thread
                        handler.post(new ProgressUpdater(uploaded, fileLength,stanzaId));

                        uploaded += read;
                        sink.write(buffer, 0, read);
                    }
                } finally {
                    in.close();
                }
            }

            private class ProgressUpdater implements Runnable {
                private long mUploaded;
                private String mStandzId;
                private long mTotal;
                public ProgressUpdater(long uploaded, long total,String standzId) {
                    mUploaded = uploaded;
                    mTotal = total;
                    mStandzId=standzId;
                }



                @Override
                public void run() {
                    mListener.onProgressUpdate((int)(100 * mUploaded / mTotal),mStandzId);
                }
            }
        }


        updateservice.class
      This is used to call api in background.

        public class UploadService extends IntentService implements ProgressRequestBody.UploadCallbacks {
                // TODO: Rename actions, choose action names  that describe tasks that this
                // IntentService can perform, e.g. ACTION_FETCH_NEW_ITEMS
                private static final String ACTION_FOO = "com.techno.chat_sdk.utilz.action.FOO";
                private static final String ACTION_BAZ = "com.techno.chat_sdk.utilz.action.BAZ";

                // TODO: Rename parameters
                private static final String EXTRA_PARAM1 = "com.techno.chat_sdk.utilz.extra.PARAM1";
                private static final String EXTRA_PARAM2 = "com.techno.chat_sdk.utilz.extra.PARAM2";

                public UploadService() {
                    super("UploadService");
                }

                /**
                 * Starts this service to perform action Foo with the given parameters. If
                 * the service is already performing a task this action will be queued.
                 *
                 * @see IntentService
                 */
                // TODO: Customize helper method
                public static void startActionFoo(Context context, String param1, String param2) {
                    Intent intent = new Intent(context, UploadService.class);
                    intent.setAction(ACTION_FOO);
                    intent.putExtra(EXTRA_PARAM1, param1);
                    intent.putExtra(EXTRA_PARAM2, param2);
                    context.startService(intent);
                }

                /**
                 * Starts this service to perform action Baz with the given parameters. If
                 * the service is already performing a task this action will be queued.
                 *
                 * @see IntentService
                 */
                // TODO: Customize helper method
                public static void startActionBaz(Context context, String param1, String param2) {
                    Intent intent = new Intent(context, UploadService.class);
                    intent.setAction(ACTION_BAZ);
                    intent.putExtra(EXTRA_PARAM1, param1);
                    intent.putExtra(EXTRA_PARAM2, param2);
                    context.startService(intent);
                }

                @Override
                protected void onHandleIntent(Intent intent) {
                    if (intent != null) {
                        /*final String action = intent.getAction();
                        if (ACTION_FOO.equals(action)) {
                            final String param1 = intent.getStringExtra(EXTRA_PARAM1);
                            final String param2 = intent.getStringExtra(EXTRA_PARAM2);
                            handleActionFoo(param1, param2);
                        } else if (ACTION_BAZ.equals(action)) {
                            final String param1 = intent.getStringExtra(EXTRA_PARAM1);
                            final String param2 = intent.getStringExtra(EXTRA_PARAM2);
                            handleActionBaz(param1, param2);
                        }*/
                        Download Download = intent.getParcelableExtra("Download");
                           File file=new File(Download.getDestinationpath());
                        ProgressRequestBody fileBody = new ProgressRequestBody(file,Download.getStandzId(), UploadService.this);
                        MultipartBody.Part filePart = MultipartBody.Part.createFormData("file", file.getName(), fileBody);
                        FileUpandDown mEdit = ApiConfiguration.getInstance().getApiBuilder().create(FileUpandDown.class);

                        final Call<JsonObject> request = mEdit.Fileupload(filePart);
                        request.enqueue(new Callback<JsonObject>() {
                            @Override
                            public void onResponse(Call<JsonObject> call, Response<JsonObject> response) {
                                if(response.body()!=null){
                                    String url=response.body().get("file_url").getAsString();
                                    if(url!=null){
                                        if (Commonclass.isNetworkConnected(UploadService.this)){
                                            /*json.items.get(0).url=url;  // update url to json.
                                            json.items.set(0,items);

                                            duce_Xmppservice.sendMessage(juid, gson.toJson(json), message, false);*/}
                                    }

                                }



                            }

                            @Override
                            public void onFailure(Call<JsonObject> call, Throwable t) {
                                System.out.println("Failure" + t.toString());
                            }
                        });

                    }
                }

                /**
                 * Handle action Foo in the provided background thread with the provided
                 * parameters.
                 */
                private void handleActionFoo(String param1, String param2) {
                    // TODO: Handle action Foo
                    throw new UnsupportedOperationException("Not yet implemented");
                }

                /**
                 * Handle action Baz in the provided background thread with the provided
                 * parameters.
                 */
                private void handleActionBaz(String param1, String param2) {
                    // TODO: Handle action Baz
                    throw new UnsupportedOperationException("Not yet implemented");
                }

                @Override
                public void onProgressUpdate(int percentage, String StandzId) {
                    ContentValues values = new ContentValues();
                    values.put(DataHelper.CHAT_Msg_DownOrUpPercentage, percentage);
                    MyApplication.writable.update(DataHelper.CHAT_TABLE_NAME, values, DataHelper.CHAT_Msg_StanzaId + " = ?",
                            new String[]{StandzId});
                    Intent intent = new Intent(Constants.ProgreessUpdate);
                    LocalBroadcastManager.getInstance(MyApplication.getAppContext()).sendBroadcast(intent);
                }

                @Override
                public void onError() {

                }

                @Override
                public void onFinish() {

                }
            }

            singlechatActivity.java  (udpate data to list from ocalbroastreceiver)



            for(ChatMessages chatMess: section.chatMessages){
                           if(chatMess.StanzaId.equals(StandzId)){
                               chatMess.DownUpPercentage=percentage;
                               section.chatMessages.set(i,chatMess);
                               strickyAdapter.notifySectionItemChanged(j,i);
                            }
                           i++;
                       }


            //StrickyAdapter
             switch (jsonMaking.Messagetype){
                        case "text":
                            ivh.outgoing_msg.setText(jsonMaking.items.get(0).Body);
                            ivh.outgoing_Time.setText(Commonclass.GetTime(chat.dateTime));

                            //set tick status for txt
                            if(chat.offlinestatus==1){
                                ivh.tick_status.setImageResource(R.drawable.offlinestatus);
                            }else if(chat.Deliverystatus==1){
                                ivh.tick_status.setImageResource(R.drawable.doubletick);
                            }else {
                                ivh.tick_status.setImageResource(R.drawable.singletick);
                            }
                            if(chat.Readstatus==1){
                                ivh.tick_status.setImageResource(R.drawable.colortick);
                            }


                            break;

                        case "Image":
                            //set Imagecmd
                            if(!Commonclass.isEmptyString(jsonMaking.items.get(0).ImagecmdTxt))
                                ivh.out_ImagecmdTxt.setText(jsonMaking.items.get(0).ImagecmdTxt);
                            else
                                ivh.out_ImagecmdTxt.setVisibility(View.GONE);

                            //set Image
                            if(!Commonclass.isEmptyString(jsonMaking.items.get(0).Base64)){
                                ivh.Outgoing_Image.setImageBitmap(Commonclass.decodeBase64(jsonMaking.items.get(0).Base64));

                                /*File file = new File(jsonMaking.items.get(0).localurl);
                                if(file.exists()){
                                    Bitmap myBitmap = BitmapFactory.decodeFile(file.getAbsolutePath());
                                    ivh.Outgoing_Image.setImageBitmap(myBitmap);
                                }*/
                            }

                            //set Image time
                            ivh.outgoing_Image_Time.setText(Commonclass.GetTime(chat.dateTime));

                            //set tick status Image
                            if(chat.offlinestatus==1){
                                ivh.Image_tick_status.setImageResource(R.drawable.offlinestatus);
                            }else if(chat.Deliverystatus==1){
                                ivh.Image_tick_status.setImageResource(R.drawable.doubletick);
                            }else {
                                ivh.Image_tick_status.setImageResource(R.drawable.singletick);
                            }
                            if(chat.Readstatus==1){
                                ivh.Image_tick_status.setImageResource(R.drawable.colortick);
                            }


  //set uploading percentage

                            context.runOnUiThread(new Runnable() {
                                @Override
                                public void run() {
                                    if(chat.DownUpPercentage!=0&&chat.DownUpPercentage<90){
                                        ivh.outgoing_circle_progress.setVisibility(View.VISIBLE);
                                        ivh.outgoing_circle_progress.setProgress(chat.DownUpPercentage);
                                    }else {
                                        ivh.outgoing_circle_progress.setVisibility(View.GONE);
                                    }
                                }
                            });


                            break;

                    }

0 个答案:

没有答案