Android实现聊天记录上传本地服务器(即时通讯)
即时通讯功能,使用SDK里封装的方法,获取聊天记录,接口请求成功,但获取不到数据。使用本地的服务器保存聊天记录,实现方法如下:
1.ChatFragment.java中请求聊天记录:
publicclassChatFragmentextendsEaseChatFragmentimplementsEaseChatFragmentHelper{ @Override protectedvoidsetUpView(){ setChatFragmentHelper(this); StringuserName=DemoHelper.getInstance().getCurrentUsernName(); conversation=EMClient.getInstance().chatManager().getConversation(toChatUsername,EaseCommonUtils.getConversationType(chatType),true); Log.e(TAG,"conversation.getAllMsgCount()="+conversation.getAllMsgCount()); if(conversation.getAllMsgCount()!=0&&conversation.getAllMsgCount()!=1){ setLisener(); }else{ conversation.clearAllMessages(); conversation.clear(); showWaitDialog("数据加载中……").show(); getHistoryMsg(userName,toChatUsername); } } privatevoidsetLisener(){ if(chatType==Constant.CHATTYPE_SINGLE){ MaprobotMap=DemoHelper.getInstance().getRobotList(); if(robotMap!=null&&robotMap.containsKey(toChatUsername)){ isRobot=true; } } super.setUpView(); …… setOnRefresh1Listener(newOnRefresh1Listener(){ @Override publicbooleanrefresh(intpage){ pageNo=page; getHistoryMsg(DemoHelper.getInstance().getCurrentUsernName(),toChatUsername); returnfalse; } }); } List emMessages=newArrayList<>(); List remoteMessages=newArrayList<>(); intpageNo=1; privatevoidgetHistoryMsg(StringsendUser,StringreceiveUser){ HashMap baseParam=newHashMap<>(4); baseParam.put("pageNo",pageNo); baseParam.put("pageSize",10); if(chatType==EaseConstant.CHATTYPE_GROUP){ baseParam.put("sendUser",receiveUser); baseParam.put("receiveUser",receiveUser); }else{ baseParam.put("sendUser",sendUser); baseParam.put("receiveUser",receiveUser); } OkHttpUtil.post(TAG,WebApi.MSN_CHAT_LIST,baseParam,newStringCallback(){ @Override publicvoidonError(Callcall,Exceptione,intid){ Log.e(TAG,"getHistoryMsge="+e); } @Override publicvoidonResponse(Stringresponse,intid){ Log.e(TAG,"getHistoryMsgresponse="+response); try{ JSONObjectobject=newJSONObject(response); if(object.getInt("code")==200){ JSONObjectobject1=object.getJSONObject("data"); Gsongson=newGson(); if(pageNo==1){ remoteMessages.clear(); } ListPageBeanlistPageBean=gson.fromJson(object1.toString(),ListPageBean.class); if(listPageBean.isLastPage()){ isLastPage=true; }else{ isLastPage=false; } JSONArrayarray=object1.getJSONArray("list"); for(inti=0;i (){ @Override protectedVoiddoInBackground(Void...params){ downLoad(message,type,path,fileName); returnnull; } @Override protectedvoidonPostExecute(Voidresult){ super.onPostExecute(result); Log.e(TAG,"getFile"+result); } }.execute(); } /* *将数据导入数据库 **/ privatevoidimportDataBase(List messages){ newAsyncTask (){ @Override protectedVoiddoInBackground(Void...params){ EMClient.getInstance().chatManager().importMessages(emMessages); returnnull; } @Override protectedvoidonPostExecute(Voidresult){ super.onPostExecute(result); handler.postDelayed(newRunnable(){ @Override publicvoidrun(){ setLisener(); hideWaitDialog(); } },3000); Log.e(TAG,"importMessages"+result); } }.execute(); } /* *附加功能,语音电话和视频电话 *增加了发送企业名片的功能 **/ @Override protectedvoidregisterExtendMenuItem(){ //usethemenuinbaseclass super.registerExtendMenuItem(); //extendmenuitems inputMenu.registerExtendMenuItem(R.string.attach_video,R.drawable.em_chat_video_selector,ITEM_VIDEO,extendMenuItemClickListener); inputMenu.registerExtendMenuItem(R.string.attach_file,R.drawable.em_chat_file_selector,ITEM_FILE,extendMenuItemClickListener); if(chatType==Constant.CHATTYPE_SINGLE){ inputMenu.registerExtendMenuItem(R.string.attach_voice_call,R.drawable.em_chat_voice_call_selector,ITEM_VOICE_CALL,extendMenuItemClickListener); inputMenu.registerExtendMenuItem(R.string.attach_video_call,R.drawable.em_chat_video_call_selector,ITEM_VIDEO_CALL,extendMenuItemClickListener); inputMenu.registerExtendMenuItem("企业名片",R.drawable.em_chat_video_call_selector,ITEM_OFFICE_CARD,extendMenuItemClickListener); }elseif(chatType==Constant.CHATTYPE_GROUP){//音视频会议 inputMenu.registerExtendMenuItem(R.string.voice_and_video_conference,R.drawable.em_chat_video_call_selector,ITEM_CONFERENCE_CALL,extendMenuItemClickListener); //inputMenu.registerExtendMenuItem(R.string.title_live,R.drawable.em_chat_video_call_selector,ITEM_LIVE,extendMenuItemClickListener); } } /* *点击附加功能 * **/ @Override publicbooleanonExtendMenuItemClick(intitemId,Viewview){ switch(itemId){ caseITEM_VIDEO: Log.e(TAG,"onExtendMenuItemClickITEM_VIDEO"); Intentintent=newIntent(getActivity(),ImageGridActivity.class); startActivityForResult(intent,REQUEST_CODE_SELECT_VIDEO); break; …… caseITEM_OFFICE_CARD: Log.e(TAG,"onExtendMenuItemClickITEM_OFFICE_CARD"); startOfficeCard(); break; default: break; } //keepexistextendmenu returnfalse; } /* *获取企业详情 *增加了发送企业名片的功能 **/ privatevoidstartOfficeCard(){ HashMap baseParam=WebFrontUtil.getBaseParam(); baseParam.put("id",SavePreferences.getString(Const.OFFICE_ID)); OkHttpUtil.post(TAG,WebApi.PUNISH_OFFICE_DETAIL,baseParam,newStringCallback(){ @Override publicvoidonError(Callcall,Exceptione,intid){ Log.e(TAG,"startOfficeCarde="+e); } @Override publicvoidonResponse(Stringresponse,intid){ Log.e(TAG,"startOfficeCardresponse="+response); try{ JSONObjectobject=newJSONObject(response); Gsongson=newGson(); if((int)object.get("code")==200){ JSONObjectobject1=object.getJSONObject("data"); OfficeBeanofficeBean=gson.fromJson(object1.toString(),OfficeBean.class); Stringcontent="officeId:"+officeBean.getId()+",公司名称:"+officeBean.getName()+",地址:"+officeBean.getAddr()+",联系电话:"+officeBean.getOfficeTel(); EMMessagemessage=EMMessage.createTxtSendMessage(content,toChatUsername); message.setAttribute("is_office",true); sendMessage(message); } }catch(JSONExceptione){ e.printStackTrace(); } } }); } /** *chatrowprovider *发送企业名片时,修改过此处,否则还是文本格式 * */ privatefinalclassCustomChatRowProviderimplementsEaseCustomChatRowProvider{ @Override publicintgetCustomChatRowTypeCount(){ //herethenumberisthemessagetypeinEMMessage::Type //whichisusedtocountthenumberofdifferentchatrow return14; } @Override publicintgetCustomChatRowType(EMMessagemessage){ if(message.getType()==EMMessage.Type.TXT){ //voicecall if(message.getBooleanAttribute(Constant.MESSAGE_ATTR_IS_VOICE_CALL,false)){ returnmessage.direct()==EMMessage.Direct.RECEIVE?MESSAGE_TYPE_RECV_VOICE_CALL:MESSAGE_TYPE_SENT_VOICE_CALL; }elseif(message.getBooleanAttribute(Constant.MESSAGE_ATTR_IS_VIDEO_CALL,false)){ //videocall returnmessage.direct()==EMMessage.Direct.RECEIVE?MESSAGE_TYPE_RECV_VIDEO_CALL:MESSAGE_TYPE_SENT_VIDEO_CALL; } //messageerecall elseif(message.getBooleanAttribute(Constant.MESSAGE_TYPE_RECALL,false)){ returnMESSAGE_TYPE_RECALL; }elseif(!"".equals(message.getStringAttribute(Constant.MSG_ATTR_CONF_ID,""))){ returnMESSAGE_TYPE_CONFERENCE_INVITE; }elseif(Constant.OP_INVITE.equals(message.getStringAttribute(Constant.EM_CONFERENCE_OP,""))){ returnMESSAGE_TYPE_LIVE_INVITE; }elseif(message.getBooleanAttribute("is_office",false)){ returnmessage.direct()==EMMessage.Direct.RECEIVE?MESSAGE_TYPE_RECV_CARD:MESSAGE_TYPE_SEND_CARD; } } return0; } @Override @Override publicEaseChatRowPresentergetCustomChatRow(EMMessagemessage,intposition,BaseAdapteradapter){ if(message.getType()==EMMessage.Type.TXT){ //voicecallorvideocall if(message.getBooleanAttribute(Constant.MESSAGE_ATTR_IS_VOICE_CALL,false)|| message.getBooleanAttribute(Constant.MESSAGE_ATTR_IS_VIDEO_CALL,false)){ EaseChatRowPresenterpresenter=newEaseChatVoiceCallPresenter(); returnpresenter; } if(message.getBooleanAttribute("is_office",false)){ Log.e(TAG,"getCustomChatRowis_office"); EaseChatRowPresenterpresenter=newEaseChatCardPresenter(); returnpresenter; } //recallmessage elseif(message.getBooleanAttribute(Constant.MESSAGE_TYPE_RECALL,false)){ EaseChatRowPresenterpresenter=newEaseChatRecallPresenter(); returnpresenter; }elseif(!"".equals(message.getStringAttribute(Constant.MSG_ATTR_CONF_ID,""))){ returnnewChatRowConferenceInvitePresenter(); }elseif(Constant.OP_INVITE.equals(message.getStringAttribute(Constant.EM_CONFERENCE_OP,""))){ returnnewChatRowLivePresenter(); } } returnnull; } } privateDialogmWaitDialog; publicDialogshowWaitDialog(Stringtext){ if(mWaitDialog==null){ mWaitDialog=DialogManager.getWaitDialog(getActivity(),text); } if(mWaitDialog!=null){ TextViewtextView=mWaitDialog.findViewById(R.id.tv_message); textView.setText(text); mWaitDialog.show(); } returnmWaitDialog; } publicvoidhideWaitDialog(){ try{ if(mWaitDialog!=null){ mWaitDialog.dismiss(); } mWaitDialog=null; }catch(Exceptionex){ ex.printStackTrace(); } } }
2.EaseChatFragment.java:发送消息,加载更多,定义了发送接口,以便activity页面调用;
publicclassEaseChatFragmentextendsEaseBaseFragmentimplementsEMMessageListener{ …… …… protectedvoidsetRefreshLayoutListener(){ swipeRefreshLayout.setOnRefreshListener(newSwipeRefreshLayout.OnRefreshListener(){ @Override publicvoidonRefresh(){ handler.postDelayed(newRunnable(){ @Override publicvoidrun(){ if(!isRoaming){ loadMoreLocalMessage(); }else{ loadMoreRoamingMessages(); } } },600); } }); } /** *加载更多,haveMoreData的变化 */ privatevoidloadMoreLocalMessage(){ Log.e(TAG,"loadMoreLocalMessageisloading="+isloading+",haveMoreData="+haveMoreData+","+listView.getFirstVisiblePosition()); if(listView.getFirstVisiblePosition()==0&&!isloading&&haveMoreData){ Listmessages; try{ messages=conversation.loadMoreMsgFromDB(conversation.getAllMessages().size()==0?"":conversation.getAllMessages().get(0).getMsgId(), pagesize); }catch(Exceptione1){ swipeRefreshLayout.setRefreshing(false); return; } if(messages.size()>0){ messageList.refreshSeekTo(messages.size()-1); if(messages.size()!=pagesize){ haveMoreData=false; } }else{ haveMoreData=false; if(onRefreshListener!=null){ intsize=conversation.getAllMessages().size(); Log.e(TAG,"size="+size); intpageNo=size/10+1; onRefreshListener.refresh(pageNo); } } isloading=false; }else{ Toast.makeText(getActivity(),getResources().getString(R.string.no_more_messages), Toast.LENGTH_SHORT).show(); } swipeRefreshLayout.setRefreshing(false); } …… /** *发送消息,并调用向本地服务器发送消息的接口 */ protectedvoidsendMessage(EMMessagemessage){ if(message==null){ return; } Log.e(TAG,"sendMessageusername="+message.getUserName()+",to="+message.getTo()+",from="+message.getFrom() +",status="+message.status()+",direct="+message.direct()+",keySet="+message.ext().keySet() +",type="+message.getType()+",MsgId="+message.getMsgId() +",body="+message.getBody().toString()); if(chatFragmentHelper!=null){ //setextension chatFragmentHelper.onSetMessageAttributes(message); } if(chatType==EaseConstant.CHATTYPE_GROUP){ message.setChatType(ChatType.GroupChat); }elseif(chatType==EaseConstant.CHATTYPE_CHATROOM){ message.setChatType(ChatType.ChatRoom); } message.setMessageStatusCallback(messageStatusCallback); //Sendmessage. EMClient.getInstance().chatManager().sendMessage(message); //调用向本地服务器发送消息的接口 if(onClickSendListener!=null){ onClickSendListener.onSendClick(message); } //refreshui if(isMessageListInited){ messageList.refreshSelectLast(); } } /** *向本地服务器发送消息,需要在ChatActivity中调用 */ publicOnClickSendListeneronClickSendListener; publicvoidsetOnItemClickListener(OnClickSendListeneronClickBottomListener){ this.onClickSendListener=onClickBottomListener; } publicinterfaceOnClickSendListener{ /** *发送消息事件 */ publicvoidonSendClick(EMMessagemessage); } /** *下拉加载,在ChatFragment中调用 */ publicOnRefresh1ListeneronRefreshListener; publicvoidsetOnRefresh1Listener(OnRefresh1ListeneronClickBottomListener){ this.onRefreshListener=onClickBottomListener; } publicinterfaceOnRefresh1Listener{ /** *下拉加载事件 */ publicbooleanrefresh(intpage); }
3.ChatActivity.java:调用fragment的发送接口,以向本地服务器发送消息;
publicclassChatActivityextendsBaseActivity{ …… @Override protectedvoidonCreate(Bundlearg0){ super.onCreate(arg0); setContentView(R.layout.em_activity_chat); activityInstance=this; //getuseridorgroupid toChatUsername=getIntent().getExtras().getString("userId"); //useEaseChatFratFragment chatFragment=newChatFragment(); //passparameterstochatfragment chatFragment.setArguments(getIntent().getExtras()); getSupportFragmentManager().beginTransaction().add(R.id.container,chatFragment).commit(); chatFragment.setOnItemClickListener(newEaseChatFragment.OnClickSendListener(){ @Override publicvoidonSendClick(EMMessagemessage){ sendRemoteMsg(message); } }); } …… privatevoidsendRemoteMsg(EMMessagemessage){ MapbaseParam=newHashMap<>(); baseParam.put("id",""); baseParam.put("msgId",message.getMsgId()); baseParam.put("sendUser",message.getFrom()); baseParam.put("receiveUser",message.getTo()); Log.e(TAG,"receiveType="+message.getChatType().name()); StringchatType=""; if(message.getChatType()==EMMessage.ChatType.Chat){ chatType="0"; }else{ chatType="1"; } baseParam.put("receiveType",chatType); inttype=1; Filefile=null,file1=null; intsize=0; Log.e(TAG,"type="+message.getType().name()); if(message.getType().name().toString().equals("TXT")){ if(message.getBooleanAttribute("is_office",false)){ type=9; }else{ type=1; } EMTextMessageBodyemTextMessageBody=((EMTextMessageBody)message.getBody()); baseParam.put("message",emTextMessageBody.getMessage()); }elseif(message.getType().name().toString().equals("LOCATION")){ type=2; baseParam.put("message",message.getBody().toString()); }elseif(message.getType().name().toString().equals("VOICE")){ type=3; EMVoiceMessageBodyemVoiceMessageBody=((EMVoiceMessageBody)message.getBody()); StringfilePath=emVoiceMessageBody.getLocalUrl(); file=newFile(filePath); baseParam.put("size",emVoiceMessageBody.getLength()+""); baseParam.put("message",message.getBody().toString()); }elseif(message.getType().name().toString().equals("VIDEO")){ type=4; EMVideoMessageBodyemVideoMessageBody=((EMVideoMessageBody)message.getBody()); StringfilePath=emVideoMessageBody.getLocalUrl(); file=newFile(filePath); baseParam.put("size",emVideoMessageBody.getDuration()+""); Stringthumbnail=emVideoMessageBody.getLocalThumb(); Log.e(TAG,"thumbnail="+thumbnail+","+emVideoMessageBody.getLocalThumb()+",size="+emVideoMessageBody.getDuration()+","+emVideoMessageBody.getVideoFileLength()); file1=newFile(thumbnail); baseParam.put("message",message.getBody().toString()); }elseif(message.getType().name().toString().equals("IMAGE")){ type=5; StringfilePath=((EMImageMessageBody)message.getBody()).getLocalUrl(); file=newFile(filePath); baseParam.put("message",message.getBody().toString()); }elseif(message.getType().name().toString().equals("FILE")){ type=6; StringfilePath=((EMFileMessageBody)message.getBody()).getLocalUrl(); file=newFile(filePath); baseParam.put("message",message.getBody().toString()); }else{ type=1; baseParam.put("message",message.getBody().toString()); } baseParam.put("mesType",String.valueOf(type)); SimpleDateFormatformat=newSimpleDateFormat("yyyy-MM-ddHH:mm:ss"); baseParam.put("sendTime",format.format(newDate(message.getMsgTime()))); Log.e(TAG,"baseParam="+baseParam); FileLoadUtils.postFile(WebApi.MSN_CHAT_SAVE,baseParam,"mesFile",file,"thuFile",file1,newCallback(){ @Override publicvoidonFailure(Callcall,IOExceptione){ Log.e(TAG,"sendRemoteMsge="+e); } @Override publicvoidonResponse(Callcall,Responseresponse)throwsIOException{ Stringresult=FileLoadUtils.getResponseBody(response); Log.e(TAG,"sendRemoteMsgresponse="+result+","+response); } }); } }
4. EMMessageUtils.java: ChatFragment.java中获取聊天记录后,将各种类型的聊天记录转化成相应的格式:
publicclassEMMessageUtils{ privatestaticfinalStringTAG="EMMessageUtils"; publicstaticEMMessagecreateImageSendMessage(StringfromUser,Stringvar0,booleanvar1,Stringvar2){ Filefile=newFile(var0); Stringpath=""; if(!file.exists()){ StringfileName=file.getName(); path=FileLoadUtils.BASE_PATH+fromUser+"/image/"+fileName; file=newFile(path); }else{ path=var0; } EMMessagevar3=EMMessage.createSendMessage(EMMessage.Type.IMAGE); var3.setTo(var2); EMImageMessageBodyvar4=newEMImageMessageBody(file); var4.setSendOriginalImage(var1); var3.addBody(var4); returnvar3; } publicstaticEMMessagecreateVoiceSendMessage(Stringvar0,intvar1,Stringvar2){ Filefile=newFile(var0); FilepathFile=newFile(file.getParent()); if(!pathFile.exists()){ pathFile.mkdirs(); } if(!file.exists()){ try{ file.createNewFile(); }catch(IOExceptione){ e.printStackTrace(); } } EMMessagevar3=EMMessage.createSendMessage(EMMessage.Type.VOICE); EMVoiceMessageBodyvar4=newEMVoiceMessageBody(file,var1); var3.addBody(var4); var3.setTo(var2); returnvar3; //} } publicstaticEMMessagecreateVideoSendMessage(StringfromUser,Stringvar0,Stringvar1,intvar2,Stringvar3){ Filefile=newFile(var0); Stringpath=""; if(!file.exists()){ StringfileName=file.getName(); path=FileLoadUtils.BASE_PATH+fromUser+"/video/"+fileName; file=newFile(path); }else{ path=var0; } Log.e(TAG,"createVideoSendMessagepath="+path); EMMessagevar5=EMMessage.createSendMessage(EMMessage.Type.VIDEO); var5.setTo(var3); EMVideoMessageBodyvar6=newEMVideoMessageBody(path,var1,var2,file.length()); var5.addBody(var6); returnvar5; } /* *修改SDK中的创建文件类型的消息,改成使用自己的路径 **/ publicstaticEMMessagecreateFileSendMessage(StringfromUser,Stringvar0,Stringvar1){ Filefile=newFile(var0); Log.e(TAG,"createFileSendMessagevar0="+var0); Stringpath=""; if(!file.exists()){ StringfileName=file.getName(); path=FileLoadUtils.BASE_PATH+fromUser+"/file/"+fileName; file=newFile(path); }else{ path=var0; } EMMessagevar3=EMMessage.createSendMessage(EMMessage.Type.FILE); var3.setTo(var1); EMNormalFileMessageBodyvar4=newEMNormalFileMessageBody(file); var3.addBody(var4); returnvar3; } /* *创建视频类型的消息 **/ publicstaticEMMessagecreateVideoMsg(RemoteMessageremoteMessage){ EMMessagemessage=null; intsize=0; if(!StringUtils.isEmpty(remoteMessage.getSize())){ size=Integer.valueOf(remoteMessage.getSize()); } StringmsgStr=remoteMessage.getMessage(); String[]msgArr=msgStr.split(","); Stringlocalurl=""; StringthumbnailUrl=""; for(intj=0;j1){ thumbnailUrl=lat[1].trim(); } } } message=createVideoSendMessage(remoteMessage.getSendUser(),localurl,remoteMessage.getThuImg(),size,remoteMessage.getReceiveUser()); ((EMVideoMessageBody)message.getBody()).setRemoteUrl(remoteMessage.getFileUrl()); returnmessage; } /* *创建地址类型的消息 **/ publicstaticEMMessagecreateLocationMsg(RemoteMessageremoteMessage){ EMMessagemessage=null; StringlocStr=remoteMessage.getMessage(); String[]locArr=locStr.split(","); doublelatitude=0,longitude=0; StringlocationAddress=""; for(intj=0;j 5. FileLoadUtils.java:向本地服务器上传数据
publicclassFileLoadUtils{ privatestaticfinalStringTAG="FileLoadUtils"; publicFileLoadUtils(){ } …… /** *上传消息到服务器,表单形式上传 */ publicstaticvoidpostFile(finalStringurl,finalMapmap,StringimgStr,Filefile,Stringparam1,Filefile1,Callbackcallback){ OkHttpClientclient=newOkHttpClient(); //form表单形式上传 MultipartBody.BuilderrequestBody=newMultipartBody.Builder().setType(MultipartBody.FORM); if(file!=null){ Log.e("FileLoadUtils","file="+file.getPath()+","+file.getName()); //MediaType.parse()里面是上传的文件类型。 RequestBodybody=RequestBody.create(MediaType.parse("image/*"),file); Stringfilename=file.getName(); //参数分别为,请求key,文件名称,RequestBody requestBody.addFormDataPart(imgStr,filename,body); } if(file1!=null){ Log.e("FileLoadUtils","file="+file1.getPath()+","+file1.getName()); //MediaType.parse()里面是上传的文件类型。 RequestBodybody=RequestBody.create(MediaType.parse("image/*"),file1); Stringfilename=file1.getName(); //参数分别为,请求key,文件名称,RequestBody requestBody.addFormDataPart(param1,filename,body); } if(map!=null){ //map里面是请求中所需要的key和value Set >entries=map.entrySet(); for(Map.Entryentry:entries){ Stringkey=String.valueOf(entry.getKey()); Stringvalue=String.valueOf(entry.getValue()); Log.d("HttpUtils","key=="+key+",value=="+value); requestBody.addFormDataPart(key,value); } } Stringtoken=SavePreferences.getString(Const.TOKEN_KEY); Requestrequest=newRequest.Builder().url(url).header("token",token).post(requestBody.build()).build(); //readTimeout("请求超时时间",时间单位); client.newBuilder().readTimeout(5000,TimeUnit.MILLISECONDS).build() .newCall(request).enqueue(callback); } /** *获取文件保存地址,toUser指发送消息过来的好友名称 */ publicstaticFilecreateFileEm(Stringtype,StringFileName,StringtoUser){ Stringpath=null; if(toUser!=null&&!toUser.equals("")){ if(type.equals("3")){ path=BASE_PATH+toUser+"/voice/"; }elseif(type.equals("4")){ path=BASE_PATH+toUser+"/video/"; }elseif(type.equals("6")){ path=BASE_PATH+toUser+"/file/"; }else{ path=BASE_PATH+toUser+"/image/"; } }else{ if(type.equals("3")){ path=PathUtil.getInstance().getVoicePath()+"/"; }elseif(type.equals("4")){ path=PathUtil.getInstance().getVideoPath()+"/"; }elseif(type.equals("6")){ path=PathUtil.getInstance().getFilePath()+"/"; }else{ path=PathUtil.getInstance().getImagePath()+"/"; } } Filefile=newFile(path); /** *如果文件夹不存在就创建 */ if(!file.exists()){ file.mkdirs(); } returnnewFile(path,FileName); } /** *获取视频的缩略图路径 */ publicstaticStringgetThumnailPath(StringfromUser,StringvideoPath){ StringfileName="thvideo"+System.currentTimeMillis(); createFileEm("5",fileName,fromUser); //Filefile=newFile(getMSNBasePath("5",fromUser),fileName); Filefile=createFileEm("5",fileName,fromUser); try{ FileOutputStreamfos=newFileOutputStream(file); BitmapThumbBitmap=ThumbnailUtils.createVideoThumbnail(videoPath,3); ThumbBitmap.compress(Bitmap.CompressFormat.JPEG,100,fos); fos.close(); }catch(Exceptione){ e.printStackTrace(); } returnfile.getAbsolutePath(); } 6.发送企业名片后的显示:
发送完信息后,有个UI刷新的过程messageList.refreshSelectLast();----> messageAdapter.refreshSelectLast();
EaseMessageAdapter.java
publicclassEaseMessageAdapterextendsBaseAdapter{ privatefinalstaticStringTAG="EaseMessageAdapter"; privateContextcontext; privatestaticfinalintHANDLER_MESSAGE_REFRESH_LIST=0; privatestaticfinalintHANDLER_MESSAGE_SELECT_LAST=1; privatestaticfinalintHANDLER_MESSAGE_SEEK_TO=2; privatestaticfinalintMESSAGE_TYPE_RECV_TXT=0; privatestaticfinalintMESSAGE_TYPE_SENT_TXT=1; privatestaticfinalintMESSAGE_TYPE_SENT_IMAGE=2; privatestaticfinalintMESSAGE_TYPE_SENT_LOCATION=3; privatestaticfinalintMESSAGE_TYPE_RECV_LOCATION=4; privatestaticfinalintMESSAGE_TYPE_RECV_IMAGE=5; privatestaticfinalintMESSAGE_TYPE_SENT_VOICE=6; privatestaticfinalintMESSAGE_TYPE_RECV_VOICE=7; privatestaticfinalintMESSAGE_TYPE_SENT_VIDEO=8; privatestaticfinalintMESSAGE_TYPE_RECV_VIDEO=9; privatestaticfinalintMESSAGE_TYPE_SENT_FILE=10; privatestaticfinalintMESSAGE_TYPE_RECV_FILE=11; privatestaticfinalintMESSAGE_TYPE_SENT_EXPRESSION=12; privatestaticfinalintMESSAGE_TYPE_RECV_EXPRESSION=13; privatestaticfinalintMESSAGE_TYPE_SEND_CARD=14; privatestaticfinalintMESSAGE_TYPE_RECV_CARD=15; privateEMConversationconversation; EMMessage[]messages=null; privateStringtoChatUsername; privateMessageListItemClickListeneritemClickListener; privateEaseCustomChatRowProvidercustomRowProvider; privateListViewlistView; privateEaseMessageListItemStyleitemStyle; publicEaseMessageAdapter(Contextcontext,Stringusername,intchatType,ListViewlistView){ this.context=context; this.listView=listView; toChatUsername=username; this.conversation=EMClient.getInstance().chatManager().getConversation(username,EaseCommonUtils.getConversationType(chatType),true); } Handlerhandler=newHandler(){ privatevoidrefreshList(){ //youshouldnotcallgetAllMessages()inUIthread //otherwisethereisproblemwhenrefreshingUIandthereisnewmessagearrive java.util.Listvar=conversation.getAllMessages(); Log.e(TAG,"EMMessage.size="+var.size()); messages=var.toArray(newEMMessage[var.size()]); conversation.markAllMessagesAsRead(); notifyDataSetChanged(); } @Override publicvoidhandleMessage(android.os.Messagemessage){ switch(message.what){ caseHANDLER_MESSAGE_REFRESH_LIST: refreshList(); break; caseHANDLER_MESSAGE_SELECT_LAST: if(messages!=null&&messages.length>0){ listView.setSelection(messages.length-1); } break; caseHANDLER_MESSAGE_SEEK_TO: intposition=message.arg1; listView.setSelection(position); break; default: break; } } }; publicvoidrefresh(){ if(handler.hasMessages(HANDLER_MESSAGE_REFRESH_LIST)){ return; } android.os.Messagemsg=handler.obtainMessage(HANDLER_MESSAGE_REFRESH_LIST); handler.sendMessage(msg); } /** *refreshandselectthelast */ publicvoidrefreshSelectLast(){ finalintTIME_DELAY_REFRESH_SELECT_LAST=100; handler.removeMessages(HANDLER_MESSAGE_REFRESH_LIST); handler.removeMessages(HANDLER_MESSAGE_SELECT_LAST); handler.sendEmptyMessageDelayed(HANDLER_MESSAGE_REFRESH_LIST,TIME_DELAY_REFRESH_SELECT_LAST); handler.sendEmptyMessageDelayed(HANDLER_MESSAGE_SELECT_LAST,TIME_DELAY_REFRESH_SELECT_LAST); } /** *refreshandseektotheposition */ publicvoidrefreshSeekTo(intposition){ handler.sendMessage(handler.obtainMessage(HANDLER_MESSAGE_REFRESH_LIST)); } publicEMMessagegetItem(intposition){ if(messages!=null&&position 0){ returncustomRowProvider.getCustomChatRowTypeCount()+14; } return14; } /** *gettypeofitem */ publicintgetItemViewType(intposition){ EMMessagemessage=getItem(position); if(message==null){ return-1; } if(customRowProvider!=null&&customRowProvider.getCustomChatRowType(message)>0){ returncustomRowProvider.getCustomChatRowType(message)+13; } if(message.getType()==EMMessage.Type.TXT){ if(message.getBooleanAttribute(EaseConstant.MESSAGE_ATTR_IS_BIG_EXPRESSION,false)){ returnmessage.direct()==EMMessage.Direct.RECEIVE?MESSAGE_TYPE_RECV_EXPRESSION:MESSAGE_TYPE_SENT_EXPRESSION; } //企业名片 if(message.getBooleanAttribute("is_office",false)){ returnmessage.direct()==EMMessage.Direct.RECEIVE?MESSAGE_TYPE_RECV_CARD:MESSAGE_TYPE_SEND_CARD; } returnmessage.direct()==EMMessage.Direct.RECEIVE?MESSAGE_TYPE_RECV_TXT:MESSAGE_TYPE_SENT_TXT; } if(message.getType()==EMMessage.Type.IMAGE){ returnmessage.direct()==EMMessage.Direct.RECEIVE?MESSAGE_TYPE_RECV_IMAGE:MESSAGE_TYPE_SENT_IMAGE; } if(message.getType()==EMMessage.Type.LOCATION){ returnmessage.direct()==EMMessage.Direct.RECEIVE?MESSAGE_TYPE_RECV_LOCATION:MESSAGE_TYPE_SENT_LOCATION; } if(message.getType()==EMMessage.Type.VOICE){ returnmessage.direct()==EMMessage.Direct.RECEIVE?MESSAGE_TYPE_RECV_VOICE:MESSAGE_TYPE_SENT_VOICE; } if(message.getType()==EMMessage.Type.VIDEO){ returnmessage.direct()==EMMessage.Direct.RECEIVE?MESSAGE_TYPE_RECV_VIDEO:MESSAGE_TYPE_SENT_VIDEO; } if(message.getType()==EMMessage.Type.FILE){ returnmessage.direct()==EMMessage.Direct.RECEIVE?MESSAGE_TYPE_RECV_FILE:MESSAGE_TYPE_SENT_FILE; } return-1;//invalid } //重点 protectedEaseChatRowPresentercreateChatRowPresenter(EMMessagemessage,intposition){ Log.e(TAG,"createChatRowPresenter"); if(customRowProvider!=null&&customRowProvider.getCustomChatRow(message,position,this)!=null){ returncustomRowProvider.getCustomChatRow(message,position,this); } EaseChatRowPresenterpresenter=null; switch(message.getType()){ caseTXT: if(message.getBooleanAttribute(EaseConstant.MESSAGE_ATTR_IS_BIG_EXPRESSION,false)){ presenter=newEaseChatBigExpressionPresenter(); }else{ Log.e(TAG,"TXTis_office"); if(message.getBooleanAttribute("is_office",false)){ Log.e(TAG,"TXTis_officetrue"); presenter=newEaseChatCardPresenter(); }else{ presenter=newEaseChatTextPresenter(); } } break; caseLOCATION: presenter=newEaseChatLocationPresenter(); break; caseFILE: presenter=newEaseChatFilePresenter(); break; caseIMAGE: presenter=newEaseChatImagePresenter(); break; caseVOICE: presenter=newEaseChatVoicePresenter(); break; caseVIDEO: presenter=newEaseChatVideoPresenter(); break; default: break; } returnpresenter; } @SuppressLint("NewApi") publicViewgetView(finalintposition,ViewconvertView,ViewGroupparent){ EMMessagemessage=getItem(position); EaseChatRowPresenterpresenter=null; Log.e(TAG,""+message.getBooleanAttribute("is_office",false)+","+message.getBody()); if(convertView==null){ presenter=createChatRowPresenter(message,position); convertView=presenter.createChatRow(context,message,position,this); convertView.setTag(presenter); }else{ presenter=(EaseChatRowPresenter)convertView.getTag(); } presenter.setup(message,position,itemClickListener,itemStyle); returnconvertView; } publicvoidsetItemStyle(EaseMessageListItemStyleitemStyle){ this.itemStyle=itemStyle; } publicvoidsetItemClickListener(MessageListItemClickListenerlistener){ itemClickListener=listener; } publicvoidsetCustomChatRowProvider(EaseCustomChatRowProviderrowProvider){ customRowProvider=rowProvider; } } 7. EaseChatCardPresenter.java
publicclassEaseChatCardPresenterextendsEaseChatRowPresenter{ privatestaticfinalStringTAG="EaseChatFilePresenter"; @Override protectedEaseChatRowonCreateChatRow(Contextcxt,EMMessagemessage,intposition,BaseAdapteradapter){ returnnewEaseChatRowCard(cxt,message,position,adapter); } @Override publicvoidonBubbleClick(EMMessagemessage){ EMTextMessageBodyfileMessageBody=(EMTextMessageBody)message.getBody(); //点击发送完后的企业名片需要的操作,还没有处理 …… if(message.direct()==EMMessage.Direct.RECEIVE&&!message.isAcked()&&message.getChatType()==EMMessage.ChatType.Chat){ try{ EMClient.getInstance().chatManager().ackMessageRead(message.getFrom(),message.getMsgId()); }catch(HyphenateExceptione){ //TODOAuto-generatedcatchblock e.printStackTrace(); } } } }8.EaseChatRowCard.java
publicclassEaseChatRowCardextendsEaseChatRow{ privatestaticfinalStringTAG="EaseChatRowCard"; protectedTextViewfileNameView; protectedTextViewfileSizeView; protectedTextViewfileStateView; protectedTextViewtvOfficeAddr; protectedTextViewtvOfficeTel; privateEMTextMessageBodyfileMessageBody; publicEaseChatRowCard(Contextcontext,EMMessagemessage,intposition,BaseAdapteradapter){ super(context,message,position,adapter); } @Override protectedvoidonInflateView(){ inflater.inflate(message.direct()==EMMessage.Direct.RECEIVE? R.layout.ease_row_received_card:R.layout.ease_row_sent_card,this); } @Override protectedvoidonFindViewById(){ fileNameView=(TextView)findViewById(R.id.tv_file_name); fileSizeView=(TextView)findViewById(R.id.tv_file_size); fileStateView=(TextView)findViewById(R.id.tv_file_state); percentageView=(TextView)findViewById(R.id.percentage); tvOfficeAddr=(TextView)findViewById(R.id.tv_officeAddr); tvOfficeTel=(TextView)findViewById(R.id.tv_officeTel); } @Override protectedvoidonSetUpView(){ fileMessageBody=(EMTextMessageBody)message.getBody(); Stringcontent=fileMessageBody.getMessage(); Log.e(TAG,"content="+content); if(message.getBooleanAttribute("is_office",false)){ String[]contentArr=content.split(","); OfficeCardcard=newOfficeCard(); card.setOfficeId(contentArr[0]); card.setOfficeName(contentArr[1]); card.setAddr(contentArr[2]); card.setTel(contentArr[3]); fileNameView.setText(card.getOfficeName()); tvOfficeAddr.setText(card.getAddr()); tvOfficeTel.setText(card.getTel()); } } @Override protectedvoidonViewUpdate(EMMessagemsg){ switch(msg.status()){ caseCREATE: onMessageCreate(); break; caseSUCCESS: onMessageSuccess(); break; caseFAIL: onMessageError(); break; caseINPROGRESS: onMessageInProgress(); break; } } privatevoidonMessageCreate(){ progressBar.setVisibility(View.VISIBLE); if(percentageView!=null) percentageView.setVisibility(View.INVISIBLE); if(statusView!=null) statusView.setVisibility(View.INVISIBLE); } privatevoidonMessageSuccess(){ progressBar.setVisibility(View.INVISIBLE); if(percentageView!=null) percentageView.setVisibility(View.INVISIBLE); if(statusView!=null) statusView.setVisibility(View.INVISIBLE); } privatevoidonMessageError(){ progressBar.setVisibility(View.INVISIBLE); if(percentageView!=null) percentageView.setVisibility(View.INVISIBLE); if(statusView!=null) statusView.setVisibility(View.VISIBLE); } privatevoidonMessageInProgress(){ progressBar.setVisibility(View.VISIBLE); if(percentageView!=null){ percentageView.setVisibility(View.VISIBLE); percentageView.setText(message.progress()+"%"); } if(statusView!=null) statusView.setVisibility(View.INVISIBLE); } }以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持毛票票。