Example usage for android.content Intent setDataAndType

List of usage examples for android.content Intent setDataAndType

Introduction

In this page you can find the example usage for android.content Intent setDataAndType.

Prototype

public @NonNull Intent setDataAndType(@Nullable Uri data, @Nullable String type) 

Source Link

Document

(Usually optional) Set the data for the intent along with an explicit MIME data type.

Usage

From source file:com.guardtrax.ui.screens.HomeScreen.java

protected void onActivityResult(final int requestCode, int resultCode, final Intent data) {
    if (resultCode == RESULT_CANCELED)
        return;//w  w  w .ja  v  a 2s . c o m

    //After running Media Gallery Program
    if (requestCode == ACTIVITY_SELECT_IMAGE) {
        Uri_image = data.getData();

        Intent i = new Intent(HomeScreen.this, SingleImageView.class);
        startActivity(i);

        return;
    }

    if (requestCode == ACTIVITY_SELECT_VIDEO) {
        Uri_image = data.getData();

        Intent intent = new Intent(android.content.Intent.ACTION_VIEW);
        intent.setDataAndType(Uri_image, "video/mpeg");
        startActivity(intent);
        return;
    }

    //after running audio program
    if (requestCode == REQUEST_CODE_RECORD) {
        //move file into GT/s directory
        Uri savedUri = data.getData();
        Cursor cursor = getContentResolver().query(savedUri, null, null, null, null);
        if (cursor.moveToFirst()) {
            int column_index = cursor.getColumnIndexOrThrow(MediaStore.Images.Media.DATA);//Instead of "MediaStore.Images.Media.DATA" can be used "_data"
            Uri filePathUri = Uri.parse(cursor.getString(column_index));
            String file_path = filePathUri.getPath();

            //rename the file
            String path = GTConstants.sendfileFolder + Utility.createFileName() + ".3ga";

            //put the file name into the global
            file_name = path;

            File file_to = new File(path);
            File file_from = new File(file_path);
            file_from.renameTo(file_to);

            //Toast.makeText(HomeScreen.this, file_name, Toast.LENGTH_LONG).show();
        }
    }

    //after running camera, audio or video program
    if (requestCode == REQUEST_CODE_RECORD || requestCode == CAMERA_PIC_REQUEST
            || requestCode == ACTION_TAKE_VIDEO) {

        //this section was pulled from the "Cancel" option of the the tagging code - it replaces tagging (i.e. as if cancel is always being selected

        try {
            //copy file to /GT/r directory so that local user can view the image
            File file = new File(file_name);
            copyFile(GTConstants.sendfileFolder, file.getName(), GTConstants.receivefileFolder);

            //this needs to be sent to clear the deleted image from the gallery memory - otherwise would have to wait for reboot of phone
            //sendBroadcast(new Intent(Intent.ACTION_MEDIA_MOUNTED, Uri .parse("file://" + Environment.getExternalStorageDirectory())));
            sendBroadcast(new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE,
                    Uri.parse("file://" + Environment.getExternalStorageDirectory())));

            //new Upload_FTP().execute(file_name);
            Utility.setUploadAvailable();
        } catch (Exception e) {
            Toast.makeText(HomeScreen.this, "File copy Error: " + e, Toast.LENGTH_LONG).show();
        }

        //create filename info for dar
        String darFile[] = null;
        String newFile;
        try {
            darFile = file_name.split("_");
            newFile = GTConstants.LICENSE_ID.substring(7) + "_" + darFile[1] + "_" + darFile[2];
            //Toast.makeText(HomeScreen.this, "File: " + newFile, Toast.LENGTH_LONG).show();
        } catch (Exception e) {
            Toast.makeText(HomeScreen.this, "File Naming Error: " + e, Toast.LENGTH_LONG).show();
            newFile = "unknown";
        }

        //email option
        if (requestCode == REQUEST_CODE_RECORD) {
            //add event to dar and srp
            if (GTConstants.sendData) {
                Utility.write_to_file(HomeScreen.this,
                        GTConstants.dardestinationFolder + GTConstants.darfileName, "Voice;" + newFile + ".3ga"
                                + ";" + Utility.getLocalTime() + ";" + Utility.getLocalDate() + "\r\n",
                        true);

                if (GTConstants.srpfileName.length() > 1)
                    Utility.write_to_file(HomeScreen.this,
                            GTConstants.dardestinationFolder + GTConstants.srpfileName,
                            "Voice;" + newFile + ".3ga" + ";" + Utility.getLocalTime() + ";"
                                    + Utility.getLocalDate() + "\r\n",
                            true);

            }
            send_media_via_email("audio");
        }

        if (requestCode == CAMERA_PIC_REQUEST) {
            //add event to dar and srp
            if (GTConstants.sendData) {
                Utility.write_to_file(HomeScreen.this,
                        GTConstants.dardestinationFolder + GTConstants.darfileName, "Photo;" + newFile + ".jpg"
                                + ";" + Utility.getLocalTime() + ";" + Utility.getLocalDate() + "\r\n",
                        true);

                if (GTConstants.srpfileName.length() > 1)
                    Utility.write_to_file(HomeScreen.this,
                            GTConstants.dardestinationFolder + GTConstants.srpfileName,
                            "Photo;" + newFile + ".jpg" + ";" + Utility.getLocalTime() + ";"
                                    + Utility.getLocalDate() + "\r\n",
                            true);

            }
            send_media_via_email("photo");
        }

        if (requestCode == ACTION_TAKE_VIDEO) {
            //add event to dar
            if (GTConstants.sendData) {
                Utility.write_to_file(HomeScreen.this,
                        GTConstants.dardestinationFolder + GTConstants.darfileName, "Video;" + newFile + ".mpeg"
                                + ";" + Utility.getLocalTime() + ";" + Utility.getLocalDate() + "\r\n",
                        true);

                if (GTConstants.srpfileName.length() > 1)
                    Utility.write_to_file(HomeScreen.this,
                            GTConstants.dardestinationFolder + GTConstants.srpfileName,
                            "Video;" + newFile + ".mpeg" + ";" + Utility.getLocalTime() + ";"
                                    + Utility.getLocalDate() + "\r\n",
                            true);

            }
            send_media_via_email("video");
        }

        //end cancel section

        /*  Allowing fore tagging of media files removed 7/1/14 - B. Hall
        //after taking audio, camera or video this routine fires.  file_name is a common variable file name that is assigned when an audio, camera or video is taken
        AlertDialog.Builder dialog = new AlertDialog.Builder(HomeScreen.this);
        dialog.setTitle("Tag");
        dialog.setMessage("Add a tag?");
        final EditText input = new EditText(this);
        dialog.setView(input);
                
        dialog.setPositiveButton("OK",new DialogInterface.OnClickListener() 
        {
           @Override
           public void onClick(DialogInterface dialog,int which) 
           {
              String tagText = input.getText().toString().trim();
                      
              //rename the file
              File currentFile = new File(file_name);
              String path = GTConstants.sendfileFolder;
                      
              String oldFile = currentFile.getName();
              String newFile = oldFile.substring(0, oldFile.lastIndexOf('.')) + "_" + tagText + "_";
                      
              if (requestCode == CAMERA_PIC_REQUEST) 
                 { 
                 //rename the file to include tag
                 newFile = newFile + ".jpg";
                 file_name = path + newFile;
                         
                 File from = new File(path,oldFile);
                 File to = new File(path,newFile);
                 from.renameTo(to);
                         
                 //now upload the file to the ftp server
          //new Upload_FTP().execute(file_name);
          Utility.setUploadAvailable();
                  
          //email option
          send_media_via_email("photo");
                  
          //this needs to be sent to clear the deleted image from the gallery memory - otherwise would have to wait for reboot of phone
         sendBroadcast(new Intent(Intent.ACTION_MEDIA_MOUNTED, Uri .parse("file://" + Environment.getExternalStorageDirectory())));
                 
          //Toast.makeText(HomeScreen.this, "Picture saved", Toast.LENGTH_LONG).show();
                 }  
                         
                 if (requestCode == ACTION_TAKE_VIDEO) 
                 {
          newFile = newFile + ".mpeg";
                 file_name = path + newFile;
                         
                 File from = new File(path,oldFile);
                 File to = new File(path,newFile);
                 from.renameTo(to);
          //new Upload_FTP().execute(file_name);
                         
                 Utility.setUploadAvailable();
                  
          //email option
          send_media_via_email("video");
                  
          //this needs to be sent to clear the deleted image from the gallery memory - otherwise would have to wait for reboot of phone
         sendBroadcast(new Intent(Intent.ACTION_MEDIA_MOUNTED, Uri.parse("file://" + Environment.getExternalStorageDirectory())));
                 
          //Toast.makeText(HomeScreen.this, "Video saved", Toast.LENGTH_LONG).show();
                 }
                         
                 if (requestCode == REQUEST_CODE_RECORD) 
                 {
          newFile = newFile + ".3ga";
                 file_name = path + newFile;
                         
                 File from = new File(path,oldFile);
                 File to = new File(path,newFile);
                 from.renameTo(to);
          //new Upload_FTP().execute(file_name);
                 Utility.setUploadAvailable();
                  
          //email option
          send_media_via_email("audio");
                  
          //Toast.makeText(HomeScreen.this, "Audio saved", Toast.LENGTH_LONG).show();
                 }
                         
               //copy file to /GT/r directory so that local user can view the image
             copyFile(GTConstants.sendfileFolder, newFile, GTConstants.receivefileFolder);
                     
             //this needs to be sent to clear the deleted image from the gallery memory - otherwise would have to wait for reboot of phone
             sendBroadcast(new Intent(Intent.ACTION_MEDIA_MOUNTED, Uri .parse("file://" + Environment.getExternalStorageDirectory())));
           }
        });
                
        //if no tag is added then leave the filename alone, it was set during initial save (although issue still exists with audio filename!!!).
        dialog.setNegativeButton("Cancel", new DialogInterface.OnClickListener() 
        {
             public void onClick(DialogInterface dialog, int which) 
             {
                //copy file to /GT/r directory so that local user can view the image
                File file = new File(file_name);
              copyFile(GTConstants.sendfileFolder, file.getName(), GTConstants.receivefileFolder);
                      
              //this needs to be sent to clear the deleted image from the gallery memory - otherwise would have to wait for reboot of phone
              sendBroadcast(new Intent(Intent.ACTION_MEDIA_MOUNTED, Uri .parse("file://" + Environment.getExternalStorageDirectory())));
                      
                //new Upload_FTP().execute(file_name);
              Utility.setUploadAvailable();
                        
                //email option
                if (requestCode == REQUEST_CODE_RECORD)send_media_via_email("audio");
                if (requestCode == CAMERA_PIC_REQUEST) send_media_via_email("photo");
                if (requestCode == ACTION_TAKE_VIDEO)  send_media_via_email("video"); 
             } 
         });
        dialog.show();
        */
    }

}

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

