构建android上多媒体apk

来源:互联网 发布:vscode支持xp吗 编辑:程序博客网 时间:2024/05/17 13:08

1.音频的使用,

a.比如说你现在在播放音乐界面则可以在activity的oncreate中setVolumeControlStream(AudioManager.STREAM_MUSIC);表示当调整音量时会调整系统的音乐音量。

b.使你的apk具有监听外部音频控制按钮的功能,例如实现线控播放,下一首,调整音量等。

<span style="font-size:18px;">注册广播,public class RemoteControlReceiver extends BroadcastReceiver {    @Override    public void onReceive(Context context, Intent intent) {        if (Intent.ACTION_MEDIA_BUTTON.equals(intent.getAction())) {            KeyEvent event = (KeyEvent)intent.getParcelableExtra(Intent.EXTRA_KEY_EVENT);            if (KeyEvent.KEYCODE_MEDIA_PLAY == event.getKeyCode()) {                // Handle key press.            }        }    }}</span>

<span style="font-size:18px;"><receiver android:name=".RemoteControlReceiver">    <intent-filter>        <action android:name="android.intent.action.MEDIA_BUTTON" />    </intent-filter></receiver></span>

<span style="font-size:18px;">监听AudioManager am = mContext.getSystemService(Context.AUDIO_SERVICE);...// Start listening for button pressesam.registerMediaButtonEventReceiver(RemoteControlReceiver);...// Stop listening for button pressesam.unregisterMediaButtonEventReceiver(RemoteControlReceiver);</span>
c.协调不同app间如果都想要播放音频的情况。在想要播放前需要申请

<span style="font-size:18px;">AudioManager am = mContext.getSystemService(Context.AUDIO_SERVICE);...// Request audio focus for playbackint result = am.requestAudioFocus(afChangeListener,                                 // Use the music stream.                                 AudioManager.STREAM_MUSIC,                                 // Request permanent focus.                                 AudioManager.AUDIOFOCUS_GAIN);if (result == AudioManager.AUDIOFOCUS_REQUEST_GRANTED) {    am.registerMediaButtonEventReceiver(RemoteControlReceiver);    // Start playback.}适当的时候需要// Abandon audio focus when playback completeam.abandonAudioFocus(afChangeListener);</span>

d.在播放音频时如果被外部打断时该如何做,

<span style="font-size:18px;">AudioManager.OnAudioFocusChangeListener afChangeListener =    new AudioManager.OnAudioFocusChangeListener() {        public void onAudioFocusChange(int focusChange) {            if (focusChange == AUDIOFOCUS_LOSS_TRANSIENT) {                // Pause playback            } else if (focusChange == AudioManager.AUDIOFOCUS_GAIN) {                // Resume playback            } else if (focusChange == AudioManager.AUDIOFOCUS_LOSS) {                am.unregisterMediaButtonEventReceiver(RemoteControlReceiver);                am.abandonAudioFocus(afChangeListener);                // Stop playback            }        }    };如果是短暂的打断,其实还可以步暂停,可以通过调小音量来让其他应用的声音能够听得见。在恢复后调大音量。OnAudioFocusChangeListener afChangeListener = new OnAudioFocusChangeListener() {    public void onAudioFocusChange(int focusChange) {        if (focusChange == AUDIOFOCUS_LOSS_TRANSIENT_CAN_DUCK) {            // Lower the volume        } else if (focusChange == AudioManager.AUDIOFOCUS_GAIN) {            // Raise it back to normal        }    }};</span>

e.如果播放音乐的时候使用了很高的音量,则可能会出现噪音,系统提供了一个方法来监听

<span style="font-size:18px;">private class NoisyAudioStreamReceiver extends BroadcastReceiver {    @Override    public void onReceive(Context context, Intent intent) {        if (AudioManager.ACTION_AUDIO_BECOMING_NOISY.equals(intent.getAction())) {            // Pause the playback        }    }}private IntentFilter intentFilter = new IntentFilter(AudioManager.ACTION_AUDIO_BECOMING_NOISY);private void startPlayback() {    registerReceiver(myNoisyAudioStreamReceiver(), intentFilter);}private void stopPlayback() {    unregisterReceiver(myNoisyAudioStreamReceiver);}</span>

2.照相拍照
拍照首先要硬件支持,所以要

<span style="font-size:18px;"><manifest ... >    <uses-feature android:name="android.hardware.camera"                  android:required="true" />    ...</manifest></span>
a.现在手机上一般都至少有一个相机应用了,所以可以使用手机上已经存在的支持照相功能的apk来完成照相。

<span style="font-size:18px;">static final int REQUEST_IMAGE_CAPTURE = 1;private void dispatchTakePictureIntent() {    Intent takePictureIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);    if (takePictureIntent.resolveActivity(getPackageManager()) != null) {        startActivityForResult(takePictureIntent, REQUEST_IMAGE_CAPTURE);    }}</span>

然后接收,一般apk如果你需要的图片仅仅是一个缩略图的话可以这样做,

<span style="font-size:18px;">@Overrideprotected void onActivityResult(int requestCode, int resultCode, Intent data) {    if (requestCode == REQUEST_IMAGE_CAPTURE && resultCode == RESULT_OK) {        Bundle extras = data.getExtras();        Bitmap imageBitmap = (Bitmap) extras.get("data");  //接收缩略图        mImageView.setImageBitmap(imageBitmap);    }}</span>


但是你可能需要的图片是全图高清的话,可以这样做,需要读写权限,需要传递一个Uri

<span style="font-size:18px;"><manifest ...>    <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />    ...</manifest></span>

<span style="font-size:18px;">static final int REQUEST_TAKE_PHOTO = 1;private void dispatchTakePictureIntent() {    Intent takePictureIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);    // Ensure that there's a camera activity to handle the intent    if (takePictureIntent.resolveActivity(getPackageManager()) != null) {        // Create the File where the photo should go        File photoFile = null;        try {            photoFile = createImageFile();        } catch (IOException ex) {            // Error occurred while creating the File            ...        }        // Continue only if the File was successfully created        if (photoFile != null) {            takePictureIntent.putExtra(MediaStore.EXTRA_OUTPUT,                    Uri.fromFile(photoFile));            startActivityForResult(takePictureIntent, REQUEST_TAKE_PHOTO);        }    }}String mCurrentPhotoPath;private File createImageFile() throws IOException {    // Create an image file name    String timeStamp = new SimpleDateFormat("yyyyMMdd_HHmmss").format(new Date());    String imageFileName = "JPEG_" + timeStamp + "_";    File storageDir = Environment.getExternalStoragePublicDirectory(            Environment.DIRECTORY_PICTURES);    File image = File.createTempFile(        imageFileName,          ".jpg",                 storageDir         );    // Save a file: path for use with ACTION_VIEW intents    mCurrentPhotoPath = "file:" + image.getAbsolutePath();    return image;}</span>

<span style="font-size:18px;">拍照完成后,如果你选择的存储图片路径是是getExternalFilesDir(),那么图片是不会加入到Media Provider's database中的,调用下面,就可以了。private void galleryAddPic() {    Intent mediaScanIntent = new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE);    File f = new File(mCurrentPhotoPath);    Uri contentUri = Uri.fromFile(f);    mediaScanIntent.setData(contentUri);    this.sendBroadcast(mediaScanIntent);}</span>

<span style="font-size:18px;">拍完后,图片一般比较大,直接加载到ImageView上,会费内存,下面可以加些处理,让图片缩放到ImageView大小。private void setPic() {    // Get the dimensions of the View    int targetW = mImageView.getWidth();    int targetH = mImageView.getHeight();    // Get the dimensions of the bitmap    BitmapFactory.Options bmOptions = new BitmapFactory.Options();    bmOptions.inJustDecodeBounds = true;    BitmapFactory.decodeFile(mCurrentPhotoPath, bmOptions);    int photoW = bmOptions.outWidth;    int photoH = bmOptions.outHeight;    // Determine how much to scale down the image    int scaleFactor = Math.min(photoW/targetW, photoH/targetH);    // Decode the image file into a Bitmap sized to fill the View    bmOptions.inJustDecodeBounds = false;    bmOptions.inSampleSize = scaleFactor;    bmOptions.inPurgeable = true;    Bitmap bitmap = BitmapFactory.decodeFile(mCurrentPhotoPath, bmOptions);    mImageView.setImageBitmap(bitmap);}</span>

3.视频录制。与拍照类似。
<span style="font-size:18px;"><manifest ... >    <uses-feature android:name="android.hardware.camera"                  android:required="true" /></manifest></span>
a.录制
<span style="font-size:18px;">static final int REQUEST_VIDEO_CAPTURE = 1;private void dispatchTakeVideoIntent() {    Intent takeVideoIntent = new Intent(MediaStore.ACTION_VIDEO_CAPTURE);    if (takeVideoIntent.resolveActivity(getPackageManager()) != null) {        startActivityForResult(takeVideoIntent, REQUEST_VIDEO_CAPTURE);    }}</span>

b.播放
@Overrideprotected void onActivityResult(int requestCode, int resultCode, Intent data) {    if (requestCode == REQUEST_VIDEO_CAPTURE && resultCode == RESULT_OK) {        Uri videoUri = intent.getData();        mVideoView.setVideoURI(videoUri);    }}


4.自定义相机,使用系统api来定义相机功能。可以避免在android不同机型上
出现的适配问题。

1 0
原创粉丝点击