Example usage for android.content.res AssetFileDescriptor getLength

List of usage examples for android.content.res AssetFileDescriptor getLength

Introduction

In this page you can find the example usage for android.content.res AssetFileDescriptor getLength.

Prototype

public long getLength() 

Source Link

Document

Returns the total number of bytes of this asset entry's data.

Usage

From source file:org.awesomeapp.messenger.ui.MessageListItem.java

public void bindIncomingMessage(MessageViewHolder holder, int id, int messageType, String address,
        String nickname, final String mimeType, final String body, Date date, Markup smileyRes,
        boolean scrolling, EncryptionState encryption, boolean showContact, int presenceStatus) {

    mHolder = holder;/*www .ja va2s .  c om*/
    applyStyleColors();
    mHolder.mTextViewForMessages.setVisibility(View.VISIBLE);
    mHolder.mAudioContainer.setVisibility(View.GONE);
    mHolder.mMediaContainer.setVisibility(View.GONE);

    if (nickname == null)
        nickname = address;

    lastMessage = formatMessage(body);
    showAvatar(address, nickname, true, presenceStatus);

    mHolder.resetOnClickListenerMediaThumbnail();

    if (mimeType != null) {

        Uri mediaUri = Uri.parse(body);
        lastMessage = "";

        if (mimeType.startsWith("audio")) {
            mHolder.mAudioButton.setImageResource(R.drawable.media_audio_play);

            try {
                mHolder.mAudioContainer.setVisibility(View.VISIBLE);
                showAudioPlayer(mimeType, mediaUri, id, mHolder);
            } catch (Exception e) {
                mHolder.mAudioContainer.setVisibility(View.GONE);
            }

        } else {
            mHolder.mTextViewForMessages.setVisibility(View.GONE);

            showMediaThumbnail(mimeType, mediaUri, id, mHolder);

            mHolder.mMediaContainer.setVisibility(View.VISIBLE);

        }

    } else if ((!TextUtils.isEmpty(lastMessage))
            && (lastMessage.charAt(0) == '/' || lastMessage.charAt(0) == ':')) {
        boolean cmdSuccess = false;

        if (lastMessage.startsWith("/sticker:")) {
            String[] cmds = lastMessage.split(":");

            String mimeTypeSticker = "image/png";

            try {

                String assetPath = cmds[1].split(" ")[0].toLowerCase();//just get up to any whitespace;

                //make sure sticker exists
                AssetFileDescriptor afd = getContext().getAssets().openFd(assetPath);
                afd.getLength();
                afd.close();

                //now setup the new URI for loading local sticker asset
                Uri mediaUri = Uri.parse("asset://localhost/" + assetPath);

                //now load the thumbnail
                cmdSuccess = showMediaThumbnail(mimeTypeSticker, mediaUri, id, mHolder);
            } catch (Exception e) {
                Log.e(ImApp.LOG_TAG, "error loading sticker bitmap: " + cmds[1], e);
                cmdSuccess = false;
            }

        } else if (lastMessage.startsWith(":")) {
            String[] cmds = lastMessage.split(":");

            String mimeTypeSticker = "image/png";
            try {
                String[] stickerParts = cmds[1].split("-");
                String stickerPath = "stickers/" + stickerParts[0].toLowerCase() + "/"
                        + stickerParts[1].toLowerCase() + ".png";

                //make sure sticker exists
                AssetFileDescriptor afd = getContext().getAssets().openFd(stickerPath);
                afd.getLength();
                afd.close();

                //now setup the new URI for loading local sticker asset
                Uri mediaUri = Uri.parse("asset://localhost/" + stickerPath);

                //now load the thumbnail
                cmdSuccess = showMediaThumbnail(mimeTypeSticker, mediaUri, id, mHolder);
            } catch (Exception e) {
                cmdSuccess = false;
            }
        }

        if (!cmdSuccess) {
            mHolder.mTextViewForMessages.setText(new SpannableString(lastMessage));
        } else {
            mHolder.mContainer.setBackgroundResource(android.R.color.transparent);
            lastMessage = "";
        }

    }

    //  if (isSelected())
    //    mHolder.mContainer.setBackgroundColor(getResources().getColor(R.color.holo_blue_bright));

    if (lastMessage.length() > 0) {
        mHolder.mTextViewForMessages.setText(new SpannableString(lastMessage));
    } else {
        mHolder.mTextViewForMessages.setText(lastMessage);
    }

    if (date != null) {

        String contact = null;
        if (showContact) {
            String[] nickParts = nickname.split("/");
            contact = nickParts[nickParts.length - 1];
        }

        CharSequence tsText = formatTimeStamp(date, messageType, null, encryption, contact);

        mHolder.mTextViewForTimestamp.setText(tsText);
        mHolder.mTextViewForTimestamp.setVisibility(View.VISIBLE);

    } else {

        mHolder.mTextViewForTimestamp.setText("");
        //mHolder.mTextViewForTimestamp.setVisibility(View.GONE);

    }
    if (linkify)
        LinkifyHelper.addLinks(mHolder.mTextViewForMessages, new URLSpanConverter());
    LinkifyHelper.addTorSafeLinks(mHolder.mTextViewForMessages);
}

