Пример #1
0
  /**
   * 接收文件
   *
   * @author Administrator
   */
  public void receivedFile() {
    /** 接收文件 */
    // Create the file transfer manager
    final FileTransferManager manager = new FileTransferManager(XmppConnection.getConnection());
    // Create the listener
    manager.addFileTransferListener(
        new FileTransferListener() {

          public void fileTransferRequest(FileTransferRequest request) {
            // Check to see if the request should be accepted
            Log.d("receivedFile ", " receive file");
            if (shouldAccept(request)) {
              // Accept it
              IncomingFileTransfer transfer = request.accept();
              try {

                System.out.println(request.getFileName());
                File file = new File(RECORD_ROOT_PATH + request.getFileName());

                android.os.Message msg = handler.obtainMessage();
                transfer.recieveFile(file);
                MessageInfo msgInfo = queryMsgForListMsg(file.getName());
                msgInfo.setFilePath(file.getPath()); // 更新 filepath
                new MyFileStatusThread(transfer, msgInfo).start();

              } catch (XMPPException e) {
                e.printStackTrace();
              }
            } else {
              // Reject it
              request.reject();
              String[] args =
                  new String[] {
                    userChat,
                    request.getFileName(),
                    TimeRender.getDate(),
                    "IN",
                    MessageInfo.TYPE[0],
                    MessageInfo.STATUS[1]
                  };
              MessageInfo msgInfo =
                  new MessageInfo(
                      args[0],
                      "redio",
                      args[2],
                      args[3],
                      MessageInfo.TYPE[0],
                      MessageInfo.STATUS[1]);
              // 在handler里取出来显示消息
              android.os.Message msg = handler.obtainMessage();
              msg.what = 5;
              msg.obj = msgInfo;
              handler.sendMessage(msg);
            }
          }
        });
  }
Пример #2
0
  /**
   * 发送文件
   *
   * @param path
   */
  public void sendFile(String path, MessageInfo msg) {
    /** 发送文件 */
    // Create the file transfer manager
    FileTransferManager sendFilemanager = new FileTransferManager(XmppConnection.getConnection());

    // Create the outgoing file transfer
    sendTransfer = sendFilemanager.createOutgoingFileTransfer(userChatSendFile);
    // Send the file
    try {

      sendTransfer.sendFile(new java.io.File(path), "send file");
      new MyFileStatusThread(sendTransfer, msg).start();
      /** 监听 */
    } catch (XMPPException e) {
      e.printStackTrace();
    }
  }
Пример #3
0
 public void sendFile(String filename) throws XMPPException {
   Presence pre = connection.getRoster().getPresence("*****@*****.**");
   System.out.println(pre);
   if (pre.getType() != Presence.Type.unavailable) {
     if (fileTransferManager == null) {
       initFileTransport();
     }
     FileTransferManager manager = new FileTransferManager(connection);
     // 创建输出的文件传输
     OutgoingFileTransfer transfer = manager.createOutgoingFileTransfer(pre.getFrom());
     // 发送文件
     transfer.sendFile(new File(filename), "图片");
     // while (!transfer.isDone()) {
     // if (transfer.getStatus() == FileTransfer.Status.in_progress) {
     // // 可以调用transfer.getProgress();获得传输的进度
     // System.out.println(transfer.getStatus());
     // System.out.println(transfer.getProgress());
     // System.out.println(transfer.isDone());
     // }
     // }
   }
 }
Пример #4
0
 private void recvFile() throws XMPPException {
   if (fileTransferManager == null) {
     initFileTransport();
   }
   fileTransferManager.addFileTransferListener(
       new FileTransferListener() {
         @Override
         public void fileTransferRequest(FileTransferRequest fileTransferRequest) {
           IncomingFileTransfer transfer = fileTransferRequest.accept();
           File sdDir = Environment.getExternalStorageDirectory();
           String filePath = sdDir.toString() + "/" + fileTransferRequest.getFileName();
           try {
             transfer.recieveFile(new File(filePath));
           } catch (XMPPException e) {
             e.printStackTrace();
           }
         }
       });
 }