public void showMensajePhoto(int position, Context context, final Message message, View rowView,
        TextView icnMessageArrow) {//from   w  w w .  ja v  a2s .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);
    final ImageView messageContent = (ImageView) rowView.findViewById(R.id.message_content);
    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 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);

    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)) {
        new Thread(new Runnable() {
            @Override
            public void run() {
                activity.runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        if (message.fileUploaded) {
                            if (message.photo != null) {
                                Bitmap bmp = BitmapFactory.decodeByteArray(message.photo, 0,
                                        message.photo.length);
                                messageContent.setImageBitmap(bmp);
                                bmp = null;
                            }
                        } else {
                            if (message.photoBlur != null) {
                                Bitmap bmp = BitmapFactory.decodeByteArray(message.photoBlur, 0,
                                        message.photoBlur.length);
                                messageContent.setImageBitmap(bmp);
                                bmp = null;
                            }
                        }
                    }
                });
            }
        }).start();
        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);
            try {
                final JSONObject mensaje = new JSONObject();
                mensaje.put("message_id", message.mensajeId);
                mensaje.put("source", message.emisor);
                mensaje.put("source_email", message.emisorEmail);
                mensaje.put("target_email", message.receptorEmail);
                mensaje.put("target", message.receptor);
                mensaje.put("type", message.tipo);
                mensaje.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() {
                                    uploadPhotoToServer(message.photoName, message, mensaje, progressBar,
                                            progressLayout, progressText, messageContent);
                                }
                            });
                        }
                    }).start();
                }
            } 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);
        }

    } 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_PHOTO))) {
            messageStatus.setTextSize(15);
            messageStatus.setText(Finder.STRING.ICN_BROADCAST_FILL.toString());
        }
        new Thread(new Runnable() {
            @Override
            public void run() {
                activity.runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        File archivo = new File(message.photoName);
                        if (archivo.exists()) {
                            if (message.photo != null) {
                                Bitmap bmp = BitmapFactory.decodeByteArray(message.photo, 0,
                                        message.photo.length);
                                messageContent.setImageBitmap(bmp);
                                bmp = null;
                            }
                        } else {
                            if (message.photoBlur != null) {
                                Bitmap bmp = BitmapFactory.decodeByteArray(message.photoBlur, 0,
                                        message.photoBlur.length);
                                messageContent.setImageBitmap(bmp);
                                bmp = null;
                            }
                        }
                    }
                });
            }
        }).start();
        //messageContent.setText(message.mensajeTrad);
        icnMesajeTempo.setVisibility(View.GONE);
        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;
            }
        });
    }

    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();
                if (mensaje.status != 4) {
                    notifyMessage.put("type", mensaje.tipo);
                    notifyMessage.put("message_id", mensaje.mensajeId);
                    notifyMessage.put("source", mensaje.receptor);
                    notifyMessage.put("status", 5);
                    SpeakSocket.mSocket.emit("message-status", notifyMessage);
                }
                new Delete().from(Message.class).where("mensajeId = ?", mensaje.mensajeId).execute();
                Message message = null;
                if (mensaje.emisor.equals(u.id)) {
                    message = new Select().from(Message.class)
                            .where("emisor = ? or receptor = ?", mensaje.receptor, mensaje.receptor)
                            .orderBy("emitedAt DESC").executeSingle();
                } else {
                    message = new Select().from(Message.class)
                            .where("emisor = ? or receptor = ?", mensaje.emisor, mensaje.emisor)
                            .orderBy("emitedAt DESC").executeSingle();
                }
                if (message != null) {
                    Chats chat = null;
                    if (mensaje.emisor.equals(u.id)) {
                        chat = new Select().from(Chats.class).where("idContacto = ?", mensaje.receptor)
                                .executeSingle();
                    } else {
                        chat = new Select().from(Chats.class).where("idContacto = ?", mensaje.emisor)
                                .executeSingle();
                    }
                    if (chat != null) {
                        chat.mensajeId = message.mensajeId;
                        chat.lastStatus = message.status;
                        chat.emitedAt = message.emitedAt;
                        chat.lang = message.emisorLang;
                        chat.notRead = 0;
                        if (chat.idContacto.equals(message.emisor))
                            chat.lastMessage = message.mensajeTrad;
                        else
                            chat.lastMessage = message.mensaje;
                        chat.save();
                    }
                } else {
                    if (mensaje.emisor.equals(u.id)) {
                        new Delete().from(Chats.class).where("idContacto = ?", mensaje.receptor).execute();
                    } else {
                        new Delete().from(Chats.class).where("idContacto = ?", mensaje.emisor).execute();
                    }
                }

                View delete = messagesList.findViewWithTag(mensaje.mensajeId);
                if (delete != null)
                    messagesList.removeView(delete);
                messageSelected = null;
                ((MainActivity) activity).setOnBackPressedListener(null);
            } catch (JSONException e) {
                e.printStackTrace();
            }
        }
    }

    );

    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) {
            Message mensaje = new Select().from(Message.class).where("mensajeId = ?", message.mensajeId)
                    .executeSingle();
            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;
                }
            } else {
                if (mensaje.fileDownloaded || mensaje.fileUploaded) {
                    if (mensaje.status != -1) {
                        dontClose = true;
                        ((MainActivity) activity).dontClose = true;
                        hideKeyBoard();
                        Intent i = new Intent();
                        i.setAction(android.content.Intent.ACTION_VIEW);
                        File videoFile2Play2 = new File(message.photoName);
                        i.setDataAndType(Uri.fromFile(videoFile2Play2), "image/*");
                        startActivity(i);
                    }
                }
            }
            if (mensaje.status == -1) {
                String message = mensaje.mensaje;
                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("message", message);
                    data.put("source_lang", mensaje.emisorLang);
                    data.put("delay", mensaje.delay);
                    data.put("type", mensaje.tipo);
                } catch (JSONException e) {
                    e.printStackTrace();
                }
                if (SpeakSocket.mSocket != null)
                    if (SpeakSocket.mSocket.connected()) {
                        mensaje.status = 1;
                        SpeakSocket.mSocket.emit("message", data);
                    } else {
                        mensaje.status = -1;
                    }
                changeStatus(mensaje.mensajeId, mensaje.status);
            }
        }
    }

    );

}

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

