示例#1
0
  /**
   * 当应用在前台时,如果当前消息不是属于当前会话,在状态栏提示一下 如果不需要,注释掉即可
   *
   * @param message
   */
  public void notifyNewMessage(EMMessage message) {
    // 如果是设置了不提醒只显示数目的群组(这个是app里保存这个数据的,demo里不做判断)
    // 以及设置了setShowNotificationInbackgroup:false(设为false后,后台时sdk也发送广播)
    if (!EasyUtils.isAppRunningForeground(this)) {
      return;
    }

    NotificationCompat.Builder mBuilder =
        new NotificationCompat.Builder(this)
            .setSmallIcon(R.drawable.zhxy_logo)
            .setContentTitle("新消息")
            .setWhen(System.currentTimeMillis())
            .setAutoCancel(true);

    String ticker = CommonUtils.getMessageDigest(message, this);
    String st = getResources().getString(R.string.expression);
    if (message.getType() == Type.TXT) ticker = ticker.replaceAll("\\[.{2,3}\\]", st);
    // 设置状态栏提示
    mBuilder.setTicker(message.getFrom() + ": " + ticker);

    // 必须设置pendingintent,否则在2.3的机器上会有bug
    Intent intent = new Intent(this, ChatActivity.class);
    // 程序内 跳转 单聊
    if (message.getChatType() == ChatType.Chat) {
      intent.putExtra(Constants.TEL, message.getFrom());
      intent.putExtra(Constants.USNAME, message.getUserName());
      Log.e("TAG", "收到的手机号 = " + message.getFrom());
      Log.e("得到的用户名为:", message.getUserName());
    }
    // 程序内 跳转 群聊
    if (message.getChatType() == ChatType.GroupChat) {
      intent.putExtra(Constants.TEL, message.getTo());
      intent.putExtra("chatType", Constants.CHATTYPE_GROUP);
      intent.putExtra(
          Constants.CLASS_SHORT_NAME,
          SharedPreferencesUtil.getClassShortName(getApplicationContext()));
      Log.e(
          "TAG",
          "收到的群组id = "
              + message.getTo()
              + "传递的 班级名称 = "
              + SharedPreferencesUtil.getClassShortName(getApplicationContext()));
    }

    intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
    PendingIntent pendingIntent =
        PendingIntent.getActivity(this, notifiId, intent, PendingIntent.FLAG_ONE_SHOT);
    mBuilder.setContentIntent(pendingIntent);

    Notification notification = mBuilder.build();
    notificationManager.notify(notifiId, notification);

    Intent intent2 = new Intent();
    intent2.setAction(Constants.AREA_UNREAD);
    intent2.putExtra(Constants.MSG_FROM, message.getFrom());
    sendOrderedBroadcast(intent2, null);
  }
示例#2
0
  @Override
  public void onEvent(EMNotifierEvent event) {
    switch (event.getEvent()) {
      case EventNewMessage:
        {
          EMMessage message = (EMMessage) event.getData();
          String userId = null;
          userId = message.getFrom();

          NotificationCompat.Builder mBuilder =
              new NotificationCompat.Builder(this)
                  .setSmallIcon(getApplicationContext().getApplicationInfo().icon)
                  .setWhen(System.currentTimeMillis())
                  .setContentTitle("有新消息了!")
                  .setContentText("A+")
                  .setAutoCancel(true);
          Intent resultIntent = new Intent(this, ChatActivity.class);
          resultIntent.setFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP);
          resultIntent.putExtra("notification", true);
          resultIntent.putExtra("easemobId", userId);
          TaskStackBuilder stackBuilder = TaskStackBuilder.create(this);
          stackBuilder.addParentStack(ChatActivity.class);
          stackBuilder.addNextIntent(resultIntent);
          PendingIntent resultPendingIntent =
              stackBuilder.getPendingIntent(0, PendingIntent.FLAG_UPDATE_CURRENT);
          mBuilder.setContentIntent(resultPendingIntent);
          NotificationManager mNotificationManager =
              (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);

          mNotificationManager.notify(0, mBuilder.build());
        }
    }
  }
        @Override
        public boolean onNewMessage(EMMessage message) {
          if (stoped) {
            return false;
          }
          EMUserInfo userinfo = EMUserInfo.createEMUserInfo(message);
          PendingIntent pendingIntent = null;
          if (message.getChatType() == EMMessage.ChatType.Chat) {
            String toUserName =
                message.getChatType() == EMMessage.ChatType.Chat
                    ? message.getFrom()
                    : message.getTo();
            Intent intent =
                new Intent(self, SingleChatActivity.class)
                    .setFlags(Intent.FLAG_ACTIVITY_NEW_TASK)
                    .putExtra(EaseConstant.EXTRA_USER_ID, toUserName);
            pendingIntent = PendingIntent.getActivity(self, 0, intent, PendingIntent.FLAG_ONE_SHOT);

            NotificationHelper.showNotification(
                self,
                EMChatHelper.EMCHAT_NEW_MESSAGE_NOTIFY_ID,
                userinfo.getUserNick() + "发来一条新信息",
                EMMessageHelper.getMessageBody(message),
                pendingIntent);
          } else if (message.getChatType() == EMMessage.ChatType.ChatRoom) {
            return true;
          }
          return true;
        }
示例#4
0
 /**
  * 根据消息内容和消息类型获取消息内容提示
  *
  * @param message
  * @param context
  * @return
  */
 private String getMessageDigest(EMMessage message, Context context) {
   String digest = "";
   switch (message.getType()) {
     case LOCATION: // 位置消息
       if (message.direct == EMMessage.Direct.RECEIVE) {
         digest = getStrng(context, R.string.location_recv);
         String name = message.getFrom();
         if (GloableParams.UserInfos != null) {
           User user = GloableParams.Users.get(message.getFrom());
           if (null != user.getUserName()) name = user.getUserName();
         }
         digest = String.format(digest, message.getFrom());
         return digest;
       } else {
         digest = getStrng(context, R.string.location_prefix);
       }
       break;
     case IMAGE: // 图片消息
       ImageMessageBody imageBody = (ImageMessageBody) message.getBody();
       digest = getStrng(context, R.string.picture) + imageBody.getFileName();
       break;
     case VOICE: // 语音消息
       digest = getStrng(context, R.string.voice_msg);
       break;
     case VIDEO: // 视频消息
       digest = getStrng(context, R.string.video);
       break;
     case TXT: // 文本消息
       if (!message.getBooleanAttribute(Constant.MESSAGE_ATTR_IS_VOICE_CALL, false)) {
         TextMessageBody txtBody = (TextMessageBody) message.getBody();
         digest = txtBody.getMessage();
       } else {
         TextMessageBody txtBody = (TextMessageBody) message.getBody();
         digest = getStrng(context, R.string.voice_call) + txtBody.getMessage();
       }
       break;
     case FILE: // 普通文件消息
       digest = getStrng(context, R.string.file);
       break;
     default:
       System.err.println("error, unknow type");
       return "";
   }
   return digest;
 }
示例#5
0
 /**
  * 发送通知栏提示 This can be override by subclass to provide customer implementation
  *
  * @param messages
  * @param isForeground
  */
 protected void sendNotification(List<EMMessage> messages, boolean isForeground) {
   for (EMMessage message : messages) {
     if (!isForeground) {
       notificationNum++;
       fromUsers.add(message.getFrom());
     }
   }
   sendNotification(messages.get(messages.size() - 1), isForeground, false);
 }
  public void playVoice(String filePath) {
    if (!(new File(filePath).exists())) {
      return;
    }
    AudioManager audioManager = (AudioManager) activity.getSystemService(Context.AUDIO_SERVICE);

    mediaPlayer = new MediaPlayer();
    if (EMChatManager.getInstance().getChatOptions().getUseSpeaker()) {
      audioManager.setMode(AudioManager.MODE_NORMAL);
      audioManager.setSpeakerphoneOn(true);
      mediaPlayer.setAudioStreamType(AudioManager.STREAM_RING);
    } else {
      audioManager.setSpeakerphoneOn(false); // 关闭扬声器
      // 把声音设定成Earpiece(听筒)出来,设定为正在通话中
      audioManager.setMode(AudioManager.MODE_IN_CALL);
      mediaPlayer.setAudioStreamType(AudioManager.STREAM_VOICE_CALL);
    }
    try {
      mediaPlayer.setDataSource(filePath);
      mediaPlayer.prepare();
      mediaPlayer.setOnCompletionListener(
          new MediaPlayer.OnCompletionListener() {

            @Override
            public void onCompletion(MediaPlayer mp) {
              // TODO Auto-generated method stub
              mediaPlayer.release();
              mediaPlayer = null;
              stopPlayVoice(); // stop animation
            }
          });
      isPlaying = true;
      currentPlayListener = this;
      currentMessage = message;
      mediaPlayer.start();
      showAnimation();
      try {
        // 如果是接收的消息
        if (!message.isAcked && message.direct == EMMessage.Direct.RECEIVE) {
          message.isAcked = true;
          if (iv_read_status != null && iv_read_status.getVisibility() == View.VISIBLE) {
            // 隐藏自己未播放这条语音消息的标志
            iv_read_status.setVisibility(View.INVISIBLE);
            EMChatDB.getInstance().updateMessageAck(message.getMsgId(), true);
          }
          // 告知对方已读这条消息
          if (chatType != ChatType.GroupChat)
            EMChatManager.getInstance().ackMessageRead(message.getFrom(), message.getMsgId());
        }
      } catch (Exception e) {
        message.isAcked = false;
      }
    } catch (Exception e) {
    }
  }
  /**
   * 根据消息内容和消息类型获取消息内容提示
   *
   * @param message
   * @param context
   * @return
   */
  private String getMessageDigest(EMMessage message, Context context) {
    String digest = "";
    switch (message.getType()) {
      case LOCATION: // 位置消息
        if (message.direct == EMMessage.Direct.RECEIVE) {
          // 从sdk中提到了ui中,使用更简单不犯错的获取string的方法
          // digest = EasyUtils.getAppResourceString(context,
          // "location_recv");
          digest = getStrng(context, R.string.location_recv);
          digest = String.format(digest, message.getFrom());
          return digest;
        } else {
          // digest = EasyUtils.getAppResourceString(context,
          // "location_prefix");
          digest = getStrng(context, R.string.location_prefix);
        }
        break;
      case IMAGE: // 图片消息
        ImageMessageBody imageBody = (ImageMessageBody) message.getBody();
        digest = getStrng(context, R.string.picture) + imageBody.getFileName();
        break;
      case VOICE: // 语音消息
        digest = getStrng(context, R.string.voice);
        break;
      case VIDEO: // 视频消息
        digest = getStrng(context, R.string.video);
        break;
      case TXT: // 文本消息
        if (((DemoHXSDKHelper) HXSDKHelper.getInstance()).isRobotMenuMessage(message)) {
          digest = ((DemoHXSDKHelper) HXSDKHelper.getInstance()).getRobotMenuMessageDigest(message);
        } else if (message.getBooleanAttribute(Constant.MESSAGE_ATTR_IS_VOICE_CALL, false)) {
          TextMessageBody txtBody = (TextMessageBody) message.getBody();
          digest = getStrng(context, R.string.voice_call) + txtBody.getMessage();
        } else {
          TextMessageBody txtBody = (TextMessageBody) message.getBody();
          digest = txtBody.getMessage();
        }
        break;
      case FILE: // 普通文件消息
        digest = getStrng(context, R.string.file);
        break;
      default:
        EMLog.e(TAG, "unknow type");
        return "";
    }

    return digest;
  }
 @Override
 public View getView(int position, View convertView, ViewGroup parent) {
   EMMessage message = conversation.getAllMessages().get(position);
   TextMessageBody body = (TextMessageBody) message.getBody();
   if (message.direct == EMMessage.Direct.RECEIVE) { // 接收方
     if (message.getType() == EMMessage.Type.TXT) {
       convertView = LayoutInflater.from(mcontext).inflate(R.layout.item_chatmsg, null);
       username = (TextView) convertView.findViewById(R.id.tv_chatusername);
       username.setText(message.getFrom());
     }
   } else {
     if (message.getType() == EMMessage.Type.TXT) {
       convertView = LayoutInflater.from(mcontext).inflate(R.layout.item_chatmsg2, null);
       username = (TextView) convertView.findViewById(R.id.tv_chatusername);
       //                username.setText(message.getFrom());
     }
   }
   msg = (TextView) convertView.findViewById(R.id.tv_chatmsg);
   msg.setText(body.getMessage());
   return convertView;
 }
示例#9
0
  /**
   * 发送通知栏提示 This can be override by subclass to provide customer implementation
   *
   * @param message
   */
  protected void sendNotification(EMMessage message, boolean isForeground, boolean numIncrease) {
    String username = message.getFrom();
    try {

      String notifyText = username + " ";
      switch (message.getType()) {
        case TXT:
          notifyText += msgs[0];
          break;
        case IMAGE:
          notifyText += msgs[1];
          break;
        case VOICE:
          notifyText += msgs[2];
          break;
        case LOCATION:
          notifyText += msgs[3];
          break;
        case VIDEO:
          notifyText += msgs[4];
          break;
        case FILE:
          notifyText += msgs[5];
          break;
      }

      PackageManager packageManager = appContext.getPackageManager();
      String appname = (String) packageManager.getApplicationLabel(appContext.getApplicationInfo());

      // notification titile
      String contentTitle = appname;
      if (notificationInfoProvider != null) {
        String customNotifyText = notificationInfoProvider.getDisplayedText(message);
        String customCotentTitle = notificationInfoProvider.getTitle(message);
        if (customNotifyText != null) {
          // 设置自定义的状态栏提示内容
          notifyText = customNotifyText;
        }

        if (customCotentTitle != null) {
          // 设置自定义的通知栏标题
          contentTitle = customCotentTitle;
        }
      }

      // create and send notificaiton
      NotificationCompat.Builder mBuilder =
          new NotificationCompat.Builder(appContext)
              .setSmallIcon(appContext.getApplicationInfo().icon)
              .setWhen(System.currentTimeMillis())
              .setAutoCancel(true);

      Intent msgIntent = appContext.getPackageManager().getLaunchIntentForPackage(packageName);
      if (notificationInfoProvider != null) {
        // 设置自定义的notification点击跳转intent
        msgIntent = notificationInfoProvider.getLaunchIntent(message);
      }

      PendingIntent pendingIntent =
          PendingIntent.getActivity(
              appContext, notifyID, msgIntent, PendingIntent.FLAG_UPDATE_CURRENT);

      if (numIncrease) {
        // prepare latest event info section
        if (!isForeground) {
          notificationNum++;
          fromUsers.add(message.getFrom());
        }
      }

      int fromUsersNum = fromUsers.size();
      String summaryBody =
          msgs[6]
              .replaceFirst("%1", Integer.toString(fromUsersNum))
              .replaceFirst("%2", Integer.toString(notificationNum));

      if (notificationInfoProvider != null) {
        // lastest text
        String customSummaryBody =
            notificationInfoProvider.getLatestText(message, fromUsersNum, notificationNum);
        if (customSummaryBody != null) {
          summaryBody = customSummaryBody;
        }

        // small icon
        int smallIcon = notificationInfoProvider.getSmallIcon(message);
        if (smallIcon != 0) {
          mBuilder.setSmallIcon(smallIcon);
        }
      }

      mBuilder.setContentTitle(contentTitle);
      mBuilder.setTicker(notifyText);
      mBuilder.setContentText(summaryBody);
      mBuilder.setContentIntent(pendingIntent);
      // mBuilder.setNumber(notificationNum);
      Notification notification = mBuilder.build();

      if (isForeground) {
        notificationManager.notify(foregroundNotifyID, notification);
        notificationManager.cancel(foregroundNotifyID);
      } else {
        notificationManager.notify(notifyID, notification);
      }

    } catch (Exception e) {
      e.printStackTrace();
    }
  }