Пример #5
0
  // [start]初始化
  private void initControl() {
    ImgLeft = (ImageView) findViewById(R.id.imageview_user_left);
    ImgRight = (ImageView) findViewById(R.id.imageview_user_right);
    mCommunity = (Button) findViewById(R.id.btn_community);
    mCommunity.setOnClickListener(new myOnClickListener());
    ref_buButton = (Button) findViewById(R.id.bn_refresh);
    ref_buButton.setOnClickListener(
        new OnClickListener() {

          @Override
          public void onClick(View v) {
            // TODO Auto-generated method stub
            new ContentAsyncTask().execute(String.format(Urls.USER_INFO, share.getString(UID, "")));
          }
        });
    friendsList = (Button) findViewById(R.id.btn_friendsList);
    friendsList.setOnClickListener(
        new OnClickListener() {

          @Override
          public void onClick(View v) {
            // TODO Auto-generated method stub
            Intent intent = new Intent(UserCenterActivity.this, FriendsMainActivity.class);
            startActivity(intent);
          }
        });
    mViewPager = (ViewPager) findViewById(R.id.user_pager);
    mViewPager.setOffscreenPageLimit(2);
    mIndicator = (PageIndicator) findViewById(R.id.user_indicator);
    mIndicator.setOnPageChangeListener(new IndicatorOnPageChangedListener());
    llGoHome = (LinearLayout) findViewById(R.id.Linear_above_toHome);
    llGoHome.setOnClickListener(this);
    loadLayout = (LinearLayout) findViewById(R.id.view_loading);
    loadFaillayout = (LinearLayout) findViewById(R.id.view_load_fail);

    FileTransferManager fileRecManager = new FileTransferManager(XmppTool.getConnection());
    fileRecManager.addFileTransferListener(
        new FileTransferListener() {
          @Override
          public void fileTransferRequest(FileTransferRequest request) {
            // 接收文件监听
            IncomingFileTransfer transfer = request.accept();
            String fileName = transfer.getFileName();
            try {
              transfer.recieveFile(
                  new File(
                      Environment.getExternalStorageDirectory().getPath()
                          + "/im/record"
                          + fileName));
            } catch (XMPPException e) {
              // TODO Auto-generated catch block
              e.printStackTrace();
            }
          }
        });

    // 开启消息监听
    ChatManager cm = XmppTool.XMPPgetChatManager();
    cm.addChatListener(
        new ChatManagerListener() {
          @Override
          public void chatCreated(Chat chat, boolean able) {
            chat.addMessageListener(
                new MessageListener() {
                  @Override
                  public void processMessage(Chat chat2, Message message) {
                    String from = message.getFrom();
                    String to = message.getTo();
                    String friendId = null;
                    String userId = null;
                    if (from.contains("/")) {
                      friendId = from.substring(0, from.lastIndexOf("/"));
                    } else {
                      friendId = from;
                    }
                    if (to.contains("/")) {
                      userId = to.substring(0, to.lastIndexOf("/"));
                    } else {
                      userId = to;
                    }
                    // System.out.println(friendId);
                    // System.out.println(userId);
                    // System.out.println(message.getBody());

                    Map<String, String> msg = new HashMap<String, String>();
                    msg.put("to", userId);
                    msg.put("from", friendId);
                    msg.put("content", message.getBody());
                    msg.put("ifread", "no");
                    msg.put("uid", userId);
                    if (IsVoice(message.getBody())) {
                      msg.put("voicetime", message.getBody().substring(10).split(",")[1]);
                    } else {
                      msg.put("voicetime", "0");
                    }

                    // 存入数据库
                    MessageStore store = new MessageStore(UserCenterActivity.this);
                    long result = 0;
                    if ((result = store.insertMessagelist(msg)) != -1) {
                      // System.out.println(result);
                    } else {
                      System.out.println("插入数据库失败");
                    }
                    store.deleteNewlist(friendId, userId);
                    store.insertNewlist(friendId, userId);
                    store.closeDB();

                    // 发送广播通知更新聊天页面与通讯录页面内容
                    Intent intent = new Intent("com.tee686.activity.FriendChatActivity");
                    intent.putExtra("content", message.getBody());
                    intent.putExtra("friendId", friendId);
                    intent.putExtra("userid", userId);
                    sendBroadcast(intent);

                    Intent newmsgintent = new Intent("com.tee686.activity.FriendsMainActivity");
                    sendBroadcast(newmsgintent);
                  }
                });
          }
        });
    // 监听prensence包
    PacketFilter filter = new AndFilter(new PacketTypeFilter(Presence.class));
    PacketListener listener =
        new PacketListener() {

          @Override
          public void processPacket(Packet packet) {
            // 看API可知道   Presence是Packet的子类
            if (packet instanceof Presence) {
              System.out.println(packet.toXML());
              Presence presence = (Presence) packet;
              // Presence还有很多方法,可查看API
              String from = presence.getFrom(); // 发送方
              String to = presence.getTo(); // 接收方
              // Presence.Type有7中状态
              if (presence.getType().equals(Presence.Type.subscribe)) { // 好友申请

              } else if (presence.getType().equals(Presence.Type.subscribed)) { // 同意添加好友

              } else if (presence.getType().equals(Presence.Type.unsubscribe)) { // 拒绝添加好友  和  删除好友

              } else if (presence.getType().equals(Presence.Type.unsubscribed)) { // 这个我没用到

              } else if (presence
                  .getType()
                  .equals(Presence.Type.unavailable)) { // 好友下线   要更新好友列表,可以在这收到包后,发广播到指定页面   更新列表

              } else { // 好友上线

              }
            }
          }
        };

    XmppTool.getConnection().addPacketListener(listener, filter);
    Roster roster = XmppTool.getConnection().getRoster();
    roster.addRosterListener(
        new RosterListener() {
          @Override
          // 监听好友申请消息
          public void entriesAdded(Collection<String> invites) {
            // TODO Auto-generated method stub
            System.out.println("监听到好友申请的消息是:" + invites);
            for (Iterator iter = invites.iterator(); iter.hasNext(); ) {
              String fromUserJids = (String) iter.next();
              System.out.println("fromUserJids是:" + fromUserJids);
            }
          }

          @Override
          // 监听好友同意添加消息
          public void entriesUpdated(Collection<String> invites) {
            // TODO Auto-generated method stub
            System.out.println("监听到好友同意的消息是:" + invites);
            for (Iterator iter = invites.iterator(); iter.hasNext(); ) {
              String fromUserJids = (String) iter.next();
              System.out.println("同意添加的好友是:" + fromUserJids);
            }
          }

          @Override
          // 监听好友删除消息
          public void entriesDeleted(Collection<String> delFriends) {
            // TODO Auto-generated method stub
            System.out.println("监听到删除好友的消息是:" + delFriends);
          }

          @Override
          // 监听好友状态改变消息
          public void presenceChanged(Presence presence) {
            // TODO Auto-generated method stub
          }
        });
  }
  /**
   * Sends a file transfer request to the given <tt>toContact</tt>.
   *
   * @return the transfer object
   * @param toContact the contact that should receive the file
   * @param file file to send
   * @param gw special gateway to be used for receiver if its jid misses the domain part
   */
  FileTransfer sendFile(Contact toContact, File file, String gw)
      throws IllegalStateException, IllegalArgumentException, OperationNotSupportedException {
    OutgoingFileTransferJabberImpl outgoingTransfer = null;

    try {
      assertConnected();

      if (file.length() > getMaximumFileLength())
        throw new IllegalArgumentException("File length exceeds the allowed one for this protocol");

      String fullJid = null;
      // Find the jid of the contact which support file transfer
      // and is with highest priority if more than one found
      // if we have equals priorities
      // choose the one that is more available
      OperationSetMultiUserChat mucOpSet =
          jabberProvider.getOperationSet(OperationSetMultiUserChat.class);
      if (mucOpSet != null && mucOpSet.isPrivateMessagingContact(toContact.getAddress())) {
        fullJid = toContact.getAddress();
      } else {
        Iterator<Presence> iter =
            jabberProvider.getConnection().getRoster().getPresences(toContact.getAddress());
        int bestPriority = -1;

        PresenceStatus jabberStatus = null;

        while (iter.hasNext()) {
          Presence presence = iter.next();

          if (jabberProvider.isFeatureListSupported(
              presence.getFrom(),
              new String[] {
                "http://jabber.org/protocol/si",
                "http://jabber.org/protocol/si/profile/file-transfer"
              })) {

            int priority =
                (presence.getPriority() == Integer.MIN_VALUE) ? 0 : presence.getPriority();

            if (priority > bestPriority) {
              bestPriority = priority;
              fullJid = presence.getFrom();
              jabberStatus =
                  OperationSetPersistentPresenceJabberImpl.jabberStatusToPresenceStatus(
                      presence, jabberProvider);
            } else if (priority == bestPriority && jabberStatus != null) {
              PresenceStatus tempStatus =
                  OperationSetPersistentPresenceJabberImpl.jabberStatusToPresenceStatus(
                      presence, jabberProvider);
              if (tempStatus.compareTo(jabberStatus) > 0) {
                fullJid = presence.getFrom();
                jabberStatus = tempStatus;
              }
            }
          }
        }
      }

      // First we check if file transfer is at all supported for this
      // contact.
      if (fullJid == null) {
        throw new OperationNotSupportedException(
            "Contact client or server does not support file transfers.");
      }

      if (gw != null && !fullJid.contains("@") && !fullJid.endsWith(gw)) {
        fullJid = fullJid + "@" + gw;
      }

      OutgoingFileTransfer transfer = manager.createOutgoingFileTransfer(fullJid);

      outgoingTransfer =
          new OutgoingFileTransferJabberImpl(toContact, file, transfer, jabberProvider);

      // Notify all interested listeners that a file transfer has been
      // created.
      FileTransferCreatedEvent event = new FileTransferCreatedEvent(outgoingTransfer, new Date());

      fireFileTransferCreated(event);

      // Send the file through the Jabber file transfer.
      transfer.sendFile(file, "Sending file");

      // Start the status and progress thread.
      new FileTransferProgressThread(transfer, outgoingTransfer).start();
    } catch (XMPPException e) {
      logger.error("Failed to send file.", e);
    }

    return outgoingTransfer;
  }