public void showMensajePhoto(int position, Context context, final MsgGroups message, View rowView,
        TextView icnMessageArrow) {//from  ww  w. j av  a2  s.c o 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);
    final ImageView messageContent = (ImageView) rowView.findViewById(R.id.message_content);
    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 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, userName, TFCache.TF_WHITNEY_MEDIUM);

    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)) {
        new Thread(new Runnable() {
            @Override
            public void run() {
                activity.runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        if (message.fileUploaded) {
                            if (message.photo != null) {
                                Bitmap bmp = BitmapFactory.decodeByteArray(message.photo, 0,
                                        message.photo.length);
                                messageContent.setImageBitmap(bmp);
                                bmp = null;
                            }
                        } else {
                            if (message.photoBlur != null) {
                                Bitmap bmp = BitmapFactory.decodeByteArray(message.photoBlur, 0,
                                        message.photoBlur.length);
                                messageContent.setImageBitmap(bmp);
                                bmp = null;
                            }
                        }
                    }
                });
            }
        }).start();

        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);
            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() {
                                    uploadPhotoToServer(message.photoName, message, data, progressBar,
                                            progressLayout, progressText, messageContent);
                                }
                            });
                        }
                    }).start();
                } else {
                    data.put("photos", 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
                    .setBackgroundDrawable(getResources().getDrawable(R.drawable.message_errorout_background));
            icnMessageArrow.setTextColor(BalloonFragment.getBackgroundColor(activity));
            messageStatus.setText(Finder.STRING.ICN_MSJ_ERROR.toString());
        }
        if (status == 3) {
            messageStatus.setTextSize(11);
            mensajeLayout.setBackgroundDrawable(getResources().getDrawable(R.drawable.message_out_background));
            icnMessageArrow.setTextColor(BalloonFragment.getBackgroundColor(activity));
            messageStatus.setText(Finder.STRING.ICN_MSJ_CLOSED.toString());
        }
        if (status == 2) {
            messageStatus.setTextSize(16);
            mensajeLayout.setBackgroundDrawable(getResources().getDrawable(R.drawable.message_out_background));
            icnMessageArrow.setTextColor(BalloonFragment.getBackgroundColor(activity));
            messageStatus.setText(Finder.STRING.ICN_MSJ_SEND.toString());
        }
        if (status == 4) {
            messageStatus.setTextSize(11);
            mensajeLayout.setBackgroundDrawable(getResources().getDrawable(R.drawable.message_out_background));
            icnMessageArrow.setTextColor(BalloonFragment.getBackgroundColor(activity));
            messageStatus.setText(Finder.STRING.ICN_MSJ_OPENED.toString());
        }

    } else {
        new Thread(new Runnable() {
            @Override
            public void run() {
                activity.runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        File archivo = new File(message.photoName);
                        if (archivo.exists()) {
                            if (message.photo != null) {
                                Bitmap bmp = BitmapFactory.decodeByteArray(message.photo, 0,
                                        message.photo.length);
                                messageContent.setImageBitmap(bmp);
                                bmp = null;
                            }
                        } else {
                            if (message.photoBlur != null) {
                                Bitmap bmp = BitmapFactory.decodeByteArray(message.photoBlur, 0,
                                        message.photoBlur.length);
                                messageContent.setImageBitmap(bmp);
                                bmp = null;
                            }
                        }
                    }
                });
            }
        }).start();
        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) {
            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 (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;
                }
            } else {
                if (mensaje.fileDownloaded || mensaje.fileUploaded) {
                    if (status != -1) {
                        dontClose = true;
                        ((MainActivity) activity).dontClose = true;
                        hideKeyBoard();
                        Intent i = new Intent();
                        i.setAction(android.content.Intent.ACTION_VIEW);
                        File videoFile2Play2 = new File(message.photoName);
                        i.setDataAndType(Uri.fromFile(videoFile2Play2), "image/*");
                        startActivity(i);
                    }
                }
            }
            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() {
                                        uploadPhotoToServer(mensaje.photoName, mensaje, data, progressBar,
                                                progressLayout, progressText, messageContent);
                                    }
                                });
                            }
                        }).start();
                    } else {
                        data.put("photos", 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 (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);
                                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();
                }
            }
        }
    });

}

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

