Example usage for android.media ThumbnailUtils createVideoThumbnail

List of usage examples for android.media ThumbnailUtils createVideoThumbnail

Introduction

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

Prototype

public static Bitmap createVideoThumbnail(String filePath, int kind) 

Source Link

Document

Create a video thumbnail for a video.

Usage

From source file:com.daiv.android.twitter.ui.compose.Compose.java

@Override
protected void onActivityResult(int requestCode, int resultCode, Intent imageReturnedIntent) {
    Log.v("Test_image_attach", "got the result, code: " + requestCode);
    switch (requestCode) {
    case SELECT_PHOTO:
        if (resultCode == RESULT_OK) {
            try {
                Uri selectedImage = imageReturnedIntent.getData();

                String filePath = IOUtils.getPath(selectedImage, context);

                Log.v("Test_compose_pic", "path to image on sd card: " + filePath);

                try {
                    attachImage[imagesAttached].setImageBitmap(getThumbnail(selectedImage));
                    attachImage[imagesAttached].setVisibility(View.VISIBLE);
                    attachedUri[imagesAttached] = selectedImage.toString();
                    imagesAttached++;// w w w .j a  va2s .  c o m
                    //numberAttached.setText(imagesAttached + " " + getResources().getString(R.string.attached_images));
                    //numberAttached.setVisibility(View.VISIBLE);
                } catch (FileNotFoundException e) {
                    Toast.makeText(context, getResources().getString(R.string.error), Toast.LENGTH_SHORT);
                    //numberAttached.setText("");
                    //numberAttached.setVisibility(View.GONE);
                } catch (IOException e) {
                    Toast.makeText(context, getResources().getString(R.string.error), Toast.LENGTH_SHORT);
                    //numberAttached.setText("");
                    //numberAttached.setVisibility(View.GONE);
                }
            } catch (Throwable e) {
                e.printStackTrace();
                Toast.makeText(context, getResources().getString(R.string.error), Toast.LENGTH_SHORT).show();
                //numberAttached.setText("");
                //numberAttached.setVisibility(View.GONE);
            }
        }
        countHandler.post(getCount);
        break;
    case CAPTURE_IMAGE:
        if (resultCode == Activity.RESULT_OK) {
            try {
                Uri selectedImage = Uri.fromFile(
                        new File(Environment.getExternalStorageDirectory() + "/Test/", "photoToTweet.jpg"));

                try {
                    attachImage[imagesAttached].setImageBitmap(getThumbnail(selectedImage));
                    attachImage[imagesAttached].setVisibility(View.VISIBLE);
                    attachedUri[imagesAttached] = selectedImage.toString();
                    imagesAttached++;
                    //numberAttached.setText(imagesAttached + " " + getResources().getString(R.string.attached_images));
                    //numberAttached.setVisibility(View.VISIBLE);
                } catch (FileNotFoundException e) {
                    Toast.makeText(context, getResources().getString(R.string.error), Toast.LENGTH_SHORT);
                    //numberAttached.setText("");
                    //numberAttached.setVisibility(View.GONE);
                } catch (IOException e) {
                    Toast.makeText(context, getResources().getString(R.string.error), Toast.LENGTH_SHORT);
                    //numberAttached.setText("");
                    //numberAttached.setVisibility(View.GONE);
                }

            } catch (Throwable e) {
                e.printStackTrace();
                Toast.makeText(this, getResources().getString(R.string.error), Toast.LENGTH_SHORT).show();
                //numberAttached.setText("");
                //numberAttached.setVisibility(View.GONE);
            }
        }
        countHandler.post(getCount);
        break;
    case PWICCER:
        if (resultCode == Activity.RESULT_OK) {
            String path = imageReturnedIntent.getStringExtra("RESULT");
            attachedUri[imagesAttached] = Uri.fromFile(new File(path)).toString();

            try {
                attachImage[imagesAttached]
                        .setImageBitmap(getThumbnail(Uri.parse(attachedUri[imagesAttached])));
                attachImage[imagesAttached].setVisibility(View.VISIBLE);
                imagesAttached++;
                //numberAttached.setText(imagesAttached + " " + getResources().getString(R.string.attached_images));
                //numberAttached.setVisibility(View.VISIBLE);
            } catch (FileNotFoundException e) {
                Toast.makeText(context, getResources().getString(R.string.error), Toast.LENGTH_SHORT);
                //numberAttached.setText("");
                //numberAttached.setVisibility(View.GONE);
            } catch (IOException e) {
                Toast.makeText(context, getResources().getString(R.string.error), Toast.LENGTH_SHORT);
                //numberAttached.setText("");
                //numberAttached.setVisibility(View.GONE);
            }

            String currText = imageReturnedIntent.getStringExtra("RESULT_TEXT");
            Log.v("pwiccer_text", currText);
            Log.v("pwiccer_text", "length: " + currText.length());
            if (currText != null) {
                reply.setText(currText);
            } else {
                reply.setText(reply.getText().toString().substring(0, 114) + "...");
            }

            pwiccer = true;

            doneClick();
            onBackPressed();
        } else {
            Toast.makeText(context, "Pwiccer failed to generate image! Is it installed?", Toast.LENGTH_SHORT)
                    .show();
        }
        countHandler.post(getCount);
        break;
    case SELECT_GIF:
        if (resultCode == RESULT_OK) {
            try {
                Uri selectedImage = imageReturnedIntent.getData();

                String filePath = IOUtils.getPath(selectedImage, context);

                Log.v("Test_compose_pic", "path to gif on sd card: " + filePath);

                attachImage[0].setImageURI(selectedImage);
                attachImage[0].setVisibility(View.VISIBLE);
                attachedUri[0] = selectedImage.toString();
                imagesAttached = 1;

                attachmentType = "animated_gif";

                attachButton.setEnabled(false);
            } catch (Throwable e) {
                e.printStackTrace();
                Toast.makeText(context, getResources().getString(R.string.error), Toast.LENGTH_SHORT).show();
            }
        }
        countHandler.post(getCount);
        break;
    case SELECT_VIDEO:
        if (resultCode == RESULT_OK) {
            try {
                Uri selectedImage = imageReturnedIntent.getData();

                String filePath = IOUtils.getPath(selectedImage, context);

                Bitmap thumbnail = ThumbnailUtils.createVideoThumbnail(filePath,
                        MediaStore.Images.Thumbnails.MINI_KIND);

                Log.v("Test_compose_pic", "path to video on sd card: " + filePath);

                attachImage[0].setImageBitmap(thumbnail);
                attachImage[0].setVisibility(View.VISIBLE);
                attachedUri[0] = selectedImage.toString();
                imagesAttached = 1;

                attachmentType = "video";

                attachButton.setEnabled(false);
            } catch (Throwable e) {
                e.printStackTrace();
                Toast.makeText(context, getResources().getString(R.string.error), Toast.LENGTH_SHORT).show();
            }
        }
        countHandler.post(getCount);
        break;
    }

    super.onActivityResult(requestCode, resultCode, imageReturnedIntent);
}