Пример #7
0
  /** Inits the file transfer manager. */
  private void initFileTransferManager() {
    _fileTransferManager = new FileTransferManager(getAgent().getConnection());
    FileTransferNegotiator.setServiceEnabled(getAgent().getConnection(), true);

    _fileTransferManager.addFileTransferListener(
        new FileTransferListener() {
          public void fileTransferRequest(final FileTransferRequest request) {
            Thread t =
                new Thread(
                    new Runnable() {

                      @Override
                      public void run() {
                        String message = "";
                        boolean transmissionSuccessful = false;
                        File incomingFile = createNewIncomingFile(request.getFileName());

                        MobilisManager.getLogger()
                            .log(
                                Level.INFO,
                                String.format(
                                    "Incoming FileTransfer from: %s with filename: %s",
                                    request.getRequestor(), request.getFileName()));

                        // log( "file expected: requestor="
                        // + _expectedUploads.containsKey( request.getRequestor() ) +
                        // " filename="
                        // + _expectedUploads.get( request.getRequestor() ) );

                        // Only if 'preparefile' bean was sent, requestor can upload the
                        // service
                        FileUploadInformation inf = _expectedUploads.get(request.getRequestor());
                        if (_expectedUploads.containsKey(request.getRequestor())
                            && request.getFileName().equals(inf.fileName)
                            && null != incomingFile) {
                          // Accept Filetransfer
                          try {
                            if (request.getFileSize() > 0) {
                              IncomingFileTransfer transfer = request.accept();
                              InputStream recieveFileInputStream = transfer.recieveFile();
                              FileHelper.createFileFromInputStream(
                                  recieveFileInputStream, incomingFile.getAbsolutePath());

                              //							if
                              // (transfer.getStatus().equals(FileTransfer.Status.complete)) {
                              transmissionSuccessful = true;
                              message =
                                  String.format(
                                      "Successful FileTransfer of file: %s",
                                      incomingFile.getName());
                              MobilisManager.getLogger().log(Level.INFO, message);
                              //							} else {
                              //								message = String.format( "FileTransfer of file: %s failed:
                              // ",
                              //										incomingFile.getName());
                              //							}

                            }
                          } catch (XMPPException e) {
                            transmissionSuccessful = false;
                            message =
                                String.format(
                                    "FileTransfer of file: %s failed: ",
                                    incomingFile.getName(), e.getMessage());
                          }
                        } else {
                          message = "File was not expected.";

                          request.reject();
                        }

                        if (transmissionSuccessful) {
                          synchronized (_expectedUploads) {
                            _expectedUploads.remove(request.getRequestor());
                          }

                          message +=
                              MobilisManager.getInstance()
                                  .installAndConfigureAndRegisterServiceFromFile(
                                      incomingFile, inf.autoDeploy, inf.singleMode, "deployment");
                        } else if (message.equals("") || message == null) {
                          message = "Unknown failure while uploading file";
                        }

                        if (null != message && !message.equals("")) {
                          MobilisManager.getLogger().log(Level.INFO, message);
                        }

                        sendServiceUploadConclusionBeanSET(
                            request.getRequestor(),
                            transmissionSuccessful,
                            incomingFile.getName(),
                            message);
                      }
                    });
            t.start();
          }
        });
  }