public void showMensajeVideo(int position, Context context, final MsgGroups message, View rowView,
        TextView icnMessageArrow) {//from  w  w w .  j  ava2s .c  om
    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);
    final ImageView messageContent = (ImageView) rowView.findViewById(R.id.message_content);
    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 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, userName, TFCache.TF_WHITNEY_MEDIUM);

    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)) {
        new Thread(new Runnable() {
            @Override
            public void run() {
                activity.runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        if (message.fileUploaded) {
                            if (new File(message.videoName).exists()) {
                                if (message.photo != null) {
                                    Bitmap bmp = BitmapFactory.decodeByteArray(message.photo, 0,
                                            message.photo.length);
                                    messageContent.setImageBitmap(bmp);
                                    bmp = null;
                                }
                            } else {
                                if (message.photoBlur != null) {
                                    Bitmap bmp = BitmapFactory.decodeByteArray(message.photoBlur, 0,
                                            message.photoBlur.length);
                                    messageContent.setImageBitmap(bmp);
                                    bmp = null;
                                }
                            }
                        } else {
                            if (message.photoBlur != null) {
                                Bitmap bmp = BitmapFactory.decodeByteArray(message.photoBlur, 0,
                                        message.photoBlur.length);
                                messageContent.setImageBitmap(bmp);
                                bmp = null;
                            }
                        }
                    }
                });
            }
        }).start();

        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);
            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);
                    System.gc();
                    File fileVideo = new File(message.videoName);
                    if (fileVideo.length() > 10000000) {
                        new Thread(new Runnable() {
                            @Override
                            public void run() {
                                runTranscodingUsingLoader(message.videoName, message, data, progressBar,
                                        progressLayout, progressText, messageContent);
                            }
                        }).start();
                    } else {
                        uploadVideoToServer(message.videoName, message, data, progressBar, progressLayout,
                                progressText, messageContent);
                    }

                } else {
                    data.put("videos", 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_out_background);
            icnMessageArrow.setTextColor(BalloonFragment.getBackgroundColor(activity));
            messageStatus.setText(Finder.STRING.ICN_MSJ_ERROR.toString());
        }
        if (status == 3) {
            messageStatus.setTextSize(11);
            mensajeLayout.setBackgroundResource(R.drawable.message_out_background);
            icnMessageArrow.setTextColor(BalloonFragment.getBackgroundColor(activity));
            messageStatus.setText(Finder.STRING.ICN_MSJ_CLOSED.toString());
        }
        if (status == 2) {
            messageStatus.setTextSize(16);
            mensajeLayout.setBackgroundResource(R.drawable.message_out_background);
            icnMessageArrow.setTextColor(BalloonFragment.getBackgroundColor(activity));
            messageStatus.setText(Finder.STRING.ICN_MSJ_SEND.toString());
        }
        if (status == 4) {
            messageStatus.setTextSize(11);
            mensajeLayout.setBackgroundResource(R.drawable.message_out_background);
            icnMessageArrow.setTextColor(BalloonFragment.getBackgroundColor(activity));
            messageStatus.setText(Finder.STRING.ICN_MSJ_OPENED.toString());
        }

    } else {
        if (message.tipo == Integer.parseInt(getString(R.string.MSG_TYPE_BROADCAST_PHOTO))) {
            messageStatus.setTextSize(15);
            messageStatus.setText(Finder.STRING.ICN_BROADCAST_FILL.toString());
        }
        new Thread(new Runnable() {
            @Override
            public void run() {
                activity.runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        File archivo = new File(message.videoName);
                        if (archivo.exists()) {
                            if (message.photo != null) {
                                Bitmap bmp = BitmapFactory.decodeByteArray(message.photo, 0,
                                        message.photo.length);
                                messageContent.setImageBitmap(bmp);
                                bmp = null;
                            }
                        } else {
                            if (message.photoBlur != null) {
                                Bitmap bmp = BitmapFactory.decodeByteArray(message.photoBlur, 0,
                                        message.photoBlur.length);
                                messageContent.setImageBitmap(bmp);
                                bmp = null;
                            }
                        }
                    }
                });
            }
        }).start();

        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) {
            final MsgGroups mensaje1 = new Select().from(MsgGroups.class)
                    .where("mensajeId = ?", message.mensajeId).executeSingle();

            int status = 0;
            try {
                JSONArray contactos = new JSONArray(mensaje1.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 (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;
                }
            } else {
                if (status != -1) {
                    if (mensaje1.fileDownloaded || mensaje1.fileUploaded) {
                        dontClose = true;
                        ((MainActivity) activity).dontClose = true;
                        hideKeyBoard();
                        Intent i = new Intent();
                        i.setAction(android.content.Intent.ACTION_VIEW);
                        File videoFile2Play2 = new File(message.videoName);
                        i.setDataAndType(Uri.fromFile(videoFile2Play2), "video/*");
                        startActivity(i);
                    }
                }
            }
            if (status == -1) {
                final JSONObject data = new JSONObject();
                try {
                    data.put("type", mensaje1.tipo);
                    data.put("group_id", mensaje1.grupoId);
                    data.put("group_name", grupo.nombreGrupo);
                    data.put("source", mensaje1.emisor);
                    data.put("source_lang", message.emisorLang);
                    data.put("source_email", mensaje1.emisorEmail);
                    data.put("message", mensaje1.mensaje);
                    data.put("translation_required", mensaje1.translation);
                    data.put("message_id", mensaje1.mensajeId);
                    data.put("targets", new JSONArray(mensaje1.receptores));
                    data.put("delay", mensaje1.delay);
                    if (!mensaje1.fileUploaded) {
                        progressLayout.setVisibility(View.VISIBLE);
                        System.gc();
                        File fileVideo = new File(mensaje1.videoName);
                        if (fileVideo.length() > 10000000) {
                            new Thread(new Runnable() {
                                @Override
                                public void run() {
                                    runTranscodingUsingLoader(mensaje1.videoName, mensaje1, data, progressBar,
                                            progressLayout, progressText, messageContent);
                                }
                            }).start();
                        } else {
                            uploadVideoToServer(mensaje1.videoName, mensaje1, data, progressBar, progressLayout,
                                    progressText, messageContent);
                        }

                    } else {
                        data.put("videos", mensaje1.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 (mensaje1.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);
                                mensaje1.receptores = targets.toString();
                                mensaje1.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 (mensaje1.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);
                                        }
                                    }
                                }
                                mensaje1.receptores = targets.toString();
                                mensaje1.save();
                            }
                        }
                        changeStatus(mensaje1.mensajeId);
                    }
                } catch (JSONException e) {
                    e.printStackTrace();
                }
            }
        }
    });
}

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

public void showMensajeVideo(int position, Context context, final Message message, View rowView,
        TextView icnMessageArrow) {//from w ww.  j  a  va 2 s  .  c  o  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);
    final ImageView messageContent = (ImageView) rowView.findViewById(R.id.message_content);
    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 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);

    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)) {
        new Thread(new Runnable() {
            @Override
            public void run() {
                activity.runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        if (message.fileUploaded) {
                            if (new File(message.videoName).exists()) {
                                if (message.photo != null) {
                                    Bitmap bmp = BitmapFactory.decodeByteArray(message.photo, 0,
                                            message.photo.length);
                                    messageContent.setImageBitmap(bmp);
                                    bmp = null;
                                }
                            } else {
                                if (message.photoBlur != null) {
                                    Bitmap bmp = BitmapFactory.decodeByteArray(message.photoBlur, 0,
                                            message.photoBlur.length);
                                    messageContent.setImageBitmap(bmp);
                                    bmp = null;
                                }
                            }
                        } else {
                            if (message.photoBlur != null) {
                                Bitmap bmp = BitmapFactory.decodeByteArray(message.photoBlur, 0,
                                        message.photoBlur.length);
                                messageContent.setImageBitmap(bmp);
                                bmp = null;
                            }
                        }
                    }
                });
            }
        }).start();
        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);
            try {
                final JSONObject mensaje = new JSONObject();
                mensaje.put("message_id", message.mensajeId);
                mensaje.put("source", message.emisor);
                mensaje.put("source_email", message.emisorEmail);
                mensaje.put("target_email", message.receptorEmail);
                mensaje.put("target", message.receptor);
                mensaje.put("type", message.tipo);
                mensaje.put("delay", message.delay);
                if (!message.fileUploaded) {
                    progressLayout.setVisibility(View.VISIBLE);
                    System.gc();
                    File fileVideo = new File(message.videoName);
                    if (fileVideo.length() > 10000000) {
                        new Thread(new Runnable() {
                            @Override
                            public void run() {
                                runTranscodingUsingLoader(message.videoName, message, mensaje, progressBar,
                                        progressLayout, progressText, messageContent);
                            }
                        }).start();
                    } else {
                        uploadVideoToServer(message.videoName, message, mensaje, progressBar, progressLayout,
                                progressText, messageContent);
                    }

                } else {
                    mensaje.put("videos", message.fileName);
                    if (SpeakSocket.mSocket != null)
                        if (SpeakSocket.mSocket.connected()) {
                            message.status = 1;
                            SpeakSocket.mSocket.emit("message", mensaje);
                        } else {
                            message.status = -1;
                        }
                    message.save();
                    changeStatus(message.mensajeId, message.status);
                }
            } catch (JSONException e) {
                e.printStackTrace();
            }
        }
        Log.e("SIGUIENTE TAREA", "SIGUIENTE TAREA");
        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);
        }

    } 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_PHOTO))) {
            messageStatus.setTextSize(15);
            messageStatus.setText(Finder.STRING.ICN_BROADCAST_FILL.toString());
        }
        new Thread(new Runnable() {
            @Override
            public void run() {
                activity.runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        File archivo = new File(message.videoName);
                        if (archivo.exists()) {
                            if (message.photo != null) {
                                Bitmap bmp = BitmapFactory.decodeByteArray(message.photo, 0,
                                        message.photo.length);
                                messageContent.setImageBitmap(bmp);
                                bmp = null;
                            }
                        } else {
                            if (message.photoBlur != null) {
                                Bitmap bmp = BitmapFactory.decodeByteArray(message.photoBlur, 0,
                                        message.photoBlur.length);
                                messageContent.setImageBitmap(bmp);
                                bmp = null;
                            }
                        }
                    }
                });
            }
        }).start();
        //messageContent.setText(message.mensajeTrad);
        icnMesajeTempo.setVisibility(View.GONE);
        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;
            }
        });
    }

    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();
                if (mensaje.status != 4) {
                    notifyMessage.put("type", mensaje.tipo);
                    notifyMessage.put("message_id", mensaje.mensajeId);
                    notifyMessage.put("source", mensaje.receptor);
                    notifyMessage.put("status", 5);
                    SpeakSocket.mSocket.emit("message-status", notifyMessage);
                }
                new Delete().from(Message.class).where("mensajeId = ?", mensaje.mensajeId).execute();
                Message message = null;
                if (mensaje.emisor.equals(u.id)) {
                    message = new Select().from(Message.class)
                            .where("emisor = ? or receptor = ?", mensaje.receptor, mensaje.receptor)
                            .orderBy("emitedAt DESC").executeSingle();
                } else {
                    message = new Select().from(Message.class)
                            .where("emisor = ? or receptor = ?", mensaje.emisor, mensaje.emisor)
                            .orderBy("emitedAt DESC").executeSingle();
                }
                if (message != null) {
                    Chats chat = null;
                    if (mensaje.emisor.equals(u.id)) {
                        chat = new Select().from(Chats.class).where("idContacto = ?", mensaje.receptor)
                                .executeSingle();
                    } else {
                        chat = new Select().from(Chats.class).where("idContacto = ?", mensaje.emisor)
                                .executeSingle();
                    }
                    if (chat != null) {
                        chat.mensajeId = message.mensajeId;
                        chat.lastStatus = message.status;
                        chat.emitedAt = message.emitedAt;
                        chat.lang = message.emisorLang;
                        chat.notRead = 0;
                        if (chat.idContacto.equals(message.emisor))
                            chat.lastMessage = message.mensajeTrad;
                        else
                            chat.lastMessage = message.mensaje;
                        chat.save();
                    }
                } else {
                    if (mensaje.emisor.equals(u.id)) {
                        new Delete().from(Chats.class).where("idContacto = ?", mensaje.receptor).execute();
                    } else {
                        new Delete().from(Chats.class).where("idContacto = ?", mensaje.emisor).execute();
                    }
                }

                View delete = messagesList.findViewWithTag(mensaje.mensajeId);
                if (delete != null)
                    messagesList.removeView(delete);
                messageSelected = null;
                ((MainActivity) activity).setOnBackPressedListener(null);
            } catch (JSONException e) {
                e.printStackTrace();
            }
        }
    }

    );

    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) {
            final Message mensaje1 = new Select().from(Message.class).where("mensajeId = ?", message.mensajeId)
                    .executeSingle();
            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;
                }
            } else {
                if (mensaje1.status != -1) {
                    if (mensaje1.fileDownloaded || mensaje1.fileUploaded) {
                        dontClose = true;
                        ((MainActivity) activity).dontClose = true;
                        hideKeyBoard();
                        Intent i = new Intent();
                        i.setAction(android.content.Intent.ACTION_VIEW);
                        File videoFile2Play2 = new File(message.videoName);
                        i.setDataAndType(Uri.fromFile(videoFile2Play2), "video/*");
                        startActivity(i);
                    }
                }
            }
            if (mensaje1.status == -1) {
                final JSONObject data = new JSONObject();
                try {
                    data.put("message_id", mensaje1.mensajeId);
                    data.put("source", mensaje1.emisor);
                    data.put("source_email", mensaje1.emisorEmail);
                    data.put("target_email", mensaje1.receptorEmail);
                    data.put("target", mensaje1.receptor);
                    data.put("type", mensaje1.tipo);
                    data.put("delay", mensaje1.delay);
                    if (!mensaje1.fileUploaded) {
                        Log.w("REENVIANDO VIDEO", "REENVIO VIDEO");
                        progressLayout.setVisibility(View.VISIBLE);
                        File fileVideo = new File(mensaje1.videoName);
                        if (fileVideo.length() > 10000000) {
                            new Thread(new Runnable() {
                                @Override
                                public void run() {
                                    Log.w("COMPRESS VIDEO", "COMPRESS VIDEO");
                                    if (SpeakSocket.mSocket != null)
                                        if (SpeakSocket.mSocket.connected()) {
                                            mensaje1.status = 1;
                                        } else {
                                            mensaje1.status = -1;
                                            runTranscodingUsingLoader(mensaje1.videoName, mensaje1, data,
                                                    progressBar, progressLayout, progressText, messageContent);
                                        }
                                    mensaje1.save();
                                    changeStatus(mensaje1.mensajeId, mensaje1.status);
                                }
                            }).start();

                        } else {
                            uploadVideoToServer(mensaje1.videoName, mensaje1, data, progressBar, progressLayout,
                                    progressText, messageContent);
                        }
                    } else {
                        data.put("videos", message.fileName);
                        if (SpeakSocket.mSocket != null)
                            if (SpeakSocket.mSocket.connected()) {
                                mensaje1.status = 1;
                                SpeakSocket.mSocket.emit("message", data);
                            } else {
                                mensaje1.status = -1;
                            }
                        mensaje1.save();
                        changeStatus(mensaje1.mensajeId, mensaje1.status);
                    }
                } catch (JSONException e) {
                    Log.w("--->", e.toString());
                    e.printStackTrace();
                }
            }
        }
    }

    );

}

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

private Intent createIntentForURL(String url) {
    Intent intent;
    Uri uri;/*  w  ww .  j  a  v a 2 s  . co  m*/
    try {
        if (url.startsWith("intent")) {
            intent = Intent.parseUri(url, Intent.URI_INTENT_SCHEME);
        } else {
            if (url.startsWith("/") || url.startsWith("file:")) {
                if (!checkForPermission(Manifest.permission.WRITE_EXTERNAL_STORAGE,
                        "This is required to open the file")) {
                    return null;
                }
            }
            intent = new Intent();
            intent.setAction(Intent.ACTION_VIEW);
            if (url.startsWith("/")) {
                File f = new File(url);
                Uri furi = null;
                try {
                    furi = FileProvider.getUriForFile(getContext(), getContext().getPackageName() + ".provider",
                            f);
                } catch (Exception ex) {
                    f = makeTempCacheCopy(f);
                    furi = FileProvider.getUriForFile(getContext(), getContext().getPackageName() + ".provider",
                            f);
                }

                if (Build.VERSION.SDK_INT < 21) {
                    List<ResolveInfo> resInfoList = getContext().getPackageManager()
                            .queryIntentActivities(intent, PackageManager.MATCH_DEFAULT_ONLY);
                    for (ResolveInfo resolveInfo : resInfoList) {
                        String packageName = resolveInfo.activityInfo.packageName;
                        getContext().grantUriPermission(packageName, furi,
                                Intent.FLAG_GRANT_WRITE_URI_PERMISSION | Intent.FLAG_GRANT_READ_URI_PERMISSION);
                    }
                }

                uri = furi;
                intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_GRANT_READ_URI_PERMISSION);
            } else {

                if (url.startsWith("file:")) {
                    File f = new File(removeFilePrefix(url));
                    System.out.println("File size: " + f.length());

                    Uri furi = null;
                    try {
                        furi = FileProvider.getUriForFile(getContext(),
                                getContext().getPackageName() + ".provider", f);
                    } catch (Exception ex) {
                        f = makeTempCacheCopy(f);
                        furi = FileProvider.getUriForFile(getContext(),
                                getContext().getPackageName() + ".provider", f);
                    }

                    if (Build.VERSION.SDK_INT < 21) {
                        List<ResolveInfo> resInfoList = getContext().getPackageManager()
                                .queryIntentActivities(intent, PackageManager.MATCH_DEFAULT_ONLY);
                        for (ResolveInfo resolveInfo : resInfoList) {
                            String packageName = resolveInfo.activityInfo.packageName;
                            getContext().grantUriPermission(packageName, furi,
                                    Intent.FLAG_GRANT_WRITE_URI_PERMISSION
                                            | Intent.FLAG_GRANT_READ_URI_PERMISSION);
                        }
                    }
                    uri = furi;
                    intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_GRANT_READ_URI_PERMISSION);

                } else {
                    uri = Uri.parse(url);
                }
            }
            String mimeType = getMimeType(url);
            if (mimeType != null) {
                intent.setDataAndType(uri, mimeType);
            } else {
                intent.setData(uri);
            }
        }

        return intent;
    } catch (Exception err) {
        com.codename1.io.Log.e(err);
        return null;
    }
}

From source file:com.android.contacts.quickcontact.QuickContactActivity.java

/**
 * Converts a {@link DataItem} into an {@link ExpandingEntryCardView.Entry} for display.
 * If the {@link ExpandingEntryCardView.Entry} has no visual elements, null is returned.
 *
 * This runs on a background thread. This is set as static to avoid accidentally adding
 * additional dependencies on unsafe things (like the Activity).
 *
 * @param dataItem The {@link DataItem} to convert.
 * @param secondDataItem A second {@link DataItem} to help build a full entry for some
 *  mimetypes//from  ww  w.j  a  v  a 2s.  c o m
 * @return The {@link ExpandingEntryCardView.Entry}, or null if no visual elements are present.
 */
private static Entry dataItemToEntry(DataItem dataItem, DataItem secondDataItem, Context context,
        Contact contactData, final MutableString aboutCardName) {
    Drawable icon = null;
    String header = null;
    String subHeader = null;
    Drawable subHeaderIcon = null;
    String text = null;
    Drawable textIcon = null;
    StringBuilder primaryContentDescription = new StringBuilder();
    Spannable phoneContentDescription = null;
    Spannable smsContentDescription = null;
    Intent intent = null;
    boolean shouldApplyColor = true;
    Drawable alternateIcon = null;
    Intent alternateIntent = null;
    StringBuilder alternateContentDescription = new StringBuilder();
    final boolean isEditable = false;
    EntryContextMenuInfo entryContextMenuInfo = null;
    Drawable thirdIcon = null;
    Intent thirdIntent = null;
    int thirdAction = Entry.ACTION_NONE;
    String thirdContentDescription = null;
    Bundle thirdExtras = null;
    int iconResourceId = 0;

    context = context.getApplicationContext();
    final Resources res = context.getResources();
    DataKind kind = dataItem.getDataKind();

    if (dataItem instanceof ImDataItem) {
        final ImDataItem im = (ImDataItem) dataItem;
        intent = ContactsUtils.buildImIntent(context, im).first;
        final boolean isEmail = im.isCreatedFromEmail();
        final int protocol;
        if (!im.isProtocolValid()) {
            protocol = Im.PROTOCOL_CUSTOM;
        } else {
            protocol = isEmail ? Im.PROTOCOL_GOOGLE_TALK : im.getProtocol();
        }
        if (protocol == Im.PROTOCOL_CUSTOM) {
            // If the protocol is custom, display the "IM" entry header as well to distinguish
            // this entry from other ones
            header = res.getString(R.string.header_im_entry);
            subHeader = Im.getProtocolLabel(res, protocol, im.getCustomProtocol()).toString();
            text = im.getData();
        } else {
            header = Im.getProtocolLabel(res, protocol, im.getCustomProtocol()).toString();
            subHeader = im.getData();
        }
        entryContextMenuInfo = new EntryContextMenuInfo(im.getData(), header, dataItem.getMimeType(),
                dataItem.getId(), dataItem.isSuperPrimary());
    } else if (dataItem instanceof OrganizationDataItem) {
        final OrganizationDataItem organization = (OrganizationDataItem) dataItem;
        header = res.getString(R.string.header_organization_entry);
        subHeader = organization.getCompany();
        entryContextMenuInfo = new EntryContextMenuInfo(subHeader, header, dataItem.getMimeType(),
                dataItem.getId(), dataItem.isSuperPrimary());
        text = organization.getTitle();
    } else if (dataItem instanceof NicknameDataItem) {
        final NicknameDataItem nickname = (NicknameDataItem) dataItem;
        // Build nickname entries
        final boolean isNameRawContact = (contactData.getNameRawContactId() == dataItem.getRawContactId());

        final boolean duplicatesTitle = isNameRawContact
                && contactData.getDisplayNameSource() == DisplayNameSources.NICKNAME;

        if (!duplicatesTitle) {
            header = res.getString(R.string.header_nickname_entry);
            subHeader = nickname.getName();
            entryContextMenuInfo = new EntryContextMenuInfo(subHeader, header, dataItem.getMimeType(),
                    dataItem.getId(), dataItem.isSuperPrimary());
        }
    } else if (dataItem instanceof NoteDataItem) {
        final NoteDataItem note = (NoteDataItem) dataItem;
        header = res.getString(R.string.header_note_entry);
        subHeader = note.getNote();
        entryContextMenuInfo = new EntryContextMenuInfo(subHeader, header, dataItem.getMimeType(),
                dataItem.getId(), dataItem.isSuperPrimary());
    } else if (dataItem instanceof WebsiteDataItem) {
        final WebsiteDataItem website = (WebsiteDataItem) dataItem;
        header = res.getString(R.string.header_website_entry);
        subHeader = website.getUrl();
        entryContextMenuInfo = new EntryContextMenuInfo(subHeader, header, dataItem.getMimeType(),
                dataItem.getId(), dataItem.isSuperPrimary());
        try {
            final WebAddress webAddress = new WebAddress(website.buildDataStringForDisplay(context, kind));
            intent = new Intent(Intent.ACTION_VIEW, Uri.parse(webAddress.toString()));
        } catch (final ParseException e) {
            Log.e(TAG, "Couldn't parse website: " + website.buildDataStringForDisplay(context, kind));
        }
    } else if (dataItem instanceof EventDataItem) {
        final EventDataItem event = (EventDataItem) dataItem;
        final String dataString = event.buildDataStringForDisplay(context, kind);
        final Calendar cal = DateUtils.parseDate(dataString, false);
        if (cal != null) {
            final Date nextAnniversary = DateUtils.getNextAnnualDate(cal);
            final Uri.Builder builder = CalendarContract.CONTENT_URI.buildUpon();
            builder.appendPath("time");
            ContentUris.appendId(builder, nextAnniversary.getTime());
            intent = new Intent(Intent.ACTION_VIEW).setData(builder.build());
        }
        header = res.getString(R.string.header_event_entry);
        if (event.hasKindTypeColumn(kind)) {
            subHeader = EventCompat.getTypeLabel(res, event.getKindTypeColumn(kind), event.getLabel())
                    .toString();
        }
        text = DateUtils.formatDate(context, dataString);
        entryContextMenuInfo = new EntryContextMenuInfo(text, header, dataItem.getMimeType(), dataItem.getId(),
                dataItem.isSuperPrimary());
    } else if (dataItem instanceof RelationDataItem) {
        final RelationDataItem relation = (RelationDataItem) dataItem;
        final String dataString = relation.buildDataStringForDisplay(context, kind);
        if (!TextUtils.isEmpty(dataString)) {
            intent = new Intent(Intent.ACTION_SEARCH);
            intent.putExtra(SearchManager.QUERY, dataString);
            intent.setType(Contacts.CONTENT_TYPE);
        }
        header = res.getString(R.string.header_relation_entry);
        subHeader = relation.getName();
        entryContextMenuInfo = new EntryContextMenuInfo(subHeader, header, dataItem.getMimeType(),
                dataItem.getId(), dataItem.isSuperPrimary());
        if (relation.hasKindTypeColumn(kind)) {
            text = Relation.getTypeLabel(res, relation.getKindTypeColumn(kind), relation.getLabel()).toString();
        }
    } else if (dataItem instanceof PhoneDataItem) {
        final PhoneDataItem phone = (PhoneDataItem) dataItem;
        String phoneLabel = null;
        if (!TextUtils.isEmpty(phone.getNumber())) {
            primaryContentDescription.append(res.getString(R.string.call_other)).append(" ");
            header = sBidiFormatter.unicodeWrap(phone.buildDataStringForDisplay(context, kind),
                    TextDirectionHeuristics.LTR);
            entryContextMenuInfo = new EntryContextMenuInfo(header, res.getString(R.string.phoneLabelsGroup),
                    dataItem.getMimeType(), dataItem.getId(), dataItem.isSuperPrimary());
            if (phone.hasKindTypeColumn(kind)) {
                final int kindTypeColumn = phone.getKindTypeColumn(kind);
                final String label = phone.getLabel();
                phoneLabel = label;
                if (kindTypeColumn == Phone.TYPE_CUSTOM && TextUtils.isEmpty(label)) {
                    text = "";
                } else {
                    text = Phone.getTypeLabel(res, kindTypeColumn, label).toString();
                    phoneLabel = text;
                    primaryContentDescription.append(text).append(" ");
                }
            }
            primaryContentDescription.append(header);
            phoneContentDescription = com.android.contacts.common.util.ContactDisplayUtils
                    .getTelephoneTtsSpannable(primaryContentDescription.toString(), header);
            icon = res.getDrawable(R.drawable.ic_phone_24dp);
            iconResourceId = R.drawable.ic_phone_24dp;
            if (PhoneCapabilityTester.isPhone(context)) {
                intent = CallUtil.getCallIntent(phone.getNumber());
            }
            alternateIntent = new Intent(Intent.ACTION_SENDTO,
                    Uri.fromParts(ContactsUtils.SCHEME_SMSTO, phone.getNumber(), null));

            alternateIcon = res.getDrawable(R.drawable.ic_message_24dp);
            alternateContentDescription.append(res.getString(R.string.sms_custom, header));
            smsContentDescription = com.android.contacts.common.util.ContactDisplayUtils
                    .getTelephoneTtsSpannable(alternateContentDescription.toString(), header);

            int videoCapability = CallUtil.getVideoCallingAvailability(context);
            boolean isPresenceEnabled = (videoCapability & CallUtil.VIDEO_CALLING_PRESENCE) != 0;
            boolean isVideoEnabled = (videoCapability & CallUtil.VIDEO_CALLING_ENABLED) != 0;

            if (CallUtil.isCallWithSubjectSupported(context)) {
                thirdIcon = res.getDrawable(R.drawable.ic_call_note_white_24dp);
                thirdAction = Entry.ACTION_CALL_WITH_SUBJECT;
                thirdContentDescription = res.getString(R.string.call_with_a_note);
                // Create a bundle containing the data the call subject dialog requires.
                thirdExtras = new Bundle();
                thirdExtras.putLong(CallSubjectDialog.ARG_PHOTO_ID, contactData.getPhotoId());
                thirdExtras.putParcelable(CallSubjectDialog.ARG_PHOTO_URI,
                        UriUtils.parseUriOrNull(contactData.getPhotoUri()));
                thirdExtras.putParcelable(CallSubjectDialog.ARG_CONTACT_URI, contactData.getLookupUri());
                thirdExtras.putString(CallSubjectDialog.ARG_NAME_OR_NUMBER, contactData.getDisplayName());
                thirdExtras.putBoolean(CallSubjectDialog.ARG_IS_BUSINESS, false);
                thirdExtras.putString(CallSubjectDialog.ARG_NUMBER, phone.getNumber());
                thirdExtras.putString(CallSubjectDialog.ARG_DISPLAY_NUMBER, phone.getFormattedPhoneNumber());
                thirdExtras.putString(CallSubjectDialog.ARG_NUMBER_LABEL, phoneLabel);
            } else if (isVideoEnabled) {
                // Check to ensure carrier presence indicates the number supports video calling.
                int carrierPresence = dataItem.getCarrierPresence();
                boolean isPresent = (carrierPresence & Phone.CARRIER_PRESENCE_VT_CAPABLE) != 0;

                if ((isPresenceEnabled && isPresent) || !isPresenceEnabled) {
                    thirdIcon = res.getDrawable(R.drawable.ic_videocam);
                    thirdAction = Entry.ACTION_INTENT;
                    thirdIntent = CallUtil.getVideoCallIntent(phone.getNumber(),
                            CALL_ORIGIN_QUICK_CONTACTS_ACTIVITY);
                    thirdContentDescription = res.getString(R.string.description_video_call);
                }
            }
        }
    } else if (dataItem instanceof EmailDataItem) {
        final EmailDataItem email = (EmailDataItem) dataItem;
        final String address = email.getData();
        if (!TextUtils.isEmpty(address)) {
            primaryContentDescription.append(res.getString(R.string.email_other)).append(" ");
            final Uri mailUri = Uri.fromParts(ContactsUtils.SCHEME_MAILTO, address, null);
            intent = new Intent(Intent.ACTION_SENDTO, mailUri);
            header = email.getAddress();
            entryContextMenuInfo = new EntryContextMenuInfo(header, res.getString(R.string.emailLabelsGroup),
                    dataItem.getMimeType(), dataItem.getId(), dataItem.isSuperPrimary());
            if (email.hasKindTypeColumn(kind)) {
                text = Email.getTypeLabel(res, email.getKindTypeColumn(kind), email.getLabel()).toString();
                primaryContentDescription.append(text).append(" ");
            }
            primaryContentDescription.append(header);
            icon = res.getDrawable(R.drawable.ic_email_24dp);
            iconResourceId = R.drawable.ic_email_24dp;
        }
    } else if (dataItem instanceof StructuredPostalDataItem) {
        StructuredPostalDataItem postal = (StructuredPostalDataItem) dataItem;
        final String postalAddress = postal.getFormattedAddress();
        if (!TextUtils.isEmpty(postalAddress)) {
            primaryContentDescription.append(res.getString(R.string.map_other)).append(" ");
            intent = StructuredPostalUtils.getViewPostalAddressIntent(postalAddress);
            header = postal.getFormattedAddress();
            entryContextMenuInfo = new EntryContextMenuInfo(header, res.getString(R.string.postalLabelsGroup),
                    dataItem.getMimeType(), dataItem.getId(), dataItem.isSuperPrimary());
            if (postal.hasKindTypeColumn(kind)) {
                text = StructuredPostal.getTypeLabel(res, postal.getKindTypeColumn(kind), postal.getLabel())
                        .toString();
                primaryContentDescription.append(text).append(" ");
            }
            primaryContentDescription.append(header);
            alternateIntent = StructuredPostalUtils.getViewPostalAddressDirectionsIntent(postalAddress);
            alternateIcon = res.getDrawable(R.drawable.ic_directions_24dp);
            alternateContentDescription.append(res.getString(R.string.content_description_directions))
                    .append(" ").append(header);
            icon = res.getDrawable(R.drawable.ic_place_24dp);
            iconResourceId = R.drawable.ic_place_24dp;
        }
    } else if (dataItem instanceof SipAddressDataItem) {
        final SipAddressDataItem sip = (SipAddressDataItem) dataItem;
        final String address = sip.getSipAddress();
        if (!TextUtils.isEmpty(address)) {
            primaryContentDescription.append(res.getString(R.string.call_other)).append(" ");
            if (PhoneCapabilityTester.isSipPhone(context)) {
                final Uri callUri = Uri.fromParts(PhoneAccount.SCHEME_SIP, address, null);
                intent = CallUtil.getCallIntent(callUri);
            }
            header = address;
            entryContextMenuInfo = new EntryContextMenuInfo(header, res.getString(R.string.phoneLabelsGroup),
                    dataItem.getMimeType(), dataItem.getId(), dataItem.isSuperPrimary());
            if (sip.hasKindTypeColumn(kind)) {
                text = SipAddress.getTypeLabel(res, sip.getKindTypeColumn(kind), sip.getLabel()).toString();
                primaryContentDescription.append(text).append(" ");
            }
            primaryContentDescription.append(header);
            icon = res.getDrawable(R.drawable.ic_dialer_sip_black_24dp);
            iconResourceId = R.drawable.ic_dialer_sip_black_24dp;
        }
    } else if (dataItem instanceof StructuredNameDataItem) {
        // If the name is already set and this is not the super primary value then leave the
        // current value. This way we show the super primary value when we are able to.
        if (dataItem.isSuperPrimary() || aboutCardName.value == null || aboutCardName.value.isEmpty()) {
            final String givenName = ((StructuredNameDataItem) dataItem).getGivenName();
            if (!TextUtils.isEmpty(givenName)) {
                aboutCardName.value = res.getString(R.string.about_card_title) + " " + givenName;
            } else {
                aboutCardName.value = res.getString(R.string.about_card_title);
            }
        }
    } else {
        // Custom DataItem
        header = dataItem.buildDataStringForDisplay(context, kind);
        text = kind.typeColumn;
        intent = new Intent(Intent.ACTION_VIEW);
        final Uri uri = ContentUris.withAppendedId(Data.CONTENT_URI, dataItem.getId());
        intent.setDataAndType(uri, dataItem.getMimeType());

        if (intent != null) {
            final String mimetype = intent.getType();

            // Build advanced entry for known 3p types. Otherwise default to ResolveCache icon.
            switch (mimetype) {
            case MIMETYPE_GPLUS_PROFILE:
                // If a secondDataItem is available, use it to build an entry with
                // alternate actions
                if (secondDataItem != null) {
                    icon = res.getDrawable(R.drawable.ic_google_plus_24dp);
                    alternateIcon = res.getDrawable(R.drawable.ic_add_to_circles_black_24);
                    final GPlusOrHangoutsDataItemModel itemModel = new GPlusOrHangoutsDataItemModel(intent,
                            alternateIntent, dataItem, secondDataItem, alternateContentDescription, header,
                            text, context);

                    populateGPlusOrHangoutsDataItemModel(itemModel);
                    intent = itemModel.intent;
                    alternateIntent = itemModel.alternateIntent;
                    alternateContentDescription = itemModel.alternateContentDescription;
                    header = itemModel.header;
                    text = itemModel.text;
                } else {
                    if (GPLUS_PROFILE_DATA_5_ADD_TO_CIRCLE.equals(intent.getDataString())) {
                        icon = res.getDrawable(R.drawable.ic_add_to_circles_black_24);
                    } else {
                        icon = res.getDrawable(R.drawable.ic_google_plus_24dp);
                    }
                }
                break;
            case MIMETYPE_HANGOUTS:
                // If a secondDataItem is available, use it to build an entry with
                // alternate actions
                if (secondDataItem != null) {
                    icon = res.getDrawable(R.drawable.ic_hangout_24dp);
                    alternateIcon = res.getDrawable(R.drawable.ic_hangout_video_24dp);
                    final GPlusOrHangoutsDataItemModel itemModel = new GPlusOrHangoutsDataItemModel(intent,
                            alternateIntent, dataItem, secondDataItem, alternateContentDescription, header,
                            text, context);

                    populateGPlusOrHangoutsDataItemModel(itemModel);
                    intent = itemModel.intent;
                    alternateIntent = itemModel.alternateIntent;
                    alternateContentDescription = itemModel.alternateContentDescription;
                    header = itemModel.header;
                    text = itemModel.text;
                } else {
                    if (HANGOUTS_DATA_5_VIDEO.equals(intent.getDataString())) {
                        icon = res.getDrawable(R.drawable.ic_hangout_video_24dp);
                    } else {
                        icon = res.getDrawable(R.drawable.ic_hangout_24dp);
                    }
                }
                break;
            default:
                entryContextMenuInfo = new EntryContextMenuInfo(header, mimetype, dataItem.getMimeType(),
                        dataItem.getId(), dataItem.isSuperPrimary());
                icon = ResolveCache.getInstance(context).getIcon(dataItem.getMimeType(), intent);
                // Call mutate to create a new Drawable.ConstantState for color filtering
                if (icon != null) {
                    icon.mutate();
                }
                shouldApplyColor = false;
            }
        }
    }

    if (intent != null) {
        // Do not set the intent is there are no resolves
        if (!PhoneCapabilityTester.isIntentRegistered(context, intent)) {
            intent = null;
        }
    }

    if (alternateIntent != null) {
        // Do not set the alternate intent is there are no resolves
        if (!PhoneCapabilityTester.isIntentRegistered(context, alternateIntent)) {
            alternateIntent = null;
        } else if (TextUtils.isEmpty(alternateContentDescription)) {
            // Attempt to use package manager to find a suitable content description if needed
            alternateContentDescription.append(getIntentResolveLabel(alternateIntent, context));
        }
    }

    // If the Entry has no visual elements, return null
    if (icon == null && TextUtils.isEmpty(header) && TextUtils.isEmpty(subHeader) && subHeaderIcon == null
            && TextUtils.isEmpty(text) && textIcon == null) {
        return null;
    }

    // Ignore dataIds from the Me profile.
    final int dataId = dataItem.getId() > Integer.MAX_VALUE ? -1 : (int) dataItem.getId();

    return new Entry(dataId, icon, header, subHeader, subHeaderIcon, text, textIcon,
            phoneContentDescription == null ? new SpannableString(primaryContentDescription.toString())
                    : phoneContentDescription,
            intent, alternateIcon, alternateIntent,
            smsContentDescription == null ? new SpannableString(alternateContentDescription.toString())
                    : smsContentDescription,
            shouldApplyColor, isEditable, entryContextMenuInfo, thirdIcon, thirdIntent, thirdContentDescription,
            thirdAction, thirdExtras, iconResourceId);
}

From source file:com.android.vending.billing.InAppBillingService.LACK.listAppsFragment.java

public void restore(PkgListItem paramPkgListItem, File paramFile) {
      if (testSD(true)) {
          this.backup = paramFile;
          new File(basepath + "/Backup/").mkdirs();
          runWithWait(new Runnable() {
              public void run() {
                  if (listAppsFragment.su) {
                      try {
                          String str1 = listAppsFragment.getPkgMng().getPackageInfo(listAppsFragment.pli.pkgName,
                                  0).applicationInfo.sourceDir;
                          Utils.run_all("rm " + Utils.getPlaceForOdex(str1, false));
                          System.out.println("put refferer");
                          new Utils("").cmdRoot(new String[] { "pm install -r -i com.android.vending '"
                                  + listAppsFragment.this.backup.getAbsolutePath() + "'" });
                          String str2 = listAppsFragment.getPkgMng().getPackageInfo(listAppsFragment.pli.pkgName,
                                  0).applicationInfo.sourceDir;
                          System.out.println(str1);
                          System.out.println(str2);
                          if (str1.equals(str2)) {
                              System.out.println("LuckyPatcher restore app: delete package for install.");
                              new Utils("").cmdRoot(
                                      new String[] { "pm uninstall -k " + listAppsFragment.pli.pkgName });
                              new Utils("").cmdRoot(new String[] { "pm install -r -i com.android.vending '"
                                      + listAppsFragment.this.backup.getAbsolutePath() + "'" });
                          }//from w ww  .jav  a 2s .  co m
                          listAppsFragment.this.runToMain(new Runnable() {
                              public void run() {
                                  try {
                                      listAppsFragment.plia.getItem(listAppsFragment.pli.pkgName).odex = false;
                                      listAppsFragment.plia
                                              .getItem(listAppsFragment.pli.pkgName).modified = false;
                                      listAppsFragment.plia.notifyDataSetChanged(
                                              listAppsFragment.plia.getItem(listAppsFragment.pli.pkgName));
                                      listAppsFragment.getConfig().edit().remove(
                                              listAppsFragment.plia.getItem(listAppsFragment.pli.pkgName).pkgName)
                                              .commit();
                                      listAppsFragment.refresh = true;
                                      listAppsFragment.removeDialogLP(11);
                                      return;
                                  } catch (Exception localException) {
                                      for (;;) {
                                          localException.printStackTrace();
                                      }
                                  }
                              }
                          });
                          return;
                      } catch (PackageManager.NameNotFoundException localNameNotFoundException) {
                          for (;;) {
                              localNameNotFoundException.printStackTrace();
                              listAppsFragment.this.runToMain(new Runnable() {
                                  public void run() {
                                      listAppsFragment.this.showMessage(Utils.getText(2131165748),
                                              Utils.getText(2131165447));
                                      listAppsFragment.removeDialogLP(11);
                                  }
                              });
                          }
                      } catch (Exception localException) {
                          for (;;) {
                              localException.printStackTrace();
                              listAppsFragment.this.runToMain(new Runnable() {
                                  public void run() {
                                      listAppsFragment.this.showMessage(Utils.getText(2131165748),
                                              Utils.getText(2131165447));
                                      listAppsFragment.removeDialogLP(11);
                                  }
                              });
                          }
                      }
                  }
                  listAppsFragment.this.runToMain(new Runnable() {
                      public void run() {
                          Intent localIntent = new Intent("android.intent.action.VIEW");
                          localIntent.setDataAndType(Uri.fromFile(listAppsFragment.this.backup),
                                  "application/vnd.android.package-archive");
                          localIntent.setFlags(131072);
                          listAppsFragment.this.startActivity(localIntent);
                          listAppsFragment.removeDialogLP(11);
                      }
                  });
              }
          });
      }
  }