From source file:edu.mit.mobile.android.locast.net.NetworkClient.java

/**
 * Uploads the content, displaying a notification in the system tray. The notification will show
 * a progress bar as the upload goes on and will show a message when finished indicating whether
 * or not it was successful.//from  w  ww.j a  v  a  2  s  .  c o  m
 *
 * @param context
 * @param cast
 *            cast item
 * @param serverPath
 *            the path on which
 * @param localFile
 * @param contentType
 * @param uploadType
 * @throws NetworkProtocolException
 * @throws IOException
 * @throws JSONException
 */
public JSONObject uploadContentWithNotification(Context context, Uri cast, String serverPath, Uri localFile,
        String contentType, UploadType uploadType) throws NetworkProtocolException, IOException, JSONException {
    String castTitle = Cast.getTitle(context, cast);
    if (castTitle == null) {
        castTitle = "untitled (cast #" + cast.getLastPathSegment() + ")";
    }
    JSONObject updatedCastMedia;
    final ProgressNotification notification = new ProgressNotification(context,
            context.getString(R.string.sync_uploading_cast, castTitle), ProgressNotification.TYPE_UPLOAD,
            PendingIntent.getActivity(context, 0,
                    new Intent(Intent.ACTION_VIEW, cast).addFlags(Intent.FLAG_ACTIVITY_NEW_TASK), 0),
            true);

    // assume fail: when successful, all will be reset.
    notification.successful = false;
    notification.doneTitle = context.getString(R.string.sync_upload_fail);
    notification.doneText = context.getString(R.string.sync_upload_fail_message, castTitle);

    notification.doneIntent = PendingIntent.getActivity(context, 0,
            new Intent(Intent.ACTION_VIEW, cast).addFlags(Intent.FLAG_ACTIVITY_NEW_TASK), 0);

    final NotificationManager nm = (NotificationManager) context.getSystemService(Context.NOTIFICATION_SERVICE);
    final NotificationProgressListener tpl = new NotificationProgressListener(nm, notification, 0,
            (int) ContentUris.parseId(cast));

    try {
        final AssetFileDescriptor afd = context.getContentResolver().openAssetFileDescriptor(localFile, "r");
        final long max = afd.getLength();

        tpl.setSize(max);

        switch (uploadType) {
        case RAW_PUT:
            updatedCastMedia = uploadContent(context, tpl, serverPath, localFile, contentType);
            break;
        case FORM_POST:
            updatedCastMedia = uploadContentUsingForm(context, tpl, serverPath, localFile, contentType);
            break;

        default:
            throw new IllegalArgumentException("unhandled upload type: " + uploadType);
        }

        notification.doneTitle = context.getString(R.string.sync_upload_success);
        notification.doneText = context.getString(R.string.sync_upload_success_message, castTitle);
        notification.successful = true;

    } catch (final NetworkProtocolException e) {
        notification.setUnsuccessful(e.getLocalizedMessage());
        throw e;
    } catch (final IOException e) {
        notification.setUnsuccessful(e.getLocalizedMessage());
        throw e;
    } finally {
        tpl.done();
    }
    return updatedCastMedia;
}

From source file:com.kjsaw.alcosys.ibacapp.IBAC.java

private void initBeepSound() {
    if (mediaPlayerBeep == null) {
        setVolumeControlStream(AudioManager.STREAM_MUSIC);
        mediaPlayerBeep = new MediaPlayer();
        mediaPlayerBeep.setAudioStreamType(AudioManager.STREAM_MUSIC);
        mediaPlayerBeep.setOnCompletionListener(beepListener);

        AssetFileDescriptor fileBeep = getResources().openRawResourceFd(R.raw.beep);
        try {//from   w w  w.j  a  va 2s  . c  o m
            mediaPlayerBeep.setDataSource(fileBeep.getFileDescriptor(), fileBeep.getStartOffset(),
                    fileBeep.getLength());
            fileBeep.close();
            mediaPlayerBeep.setVolume(BEEP_VOLUME, BEEP_VOLUME);
            mediaPlayerBeep.prepare();
        } catch (IOException e) {
            mediaPlayerBeep = null;
        }
    }
}

From source file:fr.bde_eseo.eseomega.GantierActivity.java

@Override
public void onResume() {
    super.onResume();

    /*//ww w. j  ava2  s.c o m
    senAccelerometer = senSensorManager.getDefaultSensor(Sensor.TYPE_GYROSCOPE);
    senSensorManager.registerListener(this, senAccelerometer, SensorManager.SENSOR_DELAY_GAME);*/
    initListeners();

    // wait for one second until gyroscope and magnetometer/accelerometer
    // data is initialised then scedule the complementary filter task
    fuseTimer.scheduleAtFixedRate(new calculateFusedOrientationTask(), 1000, TIME_CONSTANT);

    // if not playing
    if (!mediaPlayer.isPlaying()) {
        AssetFileDescriptor descriptor = null;
        try {
            descriptor = getAssets().openFd("wabe.mp3");
            mediaPlayer.setDataSource(descriptor.getFileDescriptor(), descriptor.getStartOffset(),
                    descriptor.getLength());
            descriptor.close();
            mediaPlayer.prepare();
            mediaPlayer.setLooping(true);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    // Start music !
    mediaPlayer.start();
}

From source file:com.kjsaw.alcosys.ibacapp.IBAC.java

private void initCaptureSound() {
    if (mediaPlayerCapture == null) {
        setVolumeControlStream(AudioManager.STREAM_MUSIC);
        mediaPlayerCapture = new MediaPlayer();
        mediaPlayerCapture.setAudioStreamType(AudioManager.STREAM_MUSIC);
        mediaPlayerCapture.setOnCompletionListener(captureListener);

        AssetFileDescriptor fileBeep = getResources().openRawResourceFd(R.raw.camera_flash);
        try {/*  w w  w.j  ava  2 s. c  o  m*/
            mediaPlayerCapture.setDataSource(fileBeep.getFileDescriptor(), fileBeep.getStartOffset(),
                    fileBeep.getLength());
            fileBeep.close();
            mediaPlayerCapture.setVolume(CAPTURE_VOLUME, CAPTURE_VOLUME);
            mediaPlayerCapture.prepare();
        } catch (IOException e) {
            mediaPlayerCapture = null;
        }
    }
}

From source file:edu.mit.mobile.android.locast.net.NetworkClient.java

/**
 * Uploads content using HTTP PUT./*ww  w.  j  a v  a2s.c om*/
 *
 * @param context
 * @param progressListener
 * @param serverPath
 *            the URL fragment to which the content should be PUT
 * @param localFile
 *            the local file that should be stored on the server
 * @param contentType
 *            MIME type of the file to be uploaded
 * @return
 * @throws NetworkProtocolException
 * @throws IOException
 * @throws JSONException
 * @throws IllegalStateException
 */
public JSONObject uploadContent(Context context, TransferProgressListener progressListener, String serverPath,
        Uri localFile, String contentType)
        throws NetworkProtocolException, IOException, IllegalStateException, JSONException {

    if (localFile == null) {
        throw new IOException("Cannot send. Content item does not reference a local file.");
    }

    final InputStream is = getFileStream(context, localFile);

    // next step is to send the file contents.
    final String putUrl = getFullUrlAsString(serverPath);
    final HttpPut r = new HttpPut(putUrl);

    if (DEBUG) {
        Log.d(TAG, "HTTP PUTting " + localFile + " (mimetype: " + contentType + ") to " + putUrl);
    }

    r.setHeader("Content-Type", contentType);

    final AssetFileDescriptor afd = context.getContentResolver().openAssetFileDescriptor(localFile, "r");

    final InputStreamWatcher isw = new InputStreamWatcher(is, progressListener);

    r.setEntity(new InputStreamEntity(isw, afd.getLength()));

    final HttpResponse c = this.execute(r);
    checkStatusCode(c, true);
    return toJsonObject(c);
}

From source file:com.fa.mastodon.activity.ComposeActivity.java

private boolean onCommitContentInternal(InputContentInfoCompat inputContentInfo, int flags) {
    if ((flags & InputConnectionCompat.INPUT_CONTENT_GRANT_READ_URI_PERMISSION) != 0) {
        try {//from w w w .j  a v a  2  s . co m
            inputContentInfo.requestPermission();
        } catch (Exception e) {
            Log.e(TAG, "InputContentInfoCompat#requestPermission() failed." + e.getMessage());
            return false;
        }
    }

    // Determine the file size before putting handing it off to be put in the queue.
    Uri uri = inputContentInfo.getContentUri();
    long mediaSize;
    AssetFileDescriptor descriptor = null;
    try {
        descriptor = getContentResolver().openAssetFileDescriptor(uri, "r");
    } catch (FileNotFoundException e) {
        // Eat this exception, having the descriptor be null is sufficient.
    }
    if (descriptor != null) {
        mediaSize = descriptor.getLength();
        try {
            descriptor.close();
        } catch (IOException e) {
            // Just eat this exception.
        }
    } else {
        mediaSize = MEDIA_SIZE_UNKNOWN;
    }
    pickMedia(uri, mediaSize);

    currentInputContentInfo = inputContentInfo;
    currentFlags = flags;

    return true;
}

From source file:org.hermes.android.NotificationsController.java

public void playOutChatSound() {
    if (!inChatSoundEnabled) {
        return;/*from   w w w  . j a v a2 s.  com*/
    }
    try {
        if (audioManager.getRingerMode() == AudioManager.RINGER_MODE_SILENT) {
            return;
        }
    } catch (Exception e) {
        FileLog.e("tmessages", e);
    }
    notificationsQueue.postRunnable(new Runnable() {
        @Override
        public void run() {
            try {
                if (mediaPlayerOut == null) {
                    AssetFileDescriptor assetFileDescriptor = ApplicationLoader.applicationContext
                            .getResources().openRawResourceFd(R.raw.sound_out);
                    if (assetFileDescriptor != null) {
                        mediaPlayerOut = new MediaPlayer();
                        mediaPlayerOut.setAudioStreamType(AudioManager.STREAM_SYSTEM);
                        mediaPlayerOut.setDataSource(assetFileDescriptor.getFileDescriptor(),
                                assetFileDescriptor.getStartOffset(), assetFileDescriptor.getLength());
                        mediaPlayerOut.setLooping(false);
                        assetFileDescriptor.close();
                        mediaPlayerOut.prepare();
                    }
                }
                mediaPlayerOut.start();
            } catch (Exception e) {
                FileLog.e("tmessages", e);
            }
        }
    });
}

From source file:org.hermes.android.NotificationsController.java

private void playInChatSound() {
    if (!inChatSoundEnabled) {
        return;/*from   w ww. j  a v a 2  s  .  c om*/
    }
    try {
        if (audioManager.getRingerMode() == AudioManager.RINGER_MODE_SILENT) {
            return;
        }
    } catch (Exception e) {
        FileLog.e("tmessages", e);
    }

    try {
        SharedPreferences preferences = ApplicationLoader.applicationContext
                .getSharedPreferences("Notifications", Context.MODE_PRIVATE);
        int notify_override = preferences.getInt("notify2_" + openned_dialog_id, 0);
        if (notify_override == 3) {
            int mute_until = preferences.getInt("notifyuntil_" + openned_dialog_id, 0);
            if (mute_until >= ConnectionsManager.getInstance().getCurrentTime()) {
                notify_override = 2;
            }
        }
        if (notify_override == 2) {
            return;
        }
        notificationsQueue.postRunnable(new Runnable() {
            @Override
            public void run() {
                if (lastSoundPlay > System.currentTimeMillis() - 500) {
                    return;
                }
                try {
                    if (mediaPlayerIn == null) {
                        AssetFileDescriptor assetFileDescriptor = ApplicationLoader.applicationContext
                                .getResources().openRawResourceFd(R.raw.sound_in);
                        if (assetFileDescriptor != null) {
                            mediaPlayerIn = new MediaPlayer();
                            mediaPlayerIn.setAudioStreamType(AudioManager.STREAM_SYSTEM);
                            mediaPlayerIn.setDataSource(assetFileDescriptor.getFileDescriptor(),
                                    assetFileDescriptor.getStartOffset(), assetFileDescriptor.getLength());
                            mediaPlayerIn.setLooping(false);
                            assetFileDescriptor.close();
                            mediaPlayerIn.prepare();
                        }
                    }
                    mediaPlayerIn.start();
                } catch (Exception e) {
                    FileLog.e("tmessages", e);
                }
            }
        });
        /*String choosenSoundPath = null;
        String defaultPath = Settings.System.DEFAULT_NOTIFICATION_URI.getPath();
                
        choosenSoundPath = preferences.getString("sound_path_" + openned_dialog_id, null);
        boolean isChat = (int)(openned_dialog_id) < 0;
        if (isChat) {
        if (choosenSoundPath != null && choosenSoundPath.equals(defaultPath)) {
            choosenSoundPath = null;
        } else if (choosenSoundPath == null) {
            choosenSoundPath = preferences.getString("GroupSoundPath", defaultPath);
        }
        } else {
        if (choosenSoundPath != null && choosenSoundPath.equals(defaultPath)) {
            choosenSoundPath = null;
        } else if (choosenSoundPath == null) {
            choosenSoundPath = preferences.getString("GlobalSoundPath", defaultPath);
        }
        }
                
        if (choosenSoundPath != null && !choosenSoundPath.equals("NoSound")) {
        if (lastMediaPlayerUri == null || !choosenSoundPath.equals(lastMediaPlayerUri)) {
            lastMediaPlayerUri = choosenSoundPath;
            mediaPlayer.reset();
            mediaPlayer.setAudioStreamType(AudioManager.STREAM_NOTIFICATION);
            if (choosenSoundPath.equals(defaultPath)) {
                mediaPlayer.setDataSource(ApplicationLoader.applicationContext, Settings.System.DEFAULT_NOTIFICATION_URI);
            } else {
                mediaPlayer.setDataSource(ApplicationLoader.applicationContext, Uri.parse(choosenSoundPath));
            }
            mediaPlayer.prepare();
        }
        mediaPlayer.start();
        }*/
    } catch (Exception e) {
        FileLog.e("tmessages", e);
    }
}

From source file:com.keylesspalace.tusky.ComposeActivity.java

private boolean onCommitContentInternal(InputContentInfoCompat inputContentInfo, int flags) {
    if ((flags & InputConnectionCompat.INPUT_CONTENT_GRANT_READ_URI_PERMISSION) != 0) {
        try {//from   w  ww  . ja  va2s .  c om
            inputContentInfo.requestPermission();
        } catch (Exception e) {
            Log.e(TAG, "InputContentInfoCompat#requestPermission() failed." + e.getMessage());
            return false;
        }
    }

    // Determine the file size before putting handing it off to be put in the queue.
    Uri uri = inputContentInfo.getContentUri();
    long mediaSize;
    AssetFileDescriptor descriptor = null;
    try {
        descriptor = getContentResolver().openAssetFileDescriptor(uri, "r");
    } catch (FileNotFoundException e) {
        Log.d(TAG, Log.getStackTraceString(e));
        // Eat this exception, having the descriptor be null is sufficient.
    }
    if (descriptor != null) {
        mediaSize = descriptor.getLength();
        try {
            descriptor.close();
        } catch (IOException e) {
            // Just eat this exception.
        }
    } else {
        mediaSize = MediaUtils.MEDIA_SIZE_UNKNOWN;
    }
    pickMedia(uri, mediaSize);

    currentInputContentInfo = inputContentInfo;
    currentFlags = flags;

    return true;
}