From source file:xj.property.activity.HXBaseActivity.ChatActivity.java

/**
 * onActivityResult//from  w  w w  .  ja v a 2  s  .  c o m
 */
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
    super.onActivityResult(requestCode, resultCode, data);
    if (resultCode == RESULT_CODE_EXIT_GROUP) {
        setResult(RESULT_OK);
        finish();
        return;
    }
    if (requestCode == REQUEST_CODE_CONTEXT_MENU) {
        switch (resultCode) {
        case RESULT_CODE_COPY: // ??
            EMMessage copyMsg = ((EMMessage) adapter.getItem(data.getIntExtra("position", -1)));
            // clipboard.setText(SmileUtils.getSmiledText(ChatActivity.this,
            // ((TextMessageBody) copyMsg.getBody()).getMessage()));
            clipboard.setText(((TextMessageBody) copyMsg.getBody()).getMessage());
            break;
        case RESULT_CODE_DELETE: // ?
            EMMessage deleteMsg = (EMMessage) adapter.getItem(data.getIntExtra("position", -1));
            conversation.removeMessage(deleteMsg.getMsgId());
            adapter.refresh();
            listView.setSelection(data.getIntExtra("position", adapter.getCount()) - 1);
            break;

        case RESULT_CODE_FORWARD: // ??
            EMMessage forwardMsg = (EMMessage) adapter.getItem(data.getIntExtra("position", 0));
            Intent intent = new Intent(this, ForwardMessageActivity.class);
            intent.putExtra("forward_msg_id", forwardMsg.getMsgId());
            startActivity(intent);

            break;

        default:
            break;
        }
    }
    if (resultCode == RESULT_OK) { // ?
        if (requestCode == REQUEST_CODE_EMPTY_HISTORY) {
            // ?
            EMChatManager.getInstance().clearConversation(toChatUsername);
            clearDB();
            adapter.refresh();
        } else if (requestCode == REQUEST_CODE_CAMERA) { // ??
            if (cameraFile != null && cameraFile.exists())
                sendPicture(cameraFile.getAbsolutePath());
        } else if (requestCode == REQUEST_CODE_SELECT_VIDEO) { // ??

            int duration = data.getIntExtra("dur", 0);
            String videoPath = data.getStringExtra("path");
            File file = new File(PathUtil.getInstance().getImagePath(), "thvideo" + System.currentTimeMillis());
            Bitmap bitmap = null;
            FileOutputStream fos = null;
            try {
                if (!file.getParentFile().exists()) {
                    file.getParentFile().mkdirs();
                }
                bitmap = ThumbnailUtils.createVideoThumbnail(videoPath, 3);
                if (bitmap == null) {
                    EMLog.d("chatactivity", "problem load video thumbnail bitmap,use default icon");
                    bitmap = BitmapFactory.decodeResource(getResources(), R.drawable.app_panel_video_icon);
                }
                fos = new FileOutputStream(file);

                bitmap.compress(CompressFormat.JPEG, 100, fos);

            } catch (Exception e) {
                e.printStackTrace();
            } finally {
                if (fos != null) {
                    try {
                        fos.close();
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                    fos = null;
                }
                if (bitmap != null) {
                    bitmap.recycle();
                    bitmap = null;
                }

            }
            sendVideo(videoPath, file.getAbsolutePath(), duration / 1000);

        } else if (requestCode == REQUEST_CODE_LOCAL) { // ??
            int bitmapChatSize = BitmapHelper.bitmapChatListStorage.size();

            if (bitmapChatSize > 0) {
                for (int i = 0; i < bitmapChatSize; i++) {
                    Uri selectedImage = Uri.parse(BitmapHelper.bitmapChatListStorage.get(i));
                    if (selectedImage != null) {
                        sendPicByUri(selectedImage);
                    }
                }
                BitmapHelper.bitmapChatListStorage.clear();
            }
            //                if (data != null) {
            //                    Uri selectedImage = data.getData();
            //                    if (selectedImage != null) {
            //                        sendPicByUri(selectedImage);
            //                    }
            //                }
        } else if (requestCode == REQUEST_CODE_SELECT_FILE) { // ??
            if (data != null) {
                Uri uri = data.getData();
                if (uri != null) {
                    sendFile(uri);
                }
            }

        } else if (requestCode == REQUEST_CODE_MAP) { // 
            double latitude = data.getDoubleExtra("latitude", 0);
            double longitude = data.getDoubleExtra("longitude", 0);
            String locationAddress = data.getStringExtra("address");
            if (locationAddress != null && !locationAddress.equals("")) {
                more(more);
                sendLocationMsg(latitude, longitude, "", locationAddress);
            } else {
                showToast("???");
            }
            // ???
        } else if (requestCode == REQUEST_CODE_TEXT || requestCode == REQUEST_CODE_VOICE
                || requestCode == REQUEST_CODE_PICTURE || requestCode == REQUEST_CODE_LOCATION
                || requestCode == REQUEST_CODE_VIDEO || requestCode == REQUEST_CODE_FILE) {
            resendMessage();
        } else if (requestCode == REQUEST_CODE_COPY_AND_PASTE) {
            // 
            if (!TextUtils.isEmpty(clipboard.getText())) {
                String pasteText = clipboard.getText().toString();
                if (pasteText.startsWith(COPY_IMAGE)) {

                    if (TextUtils.equals(servantType, Config.SERVANT_TYPE_BANGBANG)
                            || TextUtils.equals(servantType, Config.SERVANT_TYPE_WEIXIUTOUSU)
                            || TextUtils.equals(servantType, Config.SERVANT_TYPE_SHOPTOUSU)
                            || TextUtils.equals(servantType, Config.SERVANT_TYPE_WUYE)) {

                        sendPictureServantOrComplain(pasteText.replace(COPY_IMAGE, ""));
                    } else {
                        // ??path
                        sendPicture(pasteText.replace(COPY_IMAGE, ""));

                    }

                }

            }
        } else if (requestCode == REQUEST_CODE_ADD_TO_BLACKLIST) { // ???
            EMMessage deleteMsg = (EMMessage) adapter.getItem(data.getIntExtra("position", -1));
            addUserToBlacklist(deleteMsg.getFrom());
        } else if (conversation.getMsgCount() > 0) {
            adapter.refresh();
            setResult(RESULT_OK);
            //// ?, ???,?
        } else if (requestCode == REQUEST_CODE_GROUP_DETAIL) {
            if (data != null) {
                String destoryflag = data.getStringExtra(Config.EXPKey_GROUP_DESTORY);
                if (TextUtils.equals(destoryflag, Config.EXPKey_GROUP_DESTORY)) {
                    if (conversation != null) {
                        conversation.clear();
                        ////TODO   ??
                        //                            EMChatManager.getInstance().deleteConversation(conversation);
                    }
                    showToast("?");
                    finish();
                }
                group.setGroupName(data.getStringExtra(Config.EXPKey_GROUP));
            }
            adapter.refresh();
        }
    }
}

