Example usage for android.media MediaPlayer MediaPlayer

List of usage examples for android.media MediaPlayer MediaPlayer

Introduction

In this page you can find the example usage for android.media MediaPlayer MediaPlayer.

Prototype

public MediaPlayer() 

Source Link

Document

Default constructor.

Usage

From source file:es.javocsoft.android.lib.toolbox.ToolBox.java

/**
 * Plays the specified sound from the application asset folder.
 * /*from  ww  w.j  ava 2 s.c om*/
 * @param context
 * @param assetSoundPath   Path to the sound in the assets folder.
 */
public static void media_soundPlayFromAssetFolder(Context context, String assetSoundPath) {
    try {
        AssetFileDescriptor afd = context.getAssets().openFd(assetSoundPath);

        MediaPlayer player = new MediaPlayer();
        player.setDataSource(afd.getFileDescriptor(), afd.getStartOffset(), afd.getLength());
        player.prepare();
        player.start();

    } catch (Exception e) {
        if (LOG_ENABLE) {
            Log.e(TAG, "Error playing sound: '" + assetSoundPath + "' (" + e.getMessage() + ")", e);
        }
    }
}

From source file:com.codename1.impl.android.AndroidImplementation.java

/**
 * @inheritDoc/*  w ww  .  ja  va 2 s  . c o  m*/
 */
@Override
public Media createMedia(final String uri, boolean isVideo, final Runnable onCompletion) throws IOException {
    if (getActivity() == null) {
        return null;
    }
    if (!uri.startsWith(FileSystemStorage.getInstance().getAppHomePath())) {
        if (!checkForPermission(Manifest.permission.WRITE_EXTERNAL_STORAGE, "This is required to play media")) {
            return null;
        }
    }
    if (uri.startsWith("file://")) {
        return createMedia(removeFilePrefix(uri), isVideo, onCompletion);
    }
    File file = null;
    if (uri.indexOf(':') < 0) {
        // use a file object to play to try and workaround this issue:
        // http://code.google.com/p/android/issues/detail?id=4124
        file = new File(uri);
    }

    Media retVal;

    if (isVideo) {
        final AndroidImplementation.Video[] video = new AndroidImplementation.Video[1];
        final boolean[] flag = new boolean[1];
        final File f = file;
        getActivity().runOnUiThread(new Runnable() {
            @Override
            public void run() {
                VideoView v = new VideoView(getActivity());
                v.setZOrderMediaOverlay(true);
                if (f != null) {
                    v.setVideoURI(Uri.fromFile(f));
                } else {
                    v.setVideoURI(Uri.parse(uri));
                }
                video[0] = new AndroidImplementation.Video(v, getActivity(), onCompletion);
                flag[0] = true;
                synchronized (flag) {
                    flag.notify();
                }
            }
        });
        while (!flag[0]) {
            synchronized (flag) {
                try {
                    flag.wait(100);
                } catch (InterruptedException ex) {
                }
            }
        }
        return video[0];
    } else {
        MediaPlayer player;
        if (file != null) {
            FileInputStream is = new FileInputStream(file);
            player = new MediaPlayer();
            player.setDataSource(is.getFD());
            player.prepare();
        } else {
            player = MediaPlayer.create(getActivity(), Uri.parse(uri));
        }
        retVal = new Audio(getActivity(), player, null, onCompletion);
    }
    return retVal;
}

From source file:com.codename1.impl.android.AndroidImplementation.java

/**
 * @inheritDoc//from   w  w  w.  j  a  v  a  2 s. c o m
 */
@Override
public Media createMedia(InputStream stream, String mimeType, final Runnable onCompletion) throws IOException {
    if (getActivity() == null) {
        return null;
    }
    /*if(!checkForPermission(Manifest.permission.WRITE_EXTERNAL_STORAGE, "This is required to play media")){
    return null;
    }*/
    boolean isVideo = mimeType.contains("video");

    if (!isVideo && stream instanceof FileInputStream) {
        MediaPlayer player = new MediaPlayer();
        player.setDataSource(((FileInputStream) stream).getFD());
        player.prepare();
        return new Audio(getActivity(), player, stream, onCompletion);
    }
    String extension = MimeTypeMap.getFileExtensionFromUrl(mimeType);
    final File temp = File.createTempFile("mtmp", extension == null ? "dat" : extension);
    temp.deleteOnExit();
    OutputStream out = createFileOuputStream(temp);

    byte buf[] = new byte[256];
    int len = 0;
    while ((len = stream.read(buf, 0, buf.length)) > -1) {
        out.write(buf, 0, len);
    }
    out.close();
    stream.close();

    final Runnable finish = new Runnable() {

        @Override
        public void run() {
            if (onCompletion != null) {
                Display.getInstance().callSerially(onCompletion);

                // makes sure the file is only deleted after the onCompletion was invoked
                Display.getInstance().callSerially(new Runnable() {
                    @Override
                    public void run() {
                        temp.delete();
                    }
                });
                return;
            }
            temp.delete();
        }
    };

    if (isVideo) {
        final AndroidImplementation.Video[] retVal = new AndroidImplementation.Video[1];
        final boolean[] flag = new boolean[1];

        getActivity().runOnUiThread(new Runnable() {
            @Override
            public void run() {
                VideoView v = new VideoView(getActivity());
                v.setZOrderMediaOverlay(true);
                v.setVideoURI(Uri.fromFile(temp));
                retVal[0] = new AndroidImplementation.Video(v, getActivity(), finish);
                flag[0] = true;
                synchronized (flag) {
                    flag.notify();
                }
            }
        });
        while (!flag[0]) {
            synchronized (flag) {
                try {
                    flag.wait(100);
                } catch (InterruptedException ex) {
                }
            }
        }

        return retVal[0];
    } else {
        return createMedia(createFileInputStream(temp), mimeType, finish);
    }

}

From source file:com.nest5.businessClient.Initialactivity.java

public void playSound(Context context)
        throws IllegalArgumentException, SecurityException, IllegalStateException, IOException {
    Uri soundUri = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION);
    MediaPlayer mMediaPlayer = new MediaPlayer();
    mMediaPlayer.setDataSource(context, soundUri);
    final AudioManager audioManager = (AudioManager) context.getSystemService(Context.AUDIO_SERVICE);
    if (audioManager.getStreamVolume(AudioManager.STREAM_ALARM) != 0) {
        mMediaPlayer.setAudioStreamType(AudioManager.STREAM_ALARM);
        mMediaPlayer.setLooping(false);/*  ww  w.  j ava  2  s.c om*/
        mMediaPlayer.prepare();
        mMediaPlayer.start();
    }
}

From source file:me.ububble.speakall.fragment.ConversationGroupFragment.java

public void showMensajeAudio(int position, Context context, final MsgGroups message, View rowView,
        TextView icnMessageArrow) {//from  www  .java  2 s .  co m

    final TextView prevMessages = (TextView) rowView.findViewById(R.id.showprev_messages);
    TextView messageTime = (TextView) rowView.findViewById(R.id.message_time);
    final TextView icnMesajeTempo = (TextView) rowView.findViewById(R.id.icn_message_tempo);
    final View icnMensajeTempoDivider = (View) rowView.findViewById(R.id.icn_message_tempo_divider);
    final TextView icnMesajeCopy = (TextView) rowView.findViewById(R.id.icn_message_copy);
    final TextView icnMesajeBack = (TextView) rowView.findViewById(R.id.icn_message_back);
    TextView messageStatus = (TextView) rowView.findViewById(R.id.message_status);
    final LinearLayout messageMenu = (LinearLayout) rowView.findViewById(R.id.messages_menu_layout);
    final LinearLayout mensajeLayout = (LinearLayout) rowView.findViewById(R.id.mensaje_layout);
    TextView messageDate = (TextView) rowView.findViewById(R.id.message_date);
    final TextView audioTime = (TextView) rowView.findViewById(R.id.message_audio_time);
    final SeekBar audioSeekBar = (SeekBar) rowView.findViewById(R.id.audio_seekbar);
    final TextView playAudio = (TextView) rowView.findViewById(R.id.play_audio);
    final ProgressBar progressBar = (ProgressBar) rowView.findViewById(R.id.progress_bar);
    final RelativeLayout progressLayout = (RelativeLayout) rowView.findViewById(R.id.progress_layout);
    final TextView progressText = (TextView) rowView.findViewById(R.id.progress_message);
    final CircleImageView imageUser = (CircleImageView) rowView.findViewById(R.id.chat_row_user_pic);
    final TextView userName = (TextView) rowView.findViewById(R.id.username_text);

    TFCache.apply(context, messageTime, TFCache.TF_WHITNEY_MEDIUM);
    TFCache.apply(context, icnMesajeTempo, TFCache.TF_SPEAKALL);
    TFCache.apply(context, icnMesajeCopy, TFCache.TF_SPEAKALL);
    TFCache.apply(context, icnMesajeBack, TFCache.TF_SPEAKALL);
    TFCache.apply(context, messageStatus, TFCache.TF_SPEAKALL);
    TFCache.apply(context, prevMessages, TFCache.TF_WHITNEY_MEDIUM);
    TFCache.apply(context, messageDate, TFCache.TF_WHITNEY_MEDIUM);
    TFCache.apply(context, audioTime, TFCache.TF_WHITNEY_MEDIUM);
    TFCache.apply(context, userName, TFCache.TF_WHITNEY_MEDIUM);
    TFCache.apply(context, playAudio, TFCache.TF_SPEAKON);

    if (position == 0) {
        if (mensajesTotal > mensajesOffset) {
            prevMessages.setVisibility(View.VISIBLE);
            prevMessages.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    prevMessages.setVisibility(View.GONE);
                    if (mensajesTotal - mensajesOffset >= 10) {
                        mensajesLimit = 10;
                        mensajesOffset += mensajesLimit;
                        showPreviousMessages(mensajesOffset);
                    } else {
                        mensajesLimit = mensajesTotal - mensajesOffset;
                        mensajesOffset += mensajesLimit;
                        showPreviousMessages(mensajesOffset);
                    }
                }
            });
        }
    }

    DateFormat dateDay = new SimpleDateFormat("d");
    DateFormat dateDayText = new SimpleDateFormat("EEEE");
    DateFormat dateMonth = new SimpleDateFormat("MMMM");
    DateFormat dateYear = new SimpleDateFormat("yyyy");
    DateFormat timeFormat = new SimpleDateFormat("h:mm a");

    Calendar fechamsj = Calendar.getInstance();
    fechamsj.setTimeInMillis(message.emitedAt);
    String time = timeFormat.format(fechamsj.getTime());
    String dayMessage = dateDay.format(fechamsj.getTime());
    String monthMessage = dateMonth.format(fechamsj.getTime());
    String yearMessage = dateYear.format(fechamsj.getTime());
    String dayMessageText = dateDayText.format(fechamsj.getTime());
    char[] caracteres = dayMessageText.toCharArray();
    caracteres[0] = Character.toUpperCase(caracteres[0]);
    dayMessageText = new String(caracteres);

    Calendar fechaActual = Calendar.getInstance();
    String dayActual = dateDay.format(fechaActual.getTime());
    String monthActual = dateMonth.format(fechaActual.getTime());
    String yearActual = dateYear.format(fechaActual.getTime());

    String fechaMostrar = "";
    if (dayMessage.equals(dayActual) && monthMessage.equals(monthActual) && yearMessage.equals(yearActual)) {
        fechaMostrar = getString(R.string.messages_today);
    } else if (monthMessage.equals(monthActual) && yearMessage.equals(yearActual)) {
        int days = Integer.parseInt(dayActual) - Integer.parseInt(dayMessage);
        if (days < 7) {
            switch (days) {
            case 1:
                fechaMostrar = getString(R.string.messages_yesterday);
                break;
            default:
                fechaMostrar = dayMessageText;
                break;
            }
        } else {
            fechaMostrar = (dayMessage + " " + monthMessage + " " + yearMessage).toUpperCase();
        }
    } else {
        fechaMostrar = (dayMessage + " " + monthMessage + " " + yearMessage).toUpperCase();
    }

    messageDate.setText(fechaMostrar);
    if (position != -1) {

        if (itemAnterior != null) {
            if (!fechaMostrar.equals(fechaAnterior)) {
                itemAnterior.findViewById(R.id.message_date).setVisibility(View.VISIBLE);
            } else {
                itemAnterior.findViewById(R.id.message_date).setVisibility(View.GONE);
            }
        }
        itemAnterior = rowView;
        fechaAnterior = fechaMostrar;
    } else {
        View v = messagesList.getChildAt(messagesList.getChildCount() - 1);
        if (v != null) {
            TextView tv = (TextView) v.findViewById(R.id.message_date);
            if (tv.getText().toString().equals(fechaMostrar)) {
                messageDate.setVisibility(View.GONE);
            } else {
                messageDate.setVisibility(View.VISIBLE);
            }
        }
    }
    messageTime.setText(time);

    if (message.emisor.equals(u.id)) {
        progressBar.getProgressDrawable().setColorFilter(getResources().getColor(R.color.speak_all_red),
                PorterDuff.Mode.SRC_IN);
        int status = 0;
        try {
            JSONArray contactos = new JSONArray(message.receptores);
            for (int i = 0; i < contactos.length(); i++) {
                JSONObject contacto = contactos.getJSONObject(i);
                Log.w("STATUS", contacto.getInt("status") + contacto.getString("name"));
                if (status == 0 || contacto.getInt("status") <= status) {
                    status = contacto.getInt("status");
                }
            }
        } catch (JSONException e) {
            e.printStackTrace();
        }

        if (status != -1) {
            rowView.setOnLongClickListener(new View.OnLongClickListener() {
                @Override
                public boolean onLongClick(View v) {
                    if (messageSelected != null) {
                        View vista = messagesList.findViewWithTag(messageSelected);
                        vista.findViewById(messageMenu.getId()).setVisibility(View.INVISIBLE);
                        messageSelected = message.mensajeId;
                        ((MainActivity) activity).setOnBackPressedListener(new BackPressedListener(activity) {
                            @Override
                            public void doBack() {
                                View vista = messagesList.findViewWithTag(messageSelected);
                                vista.findViewById(messageMenu.getId()).setVisibility(View.INVISIBLE);
                                ((MainActivity) activity).setOnBackPressedListener(null);
                                messageSelected = null;
                            }
                        });
                    } else {
                        messageSelected = message.mensajeId;
                        ((MainActivity) activity).setOnBackPressedListener(new BackPressedListener(activity) {
                            @Override
                            public void doBack() {
                                if (messageSelected != null) {
                                    View vista = messagesList.findViewWithTag(messageSelected);
                                    vista.findViewById(messageMenu.getId()).setVisibility(View.INVISIBLE);
                                    ((MainActivity) activity).setOnBackPressedListener(null);
                                    messageSelected = null;
                                }
                            }
                        });
                    }

                    Vibrator x = (Vibrator) activity.getApplicationContext()
                            .getSystemService(Context.VIBRATOR_SERVICE);
                    x.vibrate(30);
                    MsgGroups mensaje = new Select().from(MsgGroups.class)
                            .where("mensajeId = ?", message.mensajeId).executeSingle();
                    int status = 0;
                    try {
                        JSONArray contactos = new JSONArray(mensaje.receptores);
                        for (int i = 0; i < contactos.length(); i++) {
                            JSONObject contacto = contactos.getJSONObject(i);
                            if (status == 0 || contacto.getInt("status") <= status) {
                                status = contacto.getInt("status");
                            }
                        }
                    } catch (JSONException e) {
                        e.printStackTrace();
                    }
                    if (status != 4) {
                        icnMesajeCopy.setVisibility(View.VISIBLE);
                        icnMesajeBack.setVisibility(View.VISIBLE);
                        messageMenu.setVisibility(View.VISIBLE);
                        AnimatorSet set = new AnimatorSet();
                        set.playTogether(ObjectAnimator.ofFloat(icnMesajeCopy, "alpha", 0, 1),
                                ObjectAnimator.ofFloat(icnMesajeBack, "alpha", 0, 1),
                                ObjectAnimator.ofFloat(messageMenu, "alpha", 0, 1),
                                ObjectAnimator.ofFloat(icnMesajeCopy, "translationX", 100, 0),
                                ObjectAnimator.ofFloat(icnMesajeBack, "translationX", 50, 0));
                        set.setDuration(200).start();
                    } else {
                        icnMesajeCopy.setVisibility(View.VISIBLE);
                        icnMesajeBack.setVisibility(View.VISIBLE);
                        messageMenu.setVisibility(View.VISIBLE);
                        AnimatorSet set = new AnimatorSet();
                        set.playTogether(ObjectAnimator.ofFloat(icnMesajeCopy, "alpha", 0, 1),
                                ObjectAnimator.ofFloat(icnMesajeBack, "alpha", 0, 1),
                                ObjectAnimator.ofFloat(messageMenu, "alpha", 0, 1),
                                ObjectAnimator.ofFloat(icnMesajeCopy, "translationX", 100, 0),
                                ObjectAnimator.ofFloat(icnMesajeBack, "translationX", 50, 0));
                        set.setDuration(200).start();
                    }

                    return false;
                }
            });
        }
        if (status == 1) {
            messageStatus.setTextSize(16);
            mensajeLayout.setBackgroundResource(R.drawable.message_out_background);
            icnMessageArrow.setTextColor(BalloonFragment.getBackgroundColor(activity));
            messageStatus.setTextColor(getResources().getColor(R.color.speak_all_ligh_gray));
            messageStatus.setText(Finder.STRING.ICN_MSJ_SENDING.toString());
            ValueAnimator colorAnim = ObjectAnimator.ofFloat(messageStatus, "alpha", 1, 0);
            colorAnim.setRepeatCount(ValueAnimator.INFINITE);
            colorAnim.setRepeatMode(ValueAnimator.REVERSE);
            colorAnim.setDuration(1000).start();
            animaciones.put(message.mensajeId, colorAnim);
            final JSONObject data = new JSONObject();
            try {
                data.put("type", message.tipo);
                data.put("group_id", message.grupoId);
                data.put("group_name", grupo.nombreGrupo);
                data.put("source", message.emisor);
                data.put("source_lang", message.emisorLang);
                data.put("source_email", message.emisorEmail);
                data.put("message", message.mensaje);
                data.put("translation_required", message.translation);
                data.put("message_id", message.mensajeId);
                data.put("targets", new JSONArray(message.receptores));
                data.put("delay", message.delay);
                if (!message.fileUploaded) {
                    progressLayout.setVisibility(View.VISIBLE);
                    new Thread(new Runnable() {
                        @Override
                        public void run() {
                            activity.runOnUiThread(new Runnable() {
                                @Override
                                public void run() {
                                    uploadAudioToServer(message.audioName, message, data, progressBar,
                                            progressLayout, progressText);
                                }
                            });
                        }
                    }).start();
                } else {
                    data.put("audios", message.fileName);
                    JSONArray targets = new JSONArray();
                    JSONArray contactos = new JSONArray(grupo.targets);
                    if (SpeakSocket.mSocket != null) {
                        if (SpeakSocket.mSocket.connected()) {
                            for (int i = 0; i < contactos.length(); i++) {
                                JSONObject contacto = contactos.getJSONObject(i);
                                JSONObject newContact = new JSONObject();
                                Contact contact = new Select().from(Contact.class)
                                        .where("id_contact = ?", contacto.getString("name")).executeSingle();
                                if (contact != null) {
                                    if (!contact.idContacto.equals(u.id)) {
                                        if (message.translation)
                                            newContact.put("lang", contact.lang);
                                        else
                                            newContact.put("lang", u.lang);
                                        newContact.put("name", contact.idContacto);
                                        newContact.put("screen_name", contact.screenName);
                                        newContact.put("status", 1);
                                        targets.put(targets.length(), newContact);
                                    }
                                }
                            }
                            data.put("targets", targets);
                            message.receptores = targets.toString();
                            message.save();
                            SpeakSocket.mSocket.emit("message", data);
                        } else {
                            for (int i = 0; i < contactos.length(); i++) {
                                JSONObject contacto = contactos.getJSONObject(i);
                                JSONObject newContact = new JSONObject();
                                Contact contact = new Select().from(Contact.class)
                                        .where("id_contact = ?", contacto.getString("name")).executeSingle();
                                if (contact != null) {
                                    if (!contact.idContacto.equals(u.id)) {
                                        if (message.translation)
                                            newContact.put("lang", contact.lang);
                                        else
                                            newContact.put("lang", u.lang);
                                        newContact.put("name", contact.idContacto);
                                        newContact.put("screen_name", contact.screenName);
                                        newContact.put("status", -1);
                                        targets.put(targets.length(), newContact);
                                    }
                                }
                            }
                            message.receptores = targets.toString();
                            message.save();
                        }
                    }
                    changeStatus(message.mensajeId);
                }
            } catch (JSONException e) {
                e.printStackTrace();
            }
        }
        if (status == -1) {
            messageStatus.setTextSize(11);
            mensajeLayout.setBackgroundResource(R.drawable.message_errorout_background);
            icnMessageArrow.setTextColor(getResources().getColor(R.color.speak_all_disable_red));
            messageStatus.setText(Finder.STRING.ICN_MSJ_ERROR.toString());
        }
        if (status == 3) {
            messageStatus.setTextSize(11);
            mensajeLayout.setBackgroundResource(R.drawable.message_out_background);
            icnMessageArrow.setTextColor(getResources().getColor(R.color.speak_all_disable_red));
            messageStatus.setText(Finder.STRING.ICN_MSJ_CLOSED.toString());
        }
        if (status == 2) {
            messageStatus.setTextSize(16);
            mensajeLayout.setBackgroundResource(R.drawable.message_out_background);
            icnMessageArrow.setTextColor(getResources().getColor(R.color.speak_all_disable_red));
            messageStatus.setText(Finder.STRING.ICN_MSJ_SEND.toString());
        }
        if (status == 4) {
            messageStatus.setTextSize(11);
            mensajeLayout.setBackgroundResource(R.drawable.message_out_background);
            icnMessageArrow.setTextColor(getResources().getColor(R.color.speak_all_disable_red));
            messageStatus.setText(Finder.STRING.ICN_MSJ_OPENED.toString());
        }

    } else {
        final Contact contacto = new Select().from(Contact.class).where(" id_contact= ?", message.emisor)
                .executeSingle();
        if (contacto != null) {
            new Thread(new Runnable() {
                @Override
                public void run() {
                    activity.runOnUiThread(new Runnable() {
                        @Override
                        public void run() {
                            if (contacto.photo != null) {
                                Bitmap bmp = BitmapFactory.decodeByteArray(contacto.photo, 0,
                                        contacto.photo.length);
                                imageUser.setImageBitmap(bmp);
                                userName.setText(contacto.fullName);
                            }
                        }
                    });
                }
            }).start();
        }
        rowView.setOnLongClickListener(new View.OnLongClickListener() {
            @Override
            public boolean onLongClick(View v) {
                if (messageSelected != null) {
                    View vista = messagesList.findViewWithTag(messageSelected);
                    vista.findViewById(messageMenu.getId()).setVisibility(View.INVISIBLE);
                    messageSelected = message.mensajeId;
                    ((MainActivity) activity).setOnBackPressedListener(new BackPressedListener(activity) {
                        @Override
                        public void doBack() {
                            View vista = messagesList.findViewWithTag(messageSelected);
                            vista.findViewById(messageMenu.getId()).setVisibility(View.INVISIBLE);
                            ((MainActivity) activity).setOnBackPressedListener(null);
                            messageSelected = null;
                        }
                    });
                } else {
                    messageSelected = message.mensajeId;
                    ((MainActivity) activity).setOnBackPressedListener(new BackPressedListener(activity) {
                        @Override
                        public void doBack() {
                            View vista = messagesList.findViewWithTag(messageSelected);
                            vista.findViewById(messageMenu.getId()).setVisibility(View.INVISIBLE);
                            ((MainActivity) activity).setOnBackPressedListener(null);
                            messageSelected = null;
                        }
                    });
                }

                Vibrator x = (Vibrator) activity.getApplicationContext()
                        .getSystemService(Context.VIBRATOR_SERVICE);
                x.vibrate(20);
                icnMesajeCopy.setVisibility(View.VISIBLE);
                icnMesajeBack.setVisibility(View.VISIBLE);
                messageMenu.setVisibility(View.VISIBLE);
                AnimatorSet set = new AnimatorSet();
                set.playTogether(ObjectAnimator.ofFloat(icnMesajeCopy, "alpha", 0, 1),
                        ObjectAnimator.ofFloat(icnMesajeBack, "alpha", 0, 1),
                        ObjectAnimator.ofFloat(messageMenu, "alpha", 0, 1),
                        ObjectAnimator.ofFloat(icnMesajeCopy, "translationX", -100, 0),
                        ObjectAnimator.ofFloat(icnMesajeBack, "translationX", -150, 0));
                set.setDuration(200).start();
                return false;
            }
        });
    }

    icnMesajeBack.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            if (message.emisor.equals(u.id)) {
                getFragmentManager().beginTransaction()
                        .replace(R.id.container2, ForwarForFragment.newInstance(message.mensaje))
                        .addToBackStack(null).commit();
                ((MainActivity) activity).setOnBackPressedListener(null);
            } else {
                getFragmentManager().beginTransaction()
                        .replace(R.id.container2, ForwarForFragment.newInstance(message.mensajeTrad))
                        .addToBackStack(null).commit();
                ((MainActivity) activity).setOnBackPressedListener(null);
            }
        }
    });

    rowView.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            if (messageSelected != null) {
                View vista = messagesList.findViewWithTag(messageSelected);
                if (!messageSelected.equals(message.mensajeId)) {
                    vista.findViewById(messageMenu.getId()).setVisibility(View.INVISIBLE);
                    ((MainActivity) activity).setOnBackPressedListener(null);
                    messageSelected = null;
                }
            }
            final MsgGroups mensaje = new Select().from(MsgGroups.class)
                    .where("mensajeId = ?", message.mensajeId).executeSingle();

            int status = 0;
            try {
                JSONArray contactos = new JSONArray(mensaje.receptores);
                for (int i = 0; i < contactos.length(); i++) {
                    JSONObject contacto = contactos.getJSONObject(i);
                    if (status == 0 || contacto.getInt("status") <= status) {
                        status = contacto.getInt("status");
                    }
                }
            } catch (JSONException e) {
                e.printStackTrace();
            }

            if (status == -1) {
                final JSONObject data = new JSONObject();
                try {
                    data.put("type", mensaje.tipo);
                    data.put("group_id", mensaje.grupoId);
                    data.put("group_name", grupo.nombreGrupo);
                    data.put("source", mensaje.emisor);
                    data.put("source_lang", mensaje.emisorLang);
                    data.put("source_email", mensaje.emisorEmail);
                    data.put("message", mensaje.mensaje);
                    data.put("translation_required", mensaje.translation);
                    data.put("message_id", mensaje.mensajeId);
                    data.put("targets", new JSONArray(mensaje.receptores));
                    data.put("delay", mensaje.delay);
                    if (!mensaje.fileUploaded) {
                        progressLayout.setVisibility(View.VISIBLE);
                        new Thread(new Runnable() {
                            @Override
                            public void run() {
                                activity.runOnUiThread(new Runnable() {
                                    @Override
                                    public void run() {
                                        uploadAudioToServer(mensaje.audioName, mensaje, data, progressBar,
                                                progressLayout, progressText);
                                    }
                                });
                            }
                        }).start();
                    } else {
                        data.put("audios", mensaje.fileName);
                        JSONArray targets = new JSONArray();
                        JSONArray contactos = new JSONArray(grupo.targets);
                        if (SpeakSocket.mSocket != null) {
                            if (SpeakSocket.mSocket.connected()) {
                                for (int i = 0; i < contactos.length(); i++) {
                                    JSONObject contacto = contactos.getJSONObject(i);
                                    JSONObject newContact = new JSONObject();
                                    Contact contact = new Select().from(Contact.class)
                                            .where("id_contact = ?", contacto.getString("name"))
                                            .executeSingle();
                                    if (contact != null) {
                                        if (!contact.idContacto.equals(u.id)) {
                                            if (mensaje.translation)
                                                newContact.put("lang", contact.lang);
                                            else
                                                newContact.put("lang", u.lang);
                                            newContact.put("name", contact.idContacto);
                                            newContact.put("screen_name", contact.screenName);
                                            newContact.put("status", 1);
                                            targets.put(targets.length(), newContact);
                                        }
                                    }
                                }
                                data.put("targets", targets);
                                mensaje.receptores = targets.toString();
                                mensaje.save();
                                SpeakSocket.mSocket.emit("message", data);
                            } else {
                                for (int i = 0; i < contactos.length(); i++) {
                                    JSONObject contacto = contactos.getJSONObject(i);
                                    JSONObject newContact = new JSONObject();
                                    Contact contact = new Select().from(Contact.class)
                                            .where("id_contact = ?", contacto.getString("name"))
                                            .executeSingle();
                                    if (contact != null) {
                                        if (!contact.idContacto.equals(u.id)) {
                                            if (mensaje.translation)
                                                newContact.put("lang", contact.lang);
                                            else
                                                newContact.put("lang", u.lang);
                                            newContact.put("name", contact.idContacto);
                                            newContact.put("screen_name", contact.screenName);
                                            newContact.put("status", -1);
                                            targets.put(targets.length(), newContact);
                                        }
                                    }
                                }
                                mensaje.receptores = targets.toString();
                                mensaje.save();
                            }
                        }
                        changeStatus(mensaje.mensajeId);
                    }
                } catch (JSONException e) {
                    e.printStackTrace();
                }
            }
        }
    });

    File audioFile = null;
    final MediaPlayer mediaPlayer1 = new MediaPlayer();
    audioFile = new File(message.audioName);
    try {
        mediaPlayer1.setDataSource(audioFile.getAbsolutePath());
        mediaPlayer1.prepare();
        long timePlayer = mediaPlayer1.getDuration();
        long days, hours, minutes, seconds;
        long secondsTotal = timePlayer / 1000;
        days = (Math.round(secondsTotal) / 86400);
        hours = (Math.round(secondsTotal) / 3600) - (days * 24);
        minutes = (Math.round(secondsTotal) / 60) - (days * 1440) - (hours * 60);
        seconds = Math.round(secondsTotal) % 60;
        audioTime.setText(String.format("%02d", minutes) + " : " + String.format("%02d", seconds));
        audioSeekBar.setMax(mediaPlayer1.getDuration());
        audioSeekBar.setTag(message.mensajeId);
        mediaPlayer1.release();
    } catch (IOException e) {
        e.printStackTrace();
    }

    final File finalAudioFile = audioFile;
    playAudio.setOnClickListener(new View.OnClickListener() {
        boolean isplayAudio = false;

        @Override
        public void onClick(View v) {

            if (activeAudioSeekBarr != null) {
                if (!activeAudioSeekBarr.getTag().equals(audioSeekBar.getTag())) {
                    isplayAudio = false;
                }
            }
            if (!isplayAudio) {
                try {
                    if (activeAudioSeekBarr != null) {
                        if (activeAudioSeekBarr.getTag().equals(audioSeekBar.getTag())) {
                            seekHandler.postDelayed(runAudio, 1000);
                            playAudio.setText(Finder.STRING.ICN_PAUSE.toString());
                            mediaPlayer.start();
                        } else {
                            if (mediaPlayer != null) {
                                mediaPlayer.stop();
                                mediaPlayer.release();
                            }
                            if (activeAudioSeekBarr != null) {
                                activeAudioSeekBarr.setProgress(0);
                                activeAudioSeekBarr.setOnSeekBarChangeListener(null);
                            }
                            if (activeAudioTime != null) {
                                activeAudioTime.setText(activeAudioDuration);
                            }
                            if (!activeAudioDuration.equals("")) {
                                activeAudioDuration = "";
                            }
                            if (activePlayer != null) {
                                activePlayer.setText(Finder.STRING.ICN_PLAY.toString());
                            }
                            seekHandler.removeCallbacks(runAudio);
                            mediaPlayer = new MediaPlayer();
                            mediaPlayer.setDataSource(finalAudioFile.getAbsolutePath());
                            mediaPlayer.prepare();
                            activeAudioDuration = audioTime.getText().toString();
                            audioSeekBar.setProgress(mediaPlayer.getCurrentPosition());
                            audioSeekBar.setOnSeekBarChangeListener(new SeekBar.OnSeekBarChangeListener() {
                                @Override
                                public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) {
                                    if (fromUser) {
                                        mediaPlayer.seekTo(progress);
                                    }
                                }

                                @Override
                                public void onStartTrackingTouch(SeekBar seekBar) {

                                }

                                @Override
                                public void onStopTrackingTouch(SeekBar seekBar) {

                                }
                            });
                            activeAudioSeekBarr = audioSeekBar;
                            activePlayer = playAudio;
                            activeAudioTime = audioTime;
                            seekHandler.postDelayed(runAudio, 1000);
                            mediaPlayer.start();
                            playAudio.setText(Finder.STRING.ICN_PAUSE.toString());
                        }
                    } else {
                        if (mediaPlayer != null) {
                            mediaPlayer.stop();
                            mediaPlayer.release();
                        }
                        if (activeAudioSeekBarr != null) {
                            activeAudioSeekBarr.setProgress(0);
                            activeAudioSeekBarr.setOnSeekBarChangeListener(null);
                        }
                        if (activeAudioTime != null) {
                            activeAudioTime.setText(activeAudioDuration);
                        }
                        if (!activeAudioDuration.equals("")) {
                            activeAudioDuration = "";
                        }
                        seekHandler.removeCallbacks(runAudio);
                        mediaPlayer = new MediaPlayer();
                        mediaPlayer.setDataSource(finalAudioFile.getAbsolutePath());
                        mediaPlayer.prepare();
                        activeAudioDuration = audioTime.getText().toString();
                        audioSeekBar.setProgress(mediaPlayer.getCurrentPosition());
                        audioSeekBar.setOnSeekBarChangeListener(new SeekBar.OnSeekBarChangeListener() {
                            @Override
                            public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) {
                                if (fromUser) {
                                    mediaPlayer.seekTo(progress);
                                }
                            }

                            @Override
                            public void onStartTrackingTouch(SeekBar seekBar) {

                            }

                            @Override
                            public void onStopTrackingTouch(SeekBar seekBar) {

                            }
                        });
                        activeAudioSeekBarr = audioSeekBar;
                        activePlayer = playAudio;
                        activeAudioTime = audioTime;
                        seekHandler.postDelayed(runAudio, 1000);
                        mediaPlayer.start();
                        playAudio.setText(Finder.STRING.ICN_PAUSE.toString());
                    }
                    //file2.delete();
                } catch (IOException e) {
                    e.printStackTrace();
                }
                isplayAudio = true;
            } else {
                playAudio.setText(Finder.STRING.ICN_PLAY.toString());
                mediaPlayer.pause();
                seekHandler.removeCallbacks(runAudio);
                isplayAudio = false;
            }
        }
    });

}

From source file:com.tct.mail.compose.ComposeActivity.java

protected void sendOrSave(final boolean save, final boolean showToast) {
    // Check if user is a monkey. Monkeys can compose and hit send
    // button but are not allowed to send anything off the device.
    // TS: xiaolin.li 2015-01-08 EMAIL BUGFIX-893877 DEL_S
    /*if (ActivityManager.isUserAMonkey()) {
    return;//from w  w  w. j  av  a2  s  . c  o  m
    }*/
    // TS: xiaolin.li 2015-01-08 EMAIL BUGFIX-893877 DEL_E
    final SendOrSaveCallback callback = new SendOrSaveCallback() {
        // FIXME: unused
        private int mRestoredRequestId;

        @Override
        public void initializeSendOrSave(SendOrSaveTask sendOrSaveTask) {
            synchronized (mActiveTasks) {
                int numTasks = mActiveTasks.size();
                if (numTasks == 0) {
                    // Start service so we won't be killed if this app is
                    // put in the background.
                    startService(new Intent(ComposeActivity.this, EmptyService.class));
                }

                mActiveTasks.add(sendOrSaveTask);
            }
            if (sTestSendOrSaveCallback != null) {
                sTestSendOrSaveCallback.initializeSendOrSave(sendOrSaveTask);
            }
        }

        @Override
        public void notifyMessageIdAllocated(SendOrSaveMessage sendOrSaveMessage, Message message) {
            synchronized (mDraftLock) {
                mDraftAccount = sendOrSaveMessage.mAccount;
                mDraftId = message.id;
                mDraft = message;
                if (sRequestMessageIdMap != null) {
                    sRequestMessageIdMap.put(sendOrSaveMessage.requestId(), mDraftId);
                }
                // Cache request message map, in case the process is killed
                saveRequestMap();
            }
            if (sTestSendOrSaveCallback != null) {
                sTestSendOrSaveCallback.notifyMessageIdAllocated(sendOrSaveMessage, message);
            }
        }

        @Override
        public Message getMessage() {
            synchronized (mDraftLock) {
                return mDraft;
            }
        }

        @Override
        public void sendOrSaveFinished(SendOrSaveTask task, boolean success) {
            // Update the last sent from account.
            if (mAccount != null) {
                MailAppProvider.getInstance().setLastSentFromAccount(mAccount.uri.toString());
            }
            // TS: zhaotianyong 2015-03-25 EMAIL BUGFIX-954496 ADD_S
            // TS: zhaotianyong 2015-03-31 EMAIL BUGFIX-963249 ADD_S
            if (doSend) {
                ConnectivityManager mConnectivityManager = (ConnectivityManager) ComposeActivity.this
                        .getSystemService(Context.CONNECTIVITY_SERVICE);
                NetworkInfo info = mConnectivityManager.getActiveNetworkInfo();
                if (info == null) {
                    Utility.showToast(ComposeActivity.this, R.string.send_failed);
                }
            }
            // TS: zhaotianyong 2015-03-31 EMAIL BUGFIX-963249 ADD_E
            // TS: zhaotianyong 2015-03-25 EMAIL BUGFIX-954496 ADD_E
            if (success) {
                // Successfully sent or saved so reset change markers
                discardChanges();
                //TS: zheng.zou 2015-03-18 EMAIL FEATURE_996919 ADD_S
                if (!doSend && showToast) {
                    Intent intent = new Intent(DRAFT_SAVED_ACTION);
                    intent.setPackage(getString(R.string.email_package_name));
                    intent.putExtra(BaseColumns._ID, mDraftId);
                    //send ordered broadcast to execute the event in sequence in different receivers,
                    //ordered by priority
                    sendOrderedBroadcast(intent, null);
                }
                //TS: zheng.zou 2015-03-18 EMAIL FEATURE_996919 ADD_E
            } else {
                // A failure happened with saving/sending the draft
                // TODO(pwestbro): add a better string that should be used
                // when failing to send or save
                //[BUGFIX]-MOD by SCDTABLET.shujing.jin@tcl.com,08/05/2016,2635083
                Utility.showShortToast(ComposeActivity.this, R.string.send_failed);
                //Toast.makeText(ComposeActivity.this, R.string.send_failed, Toast.LENGTH_SHORT)
                //        .show();
            }

            int numTasks;
            synchronized (mActiveTasks) {
                // Remove the task from the list of active tasks
                mActiveTasks.remove(task);
                numTasks = mActiveTasks.size();
            }

            if (numTasks == 0) {
                // Stop service so we can be killed.
                stopService(new Intent(ComposeActivity.this, EmptyService.class));
            }
            if (sTestSendOrSaveCallback != null) {
                sTestSendOrSaveCallback.sendOrSaveFinished(task, success);
            }
        }

        @Override
        public void incrementRecipientsTimesContacted(final List<String> recipients) {
            ComposeActivity.this.incrementRecipientsTimesContacted(recipients);
        }
    };
    //TS: zheng.zou 2015-3-16 EMAIL BUGFIX_948927 Mod_S
    if (mReplyFromAccount == null && mAccount != null) {
        mReplyFromAccount = getDefaultReplyFromAccount(mAccount);
    }
    if (mReplyFromAccount != null) {
        setAccount(mReplyFromAccount.account);
    }
    //TS: zheng.zou 2015-3-16 EMAIL BUGFIX_948927 Mod_E
    // TS: yanhua.chen 2015-9-19 EMAIL BUGFIX_569665 ADD_S
    mIsSaveDraft = save;
    // TS: yanhua.chen 2015-9-19 EMAIL BUGFIX_569665 ADD_E

    final Spanned body = removeComposingSpans(mBodyView.getText());
    SEND_SAVE_TASK_HANDLER.post(new Runnable() {
        @Override
        public void run() {
            final Message msg = createMessage(mReplyFromAccount, mRefMessage, getMode(), body);
            // TS: kaifeng.lu 2016-4-6 EMAIL BUGFIX_1909143 ADD_S
            if (/*!mIsClickIcon &&*/ !mEditDraft && (mIsSaveDraft || doSend)) {//[BUGFIX]-MOD by SCDTABLET.shujing.jin@tcl.com,05/06/2016,2013535
                String body1 = mBodyView.getText().toString().replace("\n", "\n\r");
                SpannableString spannableString = new SpannableString(body1);
                StringBuffer bodySignature = new StringBuffer(body1);
                //[BUGFIX]-DEL begin by SCDTABLET.shujing.jin@tcl.com,05/17/2016,2013535,2148647
                //if(mCachedSettings != null){
                //    bodySignature.append(convertToPrintableSignature(mCachedSettings.signature));
                //}
                //[BUGFIX]-DEL end by SCDTABLET.shujing.jin
                spannableString = new SpannableString(bodySignature.toString());
                msg.bodyHtml = spannedBodyToHtml(spannableString, true);
                msg.bodyText = bodySignature.toString();
            }
            // TS: kaifeng.lu 2016-4-6 EMAIL BUGFIX_1909143 ADD_E
            mRequestId = sendOrSaveInternal(ComposeActivity.this, mReplyFromAccount, msg, mRefMessage,
                    mQuotedTextView.getQuotedTextIfIncluded(), callback, SEND_SAVE_TASK_HANDLER, save,
                    mComposeMode, mDraftAccount, mExtraValues);
        }
    });

    // Don't display the toast if the user is just changing the orientation,
    // but we still need to save the draft to the cursor because this is how we restore
    // the attachments when the configuration change completes.
    if (showToast && (getChangingConfigurations() & ActivityInfo.CONFIG_ORIENTATION) == 0) {
        //TS: xinlei.sheng 2015-01-26 EMAIL FIXBUG_886976 MOD_S
        if (mLaunchContact) {
            mLaunchContact = false;
        } else {
            //TS: zheng.zou 2015-03-18 EMAIL FEATURE_996919 MDD_S
            if (!save) {
                //[BUGFIX]-MOD by SCDTABLET.shujing.jin@tcl.com,08/05/2016,2635083
                Utility.showToast(this, R.string.sending_message);
                //Toast.makeText(this, R.string.sending_message,
                //        Toast.LENGTH_LONG).show();
            }
            //                Toast.makeText(this, save ? R.string.message_saved : R.string.sending_message,
            //                        Toast.LENGTH_LONG).show();
            //TS: zheng.zou 2015-03-18 EMAIL FEATURE_996919 MOD_E
        }
        //TS: xinlei.sheng 2015-01-26 EMAIL FIXBUG_886976 MOD_E
    }

    // Need to update variables here because the send or save completes
    // asynchronously even though the toast shows right away.
    discardChanges();
    updateSaveUi();

    // If we are sending, finish the activity
    if (!save) {
        finish();
        //TS: yanhua.chen 2015-6-15 EMAIL BUGFIX_1024081 ADD_S
        //TS: lin-zhou 2015-10-15 EMAIL BUGFIX_718388 MOD_S
        Uri soundUri = Uri.parse(
                "android.resource://" + getApplicationContext().getPackageName() + "/" + R.raw.email_sent);
        MediaPlayer player = new MediaPlayer();
        try {
            if (soundUri != null) {
                player.setDataSource(getApplicationContext(), soundUri);
            }
            player.setAudioStreamType(AudioManager.STREAM_NOTIFICATION);
            player.prepare();
            player.start();
        } catch (IllegalArgumentException e) {
            LogUtils.e(LOG_TAG, "Send mail mediaPlayer get dataSource occur IllegalArgumentException");
        } catch (SecurityException e) {
            LogUtils.e(LOG_TAG, "Send mail mediaPlayer get dataSource occur SecurityException");
        } catch (IllegalStateException e) {
            LogUtils.e(LOG_TAG, "Send mail mediaPlayer get dataSource occur IllegalStateException");
        } catch (IOException e) {
            LogUtils.e(LOG_TAG, "Send mail mediaPlayer get dataSource occur IOException");
        } catch (NullPointerException e) {
            LogUtils.e(LOG_TAG, "Send mail mediaPlayer get dataSource occur NullPointerException");
        }
        //TS: lin-zhou 2015-10-15 EMAIL BUGFIX_718388 MOD_E
        //TS: yanhua.chen 2015-6-15 EMAIL BUGFIX_1024081 ADD_E
    }
}

From source file:me.ububble.speakall.fragment.ConversationChatFragment.java

public void showMensajeAudio(int position, Context context, final Message message, View rowView,
        TextView icnMessageArrow) {/* ww  w  .jav a  2  s  . co  m*/
    final TextView prevMessages = (TextView) rowView.findViewById(R.id.showprev_messages);
    TextView messageTime = (TextView) rowView.findViewById(R.id.message_time);
    final TextView icnMesajeTempo = (TextView) rowView.findViewById(R.id.icn_message_tempo);
    final View icnMensajeTempoDivider = (View) rowView.findViewById(R.id.icn_message_tempo_divider);
    final TextView icnMesajeCopy = (TextView) rowView.findViewById(R.id.icn_message_copy);
    final TextView icnMesajeBack = (TextView) rowView.findViewById(R.id.icn_message_back);
    TextView messageStatus = (TextView) rowView.findViewById(R.id.message_status);
    final LinearLayout messageMenu = (LinearLayout) rowView.findViewById(R.id.messages_menu_layout);
    final LinearLayout mensajeLayout = (LinearLayout) rowView.findViewById(R.id.mensaje_layout);
    TextView messageDate = (TextView) rowView.findViewById(R.id.message_date);
    final TextView audioTime = (TextView) rowView.findViewById(R.id.message_audio_time);
    final SeekBar audioSeekBar = (SeekBar) rowView.findViewById(R.id.audio_seekbar);
    final TextView playAudio = (TextView) rowView.findViewById(R.id.play_audio);
    final ProgressBar progressBar = (ProgressBar) rowView.findViewById(R.id.progress_bar);
    final RelativeLayout progressLayout = (RelativeLayout) rowView.findViewById(R.id.progress_layout);
    final TextView progressText = (TextView) rowView.findViewById(R.id.progress_message);

    TFCache.apply(context, messageTime, TFCache.TF_WHITNEY_MEDIUM);
    TFCache.apply(context, icnMesajeTempo, TFCache.TF_SPEAKALL);
    TFCache.apply(context, icnMesajeCopy, TFCache.TF_SPEAKALL);
    TFCache.apply(context, icnMesajeBack, TFCache.TF_SPEAKALL);
    TFCache.apply(context, messageStatus, TFCache.TF_SPEAKALL);
    TFCache.apply(context, prevMessages, TFCache.TF_WHITNEY_MEDIUM);
    TFCache.apply(context, messageDate, TFCache.TF_WHITNEY_MEDIUM);
    TFCache.apply(context, audioTime, TFCache.TF_WHITNEY_MEDIUM);
    TFCache.apply(context, playAudio, TFCache.TF_SPEAKON);

    if (position == 0) {
        if (mensajesTotal > mensajesOffset) {
            prevMessages.setVisibility(View.VISIBLE);
            prevMessages.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    prevMessages.setVisibility(View.GONE);
                    if (mensajesTotal - mensajesOffset >= 10) {
                        mensajesLimit = 10;
                        mensajesOffset += mensajesLimit;
                        showPreviousMessages(mensajesOffset);
                    } else {
                        mensajesLimit = mensajesTotal - mensajesOffset;
                        mensajesOffset += mensajesLimit;
                        showPreviousMessages(mensajesOffset);
                    }
                }
            });
        }
    }

    DateFormat dateDay = new SimpleDateFormat("d");
    DateFormat dateDayText = new SimpleDateFormat("EEEE");
    DateFormat dateMonth = new SimpleDateFormat("MMMM");
    DateFormat dateYear = new SimpleDateFormat("yyyy");
    DateFormat timeFormat = new SimpleDateFormat("h:mm a");

    Calendar fechamsj = Calendar.getInstance();
    fechamsj.setTimeInMillis(message.emitedAt);
    String time = timeFormat.format(fechamsj.getTime());
    String dayMessage = dateDay.format(fechamsj.getTime());
    String monthMessage = dateMonth.format(fechamsj.getTime());
    String yearMessage = dateYear.format(fechamsj.getTime());
    String dayMessageText = dateDayText.format(fechamsj.getTime());
    char[] caracteres = dayMessageText.toCharArray();
    caracteres[0] = Character.toUpperCase(caracteres[0]);
    dayMessageText = new String(caracteres);

    Calendar fechaActual = Calendar.getInstance();
    String dayActual = dateDay.format(fechaActual.getTime());
    String monthActual = dateMonth.format(fechaActual.getTime());
    String yearActual = dateYear.format(fechaActual.getTime());

    String fechaMostrar = "";
    if (dayMessage.equals(dayActual) && monthMessage.equals(monthActual) && yearMessage.equals(yearActual)) {
        fechaMostrar = getString(R.string.messages_today);
    } else if (monthMessage.equals(monthActual) && yearMessage.equals(yearActual)) {
        int days = Integer.parseInt(dayActual) - Integer.parseInt(dayMessage);
        if (days < 7) {
            switch (days) {
            case 1:
                fechaMostrar = getString(R.string.messages_yesterday);
                break;
            default:
                fechaMostrar = dayMessageText;
                break;
            }
        } else {
            fechaMostrar = (dayMessage + " " + monthMessage + " " + yearMessage).toUpperCase();
        }
    } else {
        fechaMostrar = (dayMessage + " " + monthMessage + " " + yearMessage).toUpperCase();
    }

    messageDate.setText(fechaMostrar);
    if (position != -1) {

        if (itemAnterior != null) {
            if (!fechaMostrar.equals(fechaAnterior)) {
                itemAnterior.findViewById(R.id.message_date).setVisibility(View.VISIBLE);
            } else {
                itemAnterior.findViewById(R.id.message_date).setVisibility(View.GONE);
            }
        }
        itemAnterior = rowView;
        fechaAnterior = fechaMostrar;
    } else {
        View v = messagesList.getChildAt(messagesList.getChildCount() - 1);
        if (v != null) {
            TextView tv = (TextView) v.findViewById(R.id.message_date);
            if (tv.getText().toString().equals(fechaMostrar)) {
                messageDate.setVisibility(View.GONE);
            } else {
                messageDate.setVisibility(View.VISIBLE);
            }
        }
    }
    messageTime.setText(time);

    if (message.emisor.equals(u.id)) {
        mensajeLayout.setBackgroundResource(R.drawable.message_out_background);
        GradientDrawable drawable1 = (GradientDrawable) mensajeLayout.getBackground();
        drawable1.setCornerRadius(radius);
        drawable1.setColor(BalloonFragment.getBackgroundColor(activity));
        progressBar.getProgressDrawable().setColorFilter(getResources().getColor(R.color.speak_all_red),
                PorterDuff.Mode.SRC_IN);
        if (message.status != -1) {
            rowView.setOnLongClickListener(new View.OnLongClickListener() {
                @Override
                public boolean onLongClick(View v) {
                    if (messageSelected != null) {
                        View vista = messagesList.findViewWithTag(messageSelected);
                        vista.findViewById(messageMenu.getId()).setVisibility(View.INVISIBLE);
                        messageSelected = message.mensajeId;
                        ((MainActivity) activity).setOnBackPressedListener(new BackPressedListener(activity) {
                            @Override
                            public void doBack() {
                                View vista = messagesList.findViewWithTag(messageSelected);
                                vista.findViewById(messageMenu.getId()).setVisibility(View.INVISIBLE);
                                ((MainActivity) activity).setOnBackPressedListener(null);
                                messageSelected = null;
                            }
                        });
                    } else {
                        messageSelected = message.mensajeId;
                        ((MainActivity) activity).setOnBackPressedListener(new BackPressedListener(activity) {
                            @Override
                            public void doBack() {
                                if (messageSelected != null) {
                                    View vista = messagesList.findViewWithTag(messageSelected);
                                    vista.findViewById(messageMenu.getId()).setVisibility(View.INVISIBLE);
                                    ((MainActivity) activity).setOnBackPressedListener(null);
                                    messageSelected = null;
                                }
                            }
                        });
                    }

                    Vibrator x = (Vibrator) activity.getApplicationContext()
                            .getSystemService(Context.VIBRATOR_SERVICE);
                    x.vibrate(30);
                    Message mensaje = new Select().from(Message.class).where("mensajeId = ?", message.mensajeId)
                            .executeSingle();
                    if (mensaje.status != 4) {
                        icnMesajeTempo.setVisibility(View.VISIBLE);
                        icnMensajeTempoDivider.setVisibility(View.VISIBLE);
                        icnMesajeCopy.setVisibility(View.VISIBLE);
                        icnMesajeBack.setVisibility(View.VISIBLE);
                        messageMenu.setVisibility(View.VISIBLE);
                        AnimatorSet set = new AnimatorSet();
                        set.playTogether(ObjectAnimator.ofFloat(icnMesajeTempo, "alpha", 0, 1),
                                ObjectAnimator.ofFloat(icnMesajeCopy, "alpha", 0, 1),
                                ObjectAnimator.ofFloat(icnMesajeBack, "alpha", 0, 1),
                                ObjectAnimator.ofFloat(messageMenu, "alpha", 0, 1),
                                ObjectAnimator.ofFloat(icnMesajeTempo, "translationX", 150, 0),
                                ObjectAnimator.ofFloat(icnMesajeCopy, "translationX", 100, 0),
                                ObjectAnimator.ofFloat(icnMesajeBack, "translationX", 50, 0));
                        set.setDuration(200).start();
                    } else {
                        icnMesajeCopy.setVisibility(View.VISIBLE);
                        icnMesajeBack.setVisibility(View.VISIBLE);
                        messageMenu.setVisibility(View.VISIBLE);
                        AnimatorSet set = new AnimatorSet();
                        set.playTogether(ObjectAnimator.ofFloat(icnMesajeCopy, "alpha", 0, 1),
                                ObjectAnimator.ofFloat(icnMesajeBack, "alpha", 0, 1),
                                ObjectAnimator.ofFloat(messageMenu, "alpha", 0, 1),
                                ObjectAnimator.ofFloat(icnMesajeCopy, "translationX", 100, 0),
                                ObjectAnimator.ofFloat(icnMesajeBack, "translationX", 50, 0));
                        set.setDuration(200).start();
                    }

                    return false;
                }
            });
        }
        if (message.status == 1) {
            messageStatus.setTextSize(16);
            mensajeLayout.setBackgroundResource(R.drawable.message_out_background);
            GradientDrawable drawable = (GradientDrawable) mensajeLayout.getBackground();
            drawable.setCornerRadius(radius);
            drawable.setColor(BalloonFragment.getBackgroundColor(activity));
            icnMessageArrow.setTextColor(BalloonFragment.getBackgroundColor(activity));
            messageStatus.setTextColor(getResources().getColor(R.color.speak_all_ligh_gray));
            messageStatus.setText(Finder.STRING.ICN_MSJ_SENDING.toString());
            ValueAnimator colorAnim = ObjectAnimator.ofFloat(messageStatus, "alpha", 1, 0);
            colorAnim.setRepeatCount(ValueAnimator.INFINITE);
            colorAnim.setRepeatMode(ValueAnimator.REVERSE);
            colorAnim.setDuration(1000).start();
            animaciones.put(message.mensajeId, colorAnim);
            final JSONObject data = new JSONObject();
            try {
                data.put("message_id", message.mensajeId);
                data.put("source", message.emisor);
                data.put("source_email", message.emisorEmail);
                data.put("target_email", message.receptorEmail);
                data.put("target", message.receptor);
                data.put("type", message.tipo);
                if (!message.fileUploaded) {
                    progressLayout.setVisibility(View.VISIBLE);
                    new Thread(new Runnable() {
                        @Override
                        public void run() {
                            activity.runOnUiThread(new Runnable() {
                                @Override
                                public void run() {
                                    uploadAudioToServer(message.audioName, message, data, progressBar,
                                            progressLayout, progressText);
                                }
                            });
                        }
                    }).start();
                } else {
                    data.put("videos", message.fileName);
                    if (SpeakSocket.mSocket != null)
                        if (SpeakSocket.mSocket.connected()) {
                            message.status = 1;
                            SpeakSocket.mSocket.emit("message", data);
                        } else {
                            message.status = -1;
                        }
                    message.save();
                    changeStatus(message.mensajeId, message.status);
                }
            } catch (JSONException e) {
                e.printStackTrace();
            }
        }
        if (message.status == -1) {
            messageStatus.setTextSize(11);
            mensajeLayout.setBackgroundResource(R.drawable.message_out_background);
            GradientDrawable drawable = (GradientDrawable) mensajeLayout.getBackground();
            drawable.setCornerRadius(radius);
            drawable.setColor(BalloonFragment.getBackgroundColor(activity));
            icnMessageArrow.setTextColor(BalloonFragment.getBackgroundColor(activity));
            messageStatus.setText(Finder.STRING.ICN_MSJ_ERROR.toString());
        }
        if (message.status == 3) {
            messageStatus.setTextSize(11);
            mensajeLayout.setBackgroundResource(R.drawable.message_out_background);
            GradientDrawable drawable = (GradientDrawable) mensajeLayout.getBackground();
            drawable.setCornerRadius(radius);
            drawable.setColor(BalloonFragment.getBackgroundColor(activity));
            icnMessageArrow.setTextColor(BalloonFragment.getBackgroundColor(activity));
            messageStatus.setText(Finder.STRING.ICN_MSJ_CLOSED.toString());
        }
        if (message.status == 2) {
            messageStatus.setTextSize(16);
            mensajeLayout.setBackgroundResource(R.drawable.message_out_background);
            GradientDrawable drawable = (GradientDrawable) mensajeLayout.getBackground();
            drawable.setCornerRadius(radius);
            drawable.setColor(BalloonFragment.getBackgroundColor(activity));
            icnMessageArrow.setTextColor(BalloonFragment.getBackgroundColor(activity));
            messageStatus.setText(Finder.STRING.ICN_MSJ_SEND.toString());
        }
        if (message.status == 4) {
            messageStatus.setTextSize(11);
            mensajeLayout.setBackgroundResource(R.drawable.message_out_background);
            GradientDrawable drawable = (GradientDrawable) mensajeLayout.getBackground();
            drawable.setCornerRadius(radius);
            drawable.setColor(BalloonFragment.getBackgroundColor(activity));
            icnMessageArrow.setTextColor(BalloonFragment.getBackgroundColor(activity));
            messageStatus.setText(Finder.STRING.ICN_MSJ_OPENED.toString());
            icnMensajeTempoDivider.setVisibility(View.GONE);
            icnMesajeTempo.setVisibility(View.GONE);
        } else {
            icnMensajeTempoDivider.setVisibility(View.INVISIBLE);
            icnMesajeTempo.setVisibility(View.INVISIBLE);
        }

        icnMesajeTempo.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                JSONObject notifyMessage = new JSONObject();
                try {
                    Message mensaje = new Select().from(Message.class).where("mensajeId = ?", message.mensajeId)
                            .executeSingle();
                    Log.w("mensaje detail",
                            mensaje.status + " : " + mensaje.receptorEmail + " : " + mensaje.tipo);
                    if (mensaje.status != 4) {
                        notifyMessage.put("type", mensaje.tipo);
                        notifyMessage.put("message_id", mensaje.mensajeId);
                        notifyMessage.put("source", mensaje.emisor);
                        notifyMessage.put("target", mensaje.receptor);
                        notifyMessage.put("status", 5);
                        if (SpeakSocket.mSocket != null)
                            if (SpeakSocket.mSocket.connected())
                                SpeakSocket.mSocket.emit("message-status", notifyMessage);
                    }
                } catch (JSONException e) {
                    e.printStackTrace();
                }
            }
        });

    } else {
        mensajeLayout.setBackgroundResource(R.drawable.message_out_background);
        GradientDrawable drawable = (GradientDrawable) mensajeLayout.getBackground();
        drawable.setCornerRadius(radius);
        drawable.setColor(BalloonFragment.getFriendBalloon(activity));
        if (message.tipo == Integer.parseInt(getString(R.string.MSG_TYPE_BROADCAST_AUDIO))) {
            messageStatus.setTextSize(15);
            messageStatus.setText(Finder.STRING.ICN_BROADCAST_FILL.toString());
        }
        rowView.setOnLongClickListener(new View.OnLongClickListener() {
            @Override
            public boolean onLongClick(View v) {
                if (messageSelected != null) {
                    View vista = messagesList.findViewWithTag(messageSelected);
                    vista.findViewById(messageMenu.getId()).setVisibility(View.INVISIBLE);
                    messageSelected = message.mensajeId;
                    ((MainActivity) activity).setOnBackPressedListener(new BackPressedListener(activity) {
                        @Override
                        public void doBack() {
                            View vista = messagesList.findViewWithTag(messageSelected);
                            vista.findViewById(messageMenu.getId()).setVisibility(View.INVISIBLE);
                            ((MainActivity) activity).setOnBackPressedListener(null);
                            messageSelected = null;
                        }
                    });
                } else {
                    messageSelected = message.mensajeId;
                    ((MainActivity) activity).setOnBackPressedListener(new BackPressedListener(activity) {
                        @Override
                        public void doBack() {
                            View vista = messagesList.findViewWithTag(messageSelected);
                            vista.findViewById(messageMenu.getId()).setVisibility(View.INVISIBLE);
                            ((MainActivity) activity).setOnBackPressedListener(null);
                            messageSelected = null;
                        }
                    });
                }

                Vibrator x = (Vibrator) activity.getApplicationContext()
                        .getSystemService(Context.VIBRATOR_SERVICE);
                x.vibrate(20);
                icnMesajeTempo.setVisibility(View.GONE);
                icnMensajeTempoDivider.setVisibility(View.GONE);
                icnMesajeCopy.setVisibility(View.VISIBLE);
                icnMesajeBack.setVisibility(View.VISIBLE);
                messageMenu.setVisibility(View.VISIBLE);
                AnimatorSet set = new AnimatorSet();
                set.playTogether(ObjectAnimator.ofFloat(icnMesajeCopy, "alpha", 0, 1),
                        ObjectAnimator.ofFloat(icnMesajeBack, "alpha", 0, 1),
                        ObjectAnimator.ofFloat(messageMenu, "alpha", 0, 1),
                        ObjectAnimator.ofFloat(icnMesajeCopy, "translationX", -100, 0),
                        ObjectAnimator.ofFloat(icnMesajeBack, "translationX", -150, 0));
                set.setDuration(200).start();
                return false;
            }
        });
    }

    /*icnMesajeCopy.setOnClickListener(new View.OnClickListener() {
      @Override
      public void onClick(View v) {
          ClipData clip = ClipData.newPlainText("text", messageContent.getText().toString());
          ClipboardManager clipboard = (ClipboardManager) getActivity().getSystemService(Context.CLIPBOARD_SERVICE);
          clipboard.setPrimaryClip(clip);
          Toast.makeText(activity, "Copiado", Toast.LENGTH_SHORT).show();
      }
    });*/

    icnMesajeBack.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            if (message.emisor.equals(u.id)) {
                getFragmentManager().beginTransaction()
                        .replace(R.id.container2, ForwarForFragment.newInstance(message.mensaje))
                        .addToBackStack(null).commit();
                ((MainActivity) activity).setOnBackPressedListener(null);
            } else {
                getFragmentManager().beginTransaction()
                        .replace(R.id.container2, ForwarForFragment.newInstance(message.mensajeTrad))
                        .addToBackStack(null).commit();
                ((MainActivity) activity).setOnBackPressedListener(null);
            }
        }
    });

    rowView.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            if (messageSelected != null) {
                View vista = messagesList.findViewWithTag(messageSelected);
                if (!messageSelected.equals(message.mensajeId)) {
                    vista.findViewById(messageMenu.getId()).setVisibility(View.INVISIBLE);
                    ((MainActivity) activity).setOnBackPressedListener(null);
                    messageSelected = null;
                }
            }
            final Message mensaje = new Select().from(Message.class).where("mensajeId = ?", message.mensajeId)
                    .executeSingle();
            if (mensaje.status == -1) {
                final JSONObject data = new JSONObject();
                try {
                    data.put("message_id", mensaje.mensajeId);
                    data.put("source", mensaje.emisor);
                    data.put("source_email", mensaje.emisorEmail);
                    data.put("target_email", mensaje.receptorEmail);
                    data.put("target", mensaje.receptor);
                    data.put("type", mensaje.tipo);
                    if (!mensaje.fileUploaded) {
                        progressLayout.setVisibility(View.VISIBLE);
                        new Thread(new Runnable() {
                            @Override
                            public void run() {
                                activity.runOnUiThread(new Runnable() {
                                    @Override
                                    public void run() {
                                        uploadAudioToServer(mensaje.audioName, mensaje, data, progressBar,
                                                progressLayout, progressText);
                                    }
                                });
                            }
                        }).start();
                    } else {
                        data.put("audios", mensaje.fileName);
                        if (SpeakSocket.mSocket != null)
                            if (SpeakSocket.mSocket.connected()) {
                                mensaje.status = 1;
                                SpeakSocket.mSocket.emit("message", data);
                            } else {
                                mensaje.status = -1;
                            }
                        mensaje.save();
                        changeStatus(mensaje.mensajeId, mensaje.status);
                    }
                } catch (JSONException e) {
                    e.printStackTrace();
                }
            }
        }
    });

    File audioFile = null;
    final MediaPlayer mediaPlayer1 = new MediaPlayer();
    audioFile = new File(message.audioName);
    try {
        mediaPlayer1.setDataSource(audioFile.getAbsolutePath());
        mediaPlayer1.prepare();
        long timePlayer = mediaPlayer1.getDuration();
        long days, hours, minutes, seconds;
        long secondsTotal = timePlayer / 1000;
        days = (Math.round(secondsTotal) / 86400);
        hours = (Math.round(secondsTotal) / 3600) - (days * 24);
        minutes = (Math.round(secondsTotal) / 60) - (days * 1440) - (hours * 60);
        seconds = Math.round(secondsTotal) % 60;
        audioTime.setText(String.format("%02d", minutes) + " : " + String.format("%02d", seconds));
        audioSeekBar.setMax(mediaPlayer1.getDuration());
        audioSeekBar.setTag(message.mensajeId);
        mediaPlayer1.release();
    } catch (IOException e) {
        e.printStackTrace();
    }

    final File finalAudioFile = audioFile;
    playAudio.setOnClickListener(new View.OnClickListener() {
        boolean isplayAudio = false;

        @Override
        public void onClick(View v) {

            if (activeAudioSeekBarr != null) {
                if (!activeAudioSeekBarr.getTag().equals(audioSeekBar.getTag())) {
                    isplayAudio = false;
                }
            }
            if (!isplayAudio) {
                try {
                    if (activeAudioSeekBarr != null) {
                        if (activeAudioSeekBarr.getTag().equals(audioSeekBar.getTag())) {
                            seekHandler.postDelayed(runAudio, 1000);
                            playAudio.setText(Finder.STRING.ICN_PAUSE.toString());
                            mediaPlayer.start();
                        } else {
                            if (mediaPlayer != null) {
                                mediaPlayer.stop();
                                mediaPlayer.release();
                            }
                            if (activeAudioSeekBarr != null) {
                                activeAudioSeekBarr.setProgress(0);
                                activeAudioSeekBarr.setOnSeekBarChangeListener(null);
                            }
                            if (activeAudioTime != null) {
                                activeAudioTime.setText(activeAudioDuration);
                            }
                            if (!activeAudioDuration.equals("")) {
                                activeAudioDuration = "";
                            }
                            if (activePlayer != null) {
                                activePlayer.setText(Finder.STRING.ICN_PLAY.toString());
                            }
                            seekHandler.removeCallbacks(runAudio);
                            mediaPlayer = new MediaPlayer();
                            mediaPlayer.setDataSource(finalAudioFile.getAbsolutePath());
                            mediaPlayer.prepare();
                            activeAudioDuration = audioTime.getText().toString();
                            audioSeekBar.setProgress(mediaPlayer.getCurrentPosition());
                            audioSeekBar.setOnSeekBarChangeListener(new SeekBar.OnSeekBarChangeListener() {
                                @Override
                                public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) {
                                    if (fromUser) {
                                        mediaPlayer.seekTo(progress);
                                    }
                                }

                                @Override
                                public void onStartTrackingTouch(SeekBar seekBar) {

                                }

                                @Override
                                public void onStopTrackingTouch(SeekBar seekBar) {

                                }
                            });
                            activeAudioSeekBarr = audioSeekBar;
                            activePlayer = playAudio;
                            activeAudioTime = audioTime;
                            seekHandler.postDelayed(runAudio, 1000);
                            mediaPlayer.start();
                            playAudio.setText(Finder.STRING.ICN_PAUSE.toString());
                        }
                    } else {
                        if (mediaPlayer != null) {
                            mediaPlayer.stop();
                            mediaPlayer.release();
                        }
                        if (activeAudioSeekBarr != null) {
                            activeAudioSeekBarr.setProgress(0);
                            activeAudioSeekBarr.setOnSeekBarChangeListener(null);
                        }
                        if (activeAudioTime != null) {
                            activeAudioTime.setText(activeAudioDuration);
                        }
                        if (!activeAudioDuration.equals("")) {
                            activeAudioDuration = "";
                        }
                        seekHandler.removeCallbacks(runAudio);
                        mediaPlayer = new MediaPlayer();
                        mediaPlayer.setDataSource(finalAudioFile.getAbsolutePath());
                        mediaPlayer.prepare();
                        activeAudioDuration = audioTime.getText().toString();
                        audioSeekBar.setProgress(mediaPlayer.getCurrentPosition());
                        audioSeekBar.setOnSeekBarChangeListener(new SeekBar.OnSeekBarChangeListener() {
                            @Override
                            public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) {
                                if (fromUser) {
                                    mediaPlayer.seekTo(progress);
                                }
                            }

                            @Override
                            public void onStartTrackingTouch(SeekBar seekBar) {

                            }

                            @Override
                            public void onStopTrackingTouch(SeekBar seekBar) {

                            }
                        });
                        activeAudioSeekBarr = audioSeekBar;
                        activePlayer = playAudio;
                        activeAudioTime = audioTime;
                        seekHandler.postDelayed(runAudio, 1000);
                        mediaPlayer.start();
                        playAudio.setText(Finder.STRING.ICN_PAUSE.toString());
                    }
                    //file2.delete();
                } catch (IOException e) {
                    e.printStackTrace();
                }
                isplayAudio = true;
            } else {
                playAudio.setText(Finder.STRING.ICN_PLAY.toString());
                mediaPlayer.pause();
                seekHandler.removeCallbacks(runAudio);
                isplayAudio = false;
            }
        }
    });

}