From source file:org.matrix.androidsdk.fragments.MatrixMessageListFragment.java

/**
 * Compute the video thumbnail/*from  w  w  w.  ja  v a 2s  .  co m*/
 *
 * @param videoUrl the video url
 * @return the video thumbnail
 */
public String getVideoThumbnailUrl(final String videoUrl) {
    String thumbUrl = null;
    try {
        Uri uri = Uri.parse(videoUrl);
        Bitmap thumb = ThumbnailUtils.createVideoThumbnail(uri.getPath(),
                MediaStore.Images.Thumbnails.MINI_KIND);
        thumbUrl = getMXMediasCache().saveBitmap(thumb, null);
    } catch (Exception e) {
        Log.e(LOG_TAG, "getVideoThumbailUrl failed with " + e.getLocalizedMessage());
    }

    return thumbUrl;
}

From source file:org.telegram.ui.ChatActivity.java

public void processSendingVideo(final String videoPath) {
    if (videoPath == null) {
        return;/*from w  w  w.  j a v a 2 s . co  m*/
    }
    Bitmap thumb = ThumbnailUtils.createVideoThumbnail(videoPath, MediaStore.Video.Thumbnails.MINI_KIND);
    TLRPC.PhotoSize size = FileLoader.scaleAndSaveImage(thumb, 90, 90, 55, currentEncryptedChat != null);
    if (size == null) {
        return;
    }
    size.type = "s";
    TLRPC.TL_video video = new TLRPC.TL_video();
    video.thumb = size;
    video.caption = "";
    video.id = 0;
    video.path = videoPath;
    File temp = new File(videoPath);
    if (temp != null && temp.exists()) {
        video.size = (int) temp.length();
    }
    UserConfig.lastLocalId--;
    UserConfig.saveConfig(false);

    MediaPlayer mp = MediaPlayer.create(ApplicationLoader.applicationContext,
            Uri.fromFile(new File(videoPath)));
    if (mp == null) {
        return;
    }
    video.duration = (int) Math.ceil(mp.getDuration() / 1000.0f);
    video.w = mp.getVideoWidth();
    video.h = mp.getVideoHeight();
    mp.release();

    MediaStore.Video.Media media = new MediaStore.Video.Media();
    MessagesController.Instance.sendMessage(video, dialog_id);
    if (chatListView != null) {
        chatListView.setSelection(messages.size() + 1);
    }
    scrollToTopOnResume = true;
}

From source file:dentex.youtube.downloader.DashboardActivity.java

private void writeThumbToDiskForSelectedFile(final File selectedFile, String pngBasename) {
    Bitmap bmThumbnail = ThumbnailUtils.createVideoThumbnail(selectedFile.getAbsolutePath(),
            Thumbnails.MINI_KIND);//from w  w  w  .j a  va2  s  .  co  m
    File bmFile = new File(getDir(YTD.THUMBS_FOLDER, 0), pngBasename + ".png");
    try {
        Utils.logger("d", "trying to write thumbnail for " + selectedFile.getName() + " -> " + pngBasename,
                DEBUG_TAG);
        FileOutputStream out = new FileOutputStream(bmFile);
        bmThumbnail.compress(Bitmap.CompressFormat.PNG, 90, out);
    } catch (Exception e) {
        Log.e(DEBUG_TAG, "writeThumbToDiskForImportedVideo -> " + e.getMessage());
    }
}

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

@Override
public void onActivityResult(int requestCode, int resultCode, final Intent data) {
    super.onActivityResult(requestCode, resultCode, data);
    System.gc();//from  w  w w  .j av a2  s  . c  o m
    if (requestCode == 18 && resultCode == Activity.RESULT_OK && null != data) {
        final ProgressDialog dialogLoader = ProgressDialog.show(activity, "",
                Finder.STRING.CONTACT_PROGRESS.toString(), true);
        Uri selectedVideo = data.getData();
        String[] filePathColumn = { MediaStore.Video.Media.DATA };
        final Cursor cursor = activity.getContentResolver().query(selectedVideo, filePathColumn, null, null,
                null);
        cursor.moveToFirst();
        int columnIndex = cursor.getColumnIndex(filePathColumn[0]);
        final String videoPath = cursor.getString(columnIndex);
        cursor.close();
        System.gc();
        final File fileVideo = new File(videoPath);
        Calendar fecha = Calendar.getInstance();
        final long fechaInMillis = fecha.getTimeInMillis();
        File pathImage = new File(
                Environment.getExternalStorageDirectory().getAbsolutePath() + "/SpeakOn/Video/Sent");
        pathImage.mkdirs();
        final File file = new File(pathImage, +fechaInMillis + ".mp4");
        cursor.close();
        //runTranscodingUsingLoader(fileVideo.getAbsolutePath(), file.getAbsolutePath());
        new Thread(new Runnable() {
            @Override
            public void run() {
                Bitmap thumbnailVideo = ThumbnailUtils.createVideoThumbnail(videoPath,
                        MediaStore.Video.Thumbnails.MICRO_KIND);
                Bitmap toUpload = scaleDownLargeImageWithAspectRatio(thumbnailVideo, 1280);
                Bitmap binaryData = toUpload;
                Bitmap binaryData2 = BlurImage(toUpload);
                try {
                    FileInputStream inStream = new FileInputStream(fileVideo);
                    FileOutputStream outStream = new FileOutputStream(file);

                    byte[] buffer = new byte[1024];

                    int length;
                    //copy the file content in bytes
                    while ((length = inStream.read(buffer)) > 0) {

                        outStream.write(buffer, 0, length);

                    }

                    inStream.close();
                    outStream.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
                final Message msjVideo = new Message();
                try {
                    String id = u.id + contact.idContacto + fechaInMillis + Settings.Secure
                            .getString(activity.getContentResolver(), Settings.Secure.ANDROID_ID);

                    msjVideo.mensajeId = id;
                    msjVideo.emisor = u.id;
                    msjVideo.receptor = contact.idContacto;
                    msjVideo.emisorEmail = u.email;
                    msjVideo.receptorEmail = contact.email;
                    msjVideo.emisorLang = u.lang;
                    msjVideo.receptorLang = contact.lang;
                    msjVideo.emitedAt = fechaInMillis;
                    msjVideo.tipo = Integer.parseInt(getString(R.string.MSG_TYPE_VIDEO));
                    if (tiempoMensaje)
                        msjVideo.delay = temporizadorSeek.getValue();
                    else
                        msjVideo.delay = 0;
                    msjVideo.videoName = file.getAbsolutePath();

                    ByteArrayOutputStream stream = new ByteArrayOutputStream();
                    binaryData.compress(Bitmap.CompressFormat.JPEG, 60, stream);
                    byte[] byteArray = stream.toByteArray();
                    msjVideo.photo = byteArray;

                    ByteArrayOutputStream stream2 = new ByteArrayOutputStream();
                    binaryData2.compress(Bitmap.CompressFormat.JPEG, 60, stream2);
                    byte[] byteArray2 = stream2.toByteArray();
                    msjVideo.photoBlur = byteArray2;
                    if (SpeakSocket.mSocket != null)
                        if (SpeakSocket.mSocket.connected()) {
                            msjVideo.status = 1;
                        } else {
                            msjVideo.status = -1;
                        }
                    msjVideo.fileUploaded = false;
                    msjVideo.save();

                    Chats chat = new Select().from(Chats.class).where("idContacto = ?", msjVideo.receptor)
                            .executeSingle();
                    if (chat == null) {
                        Contact contact = new Select().from(Contact.class)
                                .where("id_contact = ?", msjVideo.receptor).executeSingle();
                        Chats newChat = new Chats();
                        newChat.mensajeId = msjVideo.mensajeId;
                        newChat.idContacto = msjVideo.receptor;
                        newChat.isLockedConversation = false;
                        newChat.lastStatus = msjVideo.status;
                        newChat.email = msjVideo.receptorEmail;
                        if (contact != null) {
                            newChat.photo = contact.photo;
                            newChat.fullName = contact.fullName;
                            newChat.lang = contact.lang;
                            newChat.screenName = contact.screenName;
                            newChat.photoload = true;
                            newChat.phone = contact.phone;
                        } else {
                            newChat.photo = null;
                            newChat.photoload = false;
                            newChat.fullName = msjVideo.receptorEmail;
                            newChat.lang = msjVideo.receptorLang;
                            newChat.screenName = msjVideo.receptorEmail;
                            newChat.phone = null;
                        }
                        newChat.emitedAt = msjVideo.emitedAt;
                        newChat.notRead = 0;
                        newChat.lastMessage = "send Video";
                        newChat.show = true;
                        newChat.save();
                    } else {
                        if (!chat.photoload) {
                            Contact contact = new Select().from(Contact.class)
                                    .where("id_contact = ?", msjVideo.emisor).executeSingle();
                            if (contact != null) {
                                chat.photo = contact.photo;
                                chat.photoload = true;
                            } else {
                                chat.photo = null;
                                chat.photoload = false;
                            }
                        }
                        chat.mensajeId = msjVideo.mensajeId;
                        chat.lastStatus = msjVideo.status;
                        chat.emitedAt = msjVideo.emitedAt;
                        chat.notRead = 0;
                        chat.lastMessage = "send Video";
                        chat.save();
                    }
                    showNewMessage(msjVideo);
                    dialogLoader.dismiss();
                } catch (Exception e) {
                }
                System.gc();
            }
        }).start();

    }

    if (requestCode == 45) {
        milocManager = (LocationManager) getActivity().getSystemService(Context.LOCATION_SERVICE);
        List<String> allProviders = milocManager.getAllProviders();
        boolean gpsProvider = false;
        boolean netProvider = false;
        for (String providerName : allProviders) {
            if (providerName.equals(LocationManager.GPS_PROVIDER)) {
                gpsProvider = true;
            }
            if (providerName.equals(LocationManager.NETWORK_PROVIDER)) {
                netProvider = true;
            }
        }
        checkCountryLocation(gpsProvider, netProvider);
    }

    if (requestCode == 34) {
        if (resultCode == activity.RESULT_OK) {
            Uri contactUri = data.getData();
            try {
                //contactPic.setImageBitmap(getPhoto(contactUri));
                JSONObject contacto = new JSONObject();
                contacto.put("nombre", getName(contactUri));
                contacto.put("telefono", getPhone(contactUri));
                Message msjNew = new Message();
                Calendar fecha = Calendar.getInstance();
                String id = u.id + contact.idContacto + fecha.getTimeInMillis()
                        + Settings.Secure.getString(activity.getContentResolver(), Settings.Secure.ANDROID_ID);
                msjNew.translation = true;
                msjNew.mensajeId = id;
                msjNew.emisor = u.id;
                msjNew.receptor = contact.idContacto;
                msjNew.mensaje = contacto.toString();
                msjNew.emisorEmail = u.email;
                msjNew.receptorEmail = contact.email;
                msjNew.emisorLang = u.lang;
                msjNew.receptorLang = contact.lang;
                msjNew.emitedAt = fecha.getTimeInMillis();
                msjNew.tipo = Integer.parseInt(getString(R.string.MSG_TYPE_CONTACT));
                msjNew.delay = 0;
                if (SpeakSocket.mSocket != null)
                    if (SpeakSocket.mSocket.connected()) {
                        msjNew.status = 1;
                    } else {
                        msjNew.status = -1;
                    }
                msjNew.save();
                Chats chat = new Select().from(Chats.class).where("idContacto = ?", msjNew.receptor)
                        .executeSingle();
                if (chat == null) {
                    Contact contact = new Select().from(Contact.class).where("id_contact = ?", msjNew.receptor)
                            .executeSingle();
                    Chats newChat = new Chats();
                    newChat.mensajeId = msjNew.mensajeId;
                    newChat.idContacto = msjNew.receptor;
                    newChat.isLockedConversation = false;
                    newChat.lastStatus = msjNew.status;
                    newChat.email = msjNew.receptorEmail;
                    if (contact != null) {
                        newChat.photo = contact.photo;
                        newChat.fullName = contact.fullName;
                        newChat.lang = contact.lang;
                        newChat.screenName = contact.screenName;
                        newChat.photoload = true;
                        newChat.phone = contact.phone;
                    } else {
                        newChat.photo = null;
                        newChat.photoload = false;
                        newChat.fullName = msjNew.receptorEmail;
                        newChat.lang = msjNew.receptorLang;
                        newChat.screenName = msjNew.receptorEmail;
                        newChat.phone = null;
                    }
                    newChat.emitedAt = msjNew.emitedAt;
                    newChat.notRead = 0;
                    newChat.lastMessage = "send Contact";
                    newChat.show = true;
                    newChat.save();
                } else {
                    if (!chat.photoload) {
                        Contact contact = new Select().from(Contact.class)
                                .where("id_contact = ?", msjNew.emisor).executeSingle();
                        if (contact != null) {
                            chat.photo = contact.photo;
                            chat.photoload = true;
                        } else {
                            chat.photo = null;
                            chat.photoload = false;
                        }
                    }
                    chat.mensajeId = msjNew.mensajeId;
                    chat.lastStatus = msjNew.status;
                    chat.emitedAt = msjNew.emitedAt;
                    chat.notRead = 0;
                    chat.lastMessage = "send Contact";
                    chat.save();
                }
                showNewMessage(msjNew);
            } catch (JSONException e) {
                e.printStackTrace();
            }
        }
        System.gc();
    }
    if (requestCode == 1 && null != data) {
        Uri selectedImage = data.getData();
        InputStream imageStream = null;
        try {
            imageStream = activity.getContentResolver().openInputStream(selectedImage);
        } catch (FileNotFoundException e) {
        }
        String[] filePathColumn = { MediaStore.Images.Media.DATA };
        Cursor cursor = activity.getContentResolver().query(selectedImage, filePathColumn, null, null, null);
        cursor.moveToFirst();
        int columnIndex = cursor.getColumnIndex(filePathColumn[0]);
        String picturePath = cursor.getString(columnIndex);
        Bitmap bitmapRotate = C.rotateBitmapAndScale(picturePath);
        cursor.close();
        System.gc();
        Calendar fecha = Calendar.getInstance();
        long fechaInMillis = fecha.getTimeInMillis();
        File pathImage = new File(
                Environment.getExternalStorageDirectory().getAbsolutePath() + "/SpeakOn/Image/Sent");
        pathImage.mkdirs();
        Bitmap toUpload = scaleDownLargeImageWithAspectRatio(bitmapRotate, 1280);
        System.gc();
        Bitmap binaryData = scaleDownLargeImageWithAspectRatio(toUpload, 500);
        System.gc();
        Bitmap binaryData2 = BlurImage(scaleDownLargeImageWithAspectRatio(toUpload, 400));
        System.gc();
        File file = new File(pathImage, +fechaInMillis + ".png");
        OutputStream outputStream = null;
        try {
            outputStream = new FileOutputStream(file);
            toUpload.compress(Bitmap.CompressFormat.JPEG, 60, outputStream);
            outputStream.flush();
            outputStream.close();
            System.gc();
        } catch (Exception e) {
            e.printStackTrace();
        }
        try {
            final Message msjPhoto = new Message();
            String id = u.id + contact.idContacto + fechaInMillis
                    + Settings.Secure.getString(activity.getContentResolver(), Settings.Secure.ANDROID_ID);
            msjPhoto.mensajeId = id;
            msjPhoto.emisor = u.id;
            msjPhoto.receptor = contact.idContacto;
            msjPhoto.emisorEmail = u.email;
            msjPhoto.receptorEmail = contact.email;
            msjPhoto.emisorLang = u.lang;
            msjPhoto.receptorLang = contact.lang;
            msjPhoto.emitedAt = fechaInMillis;
            msjPhoto.tipo = Integer.parseInt(getString(R.string.MSG_TYPE_PHOTO));
            if (tiempoMensaje)
                msjPhoto.delay = temporizadorSeek.getValue();
            else
                msjPhoto.delay = 0;
            msjPhoto.photoName = file.getAbsolutePath();

            ByteArrayOutputStream stream = new ByteArrayOutputStream();
            binaryData.compress(Bitmap.CompressFormat.JPEG, 60, stream);
            byte[] byteArray = stream.toByteArray();
            msjPhoto.photo = byteArray;

            ByteArrayOutputStream stream2 = new ByteArrayOutputStream();
            binaryData2.compress(Bitmap.CompressFormat.JPEG, 40, stream2);
            byte[] byteArray2 = stream2.toByteArray();
            msjPhoto.photoBlur = byteArray2;
            if (SpeakSocket.mSocket != null)
                if (SpeakSocket.mSocket.connected()) {
                    msjPhoto.status = 1;
                } else {
                    msjPhoto.status = -1;
                }
            msjPhoto.fileUploaded = false;
            msjPhoto.save();
            Chats chat = new Select().from(Chats.class).where("idContacto = ?", msjPhoto.receptor)
                    .executeSingle();
            if (chat == null) {
                Contact contact = new Select().from(Contact.class).where("id_contact = ?", msjPhoto.receptor)
                        .executeSingle();
                Chats newChat = new Chats();
                newChat.mensajeId = msjPhoto.mensajeId;
                newChat.idContacto = msjPhoto.receptor;
                newChat.isLockedConversation = false;
                newChat.lastStatus = msjPhoto.status;
                newChat.email = msjPhoto.receptorEmail;
                if (contact != null) {
                    newChat.photo = contact.photo;
                    newChat.fullName = contact.fullName;
                    newChat.lang = contact.lang;
                    newChat.screenName = contact.screenName;
                    newChat.photoload = true;
                    newChat.phone = contact.phone;
                } else {
                    newChat.photo = null;
                    newChat.photoload = false;
                    newChat.fullName = msjPhoto.receptorEmail;
                    newChat.lang = msjPhoto.receptorLang;
                    newChat.screenName = msjPhoto.receptorEmail;
                    newChat.phone = null;
                }
                newChat.emitedAt = msjPhoto.emitedAt;
                newChat.notRead = 0;
                newChat.lastMessage = "send Image";
                newChat.show = true;
                newChat.save();
            } else {
                if (!chat.photoload) {
                    Contact contact = new Select().from(Contact.class).where("id_contact = ?", msjPhoto.emisor)
                            .executeSingle();
                    if (contact != null) {
                        chat.photo = contact.photo;
                        chat.photoload = true;
                    } else {
                        chat.photo = null;
                        chat.photoload = false;
                    }
                }
                chat.mensajeId = msjPhoto.mensajeId;
                chat.lastStatus = msjPhoto.status;
                chat.emitedAt = msjPhoto.emitedAt;
                chat.notRead = 0;
                chat.lastMessage = "send Image";
                chat.save();
            }
            showNewMessage(msjPhoto);

        } catch (Exception e) {
        }
        System.gc();
    }
    if (requestCode == 23) {
        if (resultCode == Activity.RESULT_OK) {
            Bitmap bitmapRotate = C
                    .rotateBitmapAndScale(Environment.getExternalStorageDirectory().getAbsolutePath()
                            + "/SpeakOn/Image/Sent/" + dateToCamera + ".png");
            System.gc();
            Bitmap toUpload = scaleDownLargeImageWithAspectRatio(bitmapRotate, 1280);
            System.gc();
            Bitmap binaryData = scaleDownLargeImageWithAspectRatio(toUpload, 500);
            System.gc();
            Bitmap binaryData2 = BlurImage(scaleDownLargeImageWithAspectRatio(toUpload, 400));
            System.gc();
            File file = new File(Environment.getExternalStorageDirectory().getAbsolutePath()
                    + "/SpeakOn/Image/Sent/" + dateToCamera + ".png");
            OutputStream outputStream = null;
            try {
                outputStream = new FileOutputStream(file);
                toUpload.compress(Bitmap.CompressFormat.JPEG, 60, outputStream);
                outputStream.flush();
                outputStream.close();
                System.gc();
            } catch (FileNotFoundException e) {
                e.printStackTrace();
            } catch (IOException e) {
                e.printStackTrace();
            }
            try {
                final Message msjPhoto = new Message();
                String id = u.id + contact.idContacto + dateToCamera
                        + Settings.Secure.getString(activity.getContentResolver(), Settings.Secure.ANDROID_ID);
                msjPhoto.mensajeId = id;
                msjPhoto.emisor = u.id;
                msjPhoto.receptor = contact.idContacto;
                msjPhoto.emisorEmail = u.email;
                msjPhoto.receptorEmail = contact.email;
                msjPhoto.emisorLang = u.lang;
                msjPhoto.receptorLang = contact.lang;
                msjPhoto.emitedAt = dateToCamera;
                msjPhoto.tipo = Integer.parseInt(getString(R.string.MSG_TYPE_PHOTO));
                if (tiempoMensaje)
                    msjPhoto.delay = temporizadorSeek.getValue();
                else
                    msjPhoto.delay = 0;
                msjPhoto.photoName = file.getAbsolutePath();

                ByteArrayOutputStream stream = new ByteArrayOutputStream();
                binaryData.compress(Bitmap.CompressFormat.JPEG, 60, stream);
                byte[] byteArray = stream.toByteArray();
                msjPhoto.photo = byteArray;

                ByteArrayOutputStream stream2 = new ByteArrayOutputStream();
                binaryData2.compress(Bitmap.CompressFormat.JPEG, 40, stream2);
                byte[] byteArray2 = stream2.toByteArray();
                msjPhoto.photoBlur = byteArray2;
                if (SpeakSocket.mSocket != null)
                    if (SpeakSocket.mSocket.connected()) {
                        msjPhoto.status = 1;
                    } else {
                        msjPhoto.status = -1;
                    }
                msjPhoto.fileUploaded = false;
                msjPhoto.save();
                Chats chat = new Select().from(Chats.class).where("idContacto = ?", msjPhoto.receptor)
                        .executeSingle();
                if (chat == null) {
                    Contact contact = new Select().from(Contact.class)
                            .where("id_contact = ?", msjPhoto.receptor).executeSingle();
                    Chats newChat = new Chats();
                    newChat.mensajeId = msjPhoto.mensajeId;
                    newChat.idContacto = msjPhoto.receptor;
                    newChat.isLockedConversation = false;
                    newChat.lastStatus = msjPhoto.status;
                    newChat.email = msjPhoto.receptorEmail;
                    if (contact != null) {
                        newChat.photo = contact.photo;
                        newChat.fullName = contact.fullName;
                        newChat.lang = contact.lang;
                        newChat.screenName = contact.screenName;
                        newChat.photoload = true;
                        newChat.phone = contact.phone;
                    } else {
                        newChat.photo = null;
                        newChat.photoload = false;
                        newChat.fullName = msjPhoto.receptorEmail;
                        newChat.lang = msjPhoto.receptorLang;
                        newChat.screenName = msjPhoto.receptorEmail;
                        newChat.phone = null;
                    }
                    newChat.emitedAt = msjPhoto.emitedAt;
                    newChat.notRead = 0;
                    newChat.lastMessage = "send Image";
                    newChat.show = true;
                    newChat.save();
                } else {
                    if (!chat.photoload) {
                        Contact contact = new Select().from(Contact.class)
                                .where("id_contact = ?", msjPhoto.emisor).executeSingle();
                        if (contact != null) {
                            chat.photo = contact.photo;
                            chat.photoload = true;
                        } else {
                            chat.photo = null;
                            chat.photoload = false;
                        }
                    }
                    chat.mensajeId = msjPhoto.mensajeId;
                    chat.lastStatus = msjPhoto.status;
                    chat.emitedAt = msjPhoto.emitedAt;
                    chat.notRead = 0;
                    chat.lastMessage = "send Image";
                    chat.save();
                }
                showNewMessage(msjPhoto);
            } catch (Exception e) {
            }
            System.gc();
        }
    }
}

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

@Override
public void onActivityResult(int requestCode, int resultCode, final Intent data) {
    super.onActivityResult(requestCode, resultCode, data);
    System.gc();/*w  w  w  .j  av a2  s  .c o  m*/
    if (requestCode == 34) {
        if (resultCode == activity.RESULT_OK) {
            Uri contactUri = data.getData();
            try {
                //contactPic.setImageBitmap(getPhoto(contactUri));
                JSONObject contactoSend = new JSONObject();
                contactoSend.put("nombre", getName(contactUri));
                contactoSend.put("telefono", getPhone(contactUri));
                MsgGroups msjNew = new MsgGroups();
                Calendar fecha = Calendar.getInstance();
                JSONArray targets = new JSONArray();
                JSONArray contactos = new JSONArray(grupo.targets);
                String contactosId = null;
                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 (translate)
                                        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);
                                    contactosId += contact.idContacto;
                                    targets.put(targets.length(), newContact);
                                }
                            }
                        }
                    } 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 (translate)
                                        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);
                                    contactosId += contact.idContacto;
                                    targets.put(targets.length(), newContact);
                                }
                            }
                        }
                    }
                }
                msjNew.grupoId = grupo.grupoId;
                msjNew.mensajeId = u.id + grupo.grupoId + fecha.getTimeInMillis()
                        + Settings.Secure.getString(activity.getContentResolver(), Settings.Secure.ANDROID_ID);
                msjNew.emisor = u.id;
                msjNew.receptores = targets.toString();
                msjNew.mensaje = contactoSend.toString();
                msjNew.emisorEmail = u.email;
                msjNew.emisorLang = u.lang;
                msjNew.translation = false;
                msjNew.emitedAt = fecha.getTimeInMillis();
                msjNew.tipo = Integer.parseInt(getString(R.string.MSG_TYPE_GROUP_CONTACT));
                msjNew.delay = 0;
                msjNew.save();
                showNewMessage(msjNew);
            } catch (JSONException e) {
                e.printStackTrace();
            }
        }
        System.gc();
    }

    if (requestCode == 1 && null != data) {
        Uri selectedImage = data.getData();
        String[] filePathColumn = { MediaStore.Images.Media.DATA };
        Cursor cursor = activity.getContentResolver().query(selectedImage, filePathColumn, null, null, null);
        cursor.moveToFirst();
        int columnIndex = cursor.getColumnIndex(filePathColumn[0]);
        String picturePath = cursor.getString(columnIndex);
        Bitmap bitmapRotate = C.rotateBitmapAndScale(picturePath);
        cursor.close();
        System.gc();
        Calendar fecha = Calendar.getInstance();
        long fechaInMillis = fecha.getTimeInMillis();
        File pathImage = new File(
                Environment.getExternalStorageDirectory().getAbsolutePath() + "/SpeakOn/Image/Sent");
        pathImage.mkdirs();
        Bitmap toUpload = scaleDownLargeImageWithAspectRatio(bitmapRotate, 1280);
        System.gc();
        Bitmap binaryData = scaleDownLargeImageWithAspectRatio(toUpload, 500);
        System.gc();
        Bitmap binaryData2 = BlurImage(scaleDownLargeImageWithAspectRatio(toUpload, 400));
        System.gc();
        File file = new File(pathImage, +fechaInMillis + ".png");
        OutputStream outputStream = null;
        try {
            outputStream = new FileOutputStream(file);
            toUpload.compress(Bitmap.CompressFormat.JPEG, 60, outputStream);
            outputStream.flush();
            outputStream.close();
            System.gc();
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
        try {
            final MsgGroups msjPhoto = new MsgGroups();
            JSONArray targets = new JSONArray();
            JSONArray contactos = new JSONArray(grupo.targets);
            String contactosId = null;
            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 (translate)
                                    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);
                                contactosId += contact.idContacto;
                                targets.put(targets.length(), newContact);
                            }
                        }
                    }
                } 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 (translate)
                                    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);
                                contactosId += contact.idContacto;
                                targets.put(targets.length(), newContact);
                            }
                        }
                    }
                }
            }
            msjPhoto.grupoId = grupo.grupoId;
            msjPhoto.mensajeId = u.id + grupo.grupoId + fechaInMillis
                    + Settings.Secure.getString(activity.getContentResolver(), Settings.Secure.ANDROID_ID);
            msjPhoto.emisor = u.id;
            msjPhoto.receptores = targets.toString();
            msjPhoto.mensaje = "send Image";
            msjPhoto.emisorEmail = u.email;
            msjPhoto.emisorLang = u.lang;
            msjPhoto.translation = false;
            msjPhoto.emitedAt = fechaInMillis;
            msjPhoto.tipo = Integer.parseInt(getString(R.string.MSG_TYPE_GROUP_PHOTO));
            msjPhoto.delay = 0;
            msjPhoto.photoName = file.getAbsolutePath();
            ByteArrayOutputStream stream = new ByteArrayOutputStream();
            binaryData.compress(Bitmap.CompressFormat.JPEG, 60, stream);
            byte[] byteArray = stream.toByteArray();
            msjPhoto.photo = byteArray;

            ByteArrayOutputStream stream2 = new ByteArrayOutputStream();
            binaryData2.compress(Bitmap.CompressFormat.JPEG, 40, stream2);
            byte[] byteArray2 = stream2.toByteArray();
            msjPhoto.photoBlur = byteArray2;
            msjPhoto.fileUploaded = false;
            msjPhoto.save();
            showNewMessage(msjPhoto);
        } catch (Exception e) {
        }
        System.gc();
    }

    if (requestCode == 23) {
        if (resultCode == Activity.RESULT_OK) {
            Bitmap bitmapRotate = C
                    .rotateBitmapAndScale(Environment.getExternalStorageDirectory().getAbsolutePath()
                            + "/SpeakOn/Image/Sent/" + dateToCamera + ".png");
            System.gc();
            Bitmap toUpload = scaleDownLargeImageWithAspectRatio(bitmapRotate, 1280);
            System.gc();
            Bitmap binaryData = scaleDownLargeImageWithAspectRatio(toUpload, 500);
            System.gc();
            Bitmap binaryData2 = BlurImage(scaleDownLargeImageWithAspectRatio(toUpload, 400));
            System.gc();
            File file = new File(Environment.getExternalStorageDirectory().getAbsolutePath()
                    + "/SpeakOn/Image/Sent/" + dateToCamera + ".png");
            OutputStream outputStream = null;
            try {
                outputStream = new FileOutputStream(file);
                toUpload.compress(Bitmap.CompressFormat.JPEG, 60, outputStream);
                outputStream.flush();
                outputStream.close();
                System.gc();
            } catch (FileNotFoundException e) {
                e.printStackTrace();
            } catch (IOException e) {
                e.printStackTrace();
            }
            try {
                final MsgGroups msjPhoto = new MsgGroups();
                JSONArray targets = new JSONArray();
                JSONArray contactos = new JSONArray(grupo.targets);
                String contactosId = null;
                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 (translate)
                                        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);
                                    contactosId += contact.idContacto;
                                    targets.put(targets.length(), newContact);
                                }
                            }
                        }
                    } 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 (translate)
                                        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);
                                    contactosId += contact.idContacto;
                                    targets.put(targets.length(), newContact);
                                }
                            }
                        }
                    }
                }
                msjPhoto.grupoId = grupo.grupoId;
                msjPhoto.mensajeId = u.id + grupo.grupoId + dateToCamera
                        + Settings.Secure.getString(activity.getContentResolver(), Settings.Secure.ANDROID_ID);
                msjPhoto.emisor = u.id;
                msjPhoto.receptores = targets.toString();
                msjPhoto.mensaje = "send Image";
                msjPhoto.emisorEmail = u.email;
                msjPhoto.emisorLang = u.lang;
                msjPhoto.translation = false;
                msjPhoto.emitedAt = dateToCamera;
                msjPhoto.tipo = Integer.parseInt(getString(R.string.MSG_TYPE_GROUP_PHOTO));
                msjPhoto.delay = 0;
                msjPhoto.photoName = file.getAbsolutePath();
                ByteArrayOutputStream stream = new ByteArrayOutputStream();
                binaryData.compress(Bitmap.CompressFormat.JPEG, 60, stream);
                byte[] byteArray = stream.toByteArray();
                msjPhoto.photo = byteArray;

                ByteArrayOutputStream stream2 = new ByteArrayOutputStream();
                binaryData2.compress(Bitmap.CompressFormat.JPEG, 40, stream2);
                byte[] byteArray2 = stream2.toByteArray();
                msjPhoto.photoBlur = byteArray2;
                msjPhoto.fileUploaded = false;
                msjPhoto.save();
                showNewMessage(msjPhoto);
            } catch (Exception e) {
            }
            System.gc();
        }
    }

    System.gc();
    if (requestCode == 18 && resultCode == Activity.RESULT_OK && null != data) {
        final ProgressDialog dialogLoader = ProgressDialog.show(activity, "",
                Finder.STRING.CONTACT_PROGRESS.toString(), true);
        Uri selectedVideo = data.getData();
        String[] filePathColumn = { MediaStore.Video.Media.DATA };
        final Cursor cursor = activity.getContentResolver().query(selectedVideo, filePathColumn, null, null,
                null);
        cursor.moveToFirst();
        int columnIndex = cursor.getColumnIndex(filePathColumn[0]);
        final String videoPath = cursor.getString(columnIndex);
        cursor.close();
        System.gc();
        final File fileVideo = new File(videoPath);
        Calendar fecha = Calendar.getInstance();
        final long fechaInMillis = fecha.getTimeInMillis();
        File pathImage = new File(
                Environment.getExternalStorageDirectory().getAbsolutePath() + "/SpeakOn/Video/Sent");
        pathImage.mkdirs();
        final File file = new File(pathImage, +fechaInMillis + ".mp4");
        cursor.close();
        //runTranscodingUsingLoader(fileVideo.getAbsolutePath(), file.getAbsolutePath());
        new Thread(new Runnable() {
            @Override
            public void run() {
                Bitmap thumbnailVideo = ThumbnailUtils.createVideoThumbnail(videoPath,
                        MediaStore.Video.Thumbnails.MICRO_KIND);
                Bitmap toUpload = scaleDownLargeImageWithAspectRatio(thumbnailVideo, 1280);
                Bitmap binaryData = toUpload;
                Bitmap binaryData2 = BlurImage(toUpload);
                try {
                    FileInputStream inStream = new FileInputStream(fileVideo);
                    FileOutputStream outStream = new FileOutputStream(file);

                    byte[] buffer = new byte[1024];

                    int length;
                    //copy the file content in bytes
                    while ((length = inStream.read(buffer)) > 0) {

                        outStream.write(buffer, 0, length);

                    }

                    inStream.close();
                    outStream.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
                try {
                    final MsgGroups msjVideo = new MsgGroups();
                    JSONArray targets = new JSONArray();
                    JSONArray contactos = new JSONArray(grupo.targets);
                    String contactosId = null;
                    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 (translate)
                                            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);
                                        contactosId += contact.idContacto;
                                        targets.put(targets.length(), newContact);
                                    }
                                }
                            }
                        } 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 (translate)
                                            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);
                                        contactosId += contact.idContacto;
                                        targets.put(targets.length(), newContact);
                                    }
                                }
                            }
                        }
                    }
                    msjVideo.grupoId = grupo.grupoId;
                    msjVideo.mensajeId = u.id + grupo.grupoId + fechaInMillis + Settings.Secure
                            .getString(activity.getContentResolver(), Settings.Secure.ANDROID_ID);
                    msjVideo.emisor = u.id;
                    msjVideo.receptores = targets.toString();
                    msjVideo.mensaje = "send Video";
                    msjVideo.emisorEmail = u.email;
                    msjVideo.emisorLang = u.lang;
                    msjVideo.translation = false;
                    msjVideo.emitedAt = fechaInMillis;
                    msjVideo.tipo = Integer.parseInt(getString(R.string.MSG_TYPE_GROUP_VIDEO));
                    msjVideo.delay = 0;
                    ByteArrayOutputStream stream = new ByteArrayOutputStream();
                    binaryData.compress(Bitmap.CompressFormat.JPEG, 60, stream);
                    byte[] byteArray = stream.toByteArray();
                    msjVideo.photo = byteArray;
                    ByteArrayOutputStream stream2 = new ByteArrayOutputStream();
                    binaryData2.compress(Bitmap.CompressFormat.JPEG, 60, stream2);
                    byte[] byteArray2 = stream2.toByteArray();
                    msjVideo.photoBlur = byteArray2;
                    msjVideo.fileUploaded = false;
                    msjVideo.videoName = file.getAbsolutePath();
                    msjVideo.save();
                    showNewMessage(msjVideo);
                    dialogLoader.dismiss();
                } catch (Exception e) {
                }
                System.gc();
            }
        }).start();

    }

    if (requestCode == 45) {
        milocManager = (LocationManager) getActivity().getSystemService(Context.LOCATION_SERVICE);
        List<String> allProviders = milocManager.getAllProviders();
        boolean gpsProvider = false;
        boolean netProvider = false;
        for (String providerName : allProviders) {
            if (providerName.equals(LocationManager.GPS_PROVIDER)) {
                gpsProvider = true;
            }
            if (providerName.equals(LocationManager.NETWORK_PROVIDER)) {
                netProvider = true;
            }
        }
        checkCountryLocation(gpsProvider, netProvider);
    }

}