一、调用摄像头和相册
1.调用摄像头拍照
在activity_main.xml文件,添加一个Button用于打开摄像头进行拍照,添加ImageView用于将图片显示出来。
<LinearLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="match_parent"
android:layout_height="match_parent">
<Button
android:id="@+id/take_photo"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="take photo"/>
<ImageView
android:id="@+id/picture"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center_horizontal"/>
</LinearLayout>
MainActivity文件中代码
public class MainActivity extends AppCompatActivity {
public static final int TAKE_PHOTO = 1;
private ImageView picture;
//图片本地的真实路径
private Uri imageUri;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Button takePhoto = (Button) findViewById(R.id.take_photo);
picture = (ImageView) findViewById(R.id.picture);
takePhoto.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
//用于存放拍下的照片
File outputImage = new File(getExternalCacheDir(), "output_image.jpg");
try {
if(outputImage.exists()){
outputImage.delete();
}
outputImage.createNewFile();
} catch (IOException e) {
e.printStackTrace();
}
if(Build.VERSION.SDK_INT >= 24){
//File对象转换为Uri标识对象
imageUri = FileProvider.getUriForFile(MainActivity.this, "com.launcher.cameraalbumtest.fileprovider", outputImage);
}else{
//指定图片的输出地址
imageUri = Uri.fromFile(outputImage);
}
//隐式Intent,启动相机程序
Intent intent = new Intent("android.media.action.IMAGE_CAPTURE");
intent.putExtra(MediaStore.EXTRA_OUTPUT, imageUri);
startActivityForResult(intent, TAKE_PHOTO);
}
});
}
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
switch (requestCode){
case TAKE_PHOTO:
if(resultCode == RESULT_OK){
try {
//拍照成功后显示图片
Bitmap bitmap = BitmapFactory.decodeStream(getContentResolver().openInputStream(imageUri));
picture.setImageBitmap(bitmap);
} catch (FileNotFoundException e) {
e.printStackTrace();
}
}
break;
default:
break;
}
}
}
应用关联缓存目录:
SD卡中专门用于存放当前应用缓存数据的位置,调用getExternalCacheDir()方法可以得到这个目录,具体路径:/sdcard/Android/data/<package name>/cache。
Android 6.0以后读写SD卡被列为危险权限,如果将图片存放到其他目录要进行运行时权限处理,使用应用关联缓存目录可以跳过这一步。
Android 7.0以后,直接使用本地真实路径的Uri被认为是不安全的,会抛出FileUriExposedException异常,而使用FileProvider是一种特殊的内容提供器,它使用了和内容提供器类似的机制对数据进行保护,可以选择性的封装过的Uri共享给外部,从而提高应用的安全性。
2.从相册中选择照片
布局文件,放一个Button和一个ImageView,Button用来启动拍照图片并截图,ImageView用来显示截图后的照片,activity_main.xml代码如下所示:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical">
<Button
android:id="@+id/btn_photo"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="Take Photo" />
<Button
android:id="@+id/btn_album"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="Choose from Album" />
<ImageView
android:id="@+id/img_photo"
android:layout_width="300dp"
android:layout_height="300dp"
android:layout_gravity="center_horizontal" />
</LinearLayout>
MainActivity.java代码:
package com.test.photo;
import android.app.Activity;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.os.Environment;
import android.provider.MediaStore;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;
//import com.test.R;
import androidx.core.content.FileProvider;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.IOException;
/**
* Created by Administrator on 2016/5/4 0004.
*/
public class MainActivity extends Activity {
private static final int TAKE_PHOTO = 1;
private static final int CROP_PHOTO = 2;
private Button btnPhoto;
private ImageView imgPhoto;
private Uri imgUri;
private Button btnAlbum;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_photo);
btnPhoto = (Button) findViewById(R.id.btn_photo);
imgPhoto = (ImageView) findViewById(R.id.img_photo);
btnAlbum = (Button) findViewById(R.id.btn_album);
btnAlbum.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
//创建一个File对象,用于存储摄像头拍下的图片,这里命名为outputImg.jpg,并将它存放在手机SD卡的根目录下
//Environment.getExternalStorageDirectory()这个方法就是获取到手机SD卡的根目录
File outputImage = new File(Environment.getExternalStorageDirectory(), "output_image.jpg");
try {
if (outputImage.exists()) {
outputImage.delete();
}
outputImage.createNewFile();
} catch (IOException e) {
e.printStackTrace();
}
//调用Uri.fromFile 将File对象转化成Uri对象,这个Uri对象标识着outputImg.jpg这张图片的唯一地址
imgUri = Uri.fromFile(outputImage);
//构建Intent对象,Intent的action指定为android.media.action.GET_CONTENT允许用户选择特殊的数据并返回
Intent intent = new Intent("android.intent.action.GET_CONTENT");
//查看类型为image的数据
intent.setType("image/*");
//设置该图片可裁剪
intent.putExtra("crop", true);
//设置该图片可缩放
intent.putExtra("scale", true);
//调用Intent的putExtra指定图片的输出地址,这边为刚刚得到的Uri(即imgUri)对象
intent.putExtra(MediaStore.EXTRA_OUTPUT, imgUri);
startActivityForResult(intent, CROP_PHOTO);
}
});
btnPhoto.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
//创建一个File对象,用于存储摄像头拍下的图片,这里命名为outputImg.jpg,并将它存放在手机SD卡的根目录下
//Environment.getExternalStorageDirectory()这个方法就是获取到手机SD卡的根目录
File outputImg = new File(Environment.getExternalStorageDirectory(), "tempImg.jpg");
try {
if (outputImg.exists()) {
outputImg.delete();
}
outputImg.createNewFile();
} catch (IOException e) {
e.printStackTrace();
}
//调用Uri.fromFile 将File对象转化成Uri对象,这个Uri对象标识着outputImg.jpg这张图片的唯一地址
imgUri = Uri.fromFile(outputImg);
//构建Intent对象,Intent的action指定为android.media.action.IMAGE_CAPTURE表示使用系统的拍照功能
Intent intent = new Intent("android.media.action.IMAGE_CAPTURE");
//调用Intent的putExtra指定图片的输出地址,这边为刚刚得到的Uri(即imgUri)对象
intent.putExtra(MediaStore.EXTRA_OUTPUT, imgUri);
startActivityForResult(intent, TAKE_PHOTO); //启动活动
}
});
}
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
switch (requestCode) {
case TAKE_PHOTO:
if (resultCode == RESULT_OK) {
//构建Intent对象,Intent的action指定为com.android.camera.action.CROP 表示使用系裁剪图片
Intent intent = new Intent("com.android.camera.action.CROP");
//查看类型为image的数据
intent.setDataAndType(imgUri, "image/*");
//设置该图片可缩放
intent.putExtra("scale", true);
//调用Intent的putExtra指定图片的输出地址,这边为刚刚得到的Uri(即imgUri)对象
intent.putExtra(MediaStore.EXTRA_OUTPUT, imgUri);
startActivityForResult(intent, CROP_PHOTO);//启动裁剪程序
}
break;
case CROP_PHOTO:
if (resultCode == RESULT_OK) {
try {
Bitmap bitmap = BitmapFactory.decodeStream(getContentResolver().openInputStream(imgUri));
imgPhoto.setImageBitmap(bitmap);//将裁剪后的图片显示出来
} catch (FileNotFoundException e) {
e.printStackTrace();
}
}
break;
}
}
}
AndroidManifest.xml文件中声明权限:
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
二、播放多媒体文件
在安卓中播放音频文件一般用 MediaPlayer类来实现,播放视频文件主要用 VideoView类来实现。
(一)MediaPlayer 常用方法:
| MediaPlayer | 构造方法 |
|---|---|
| create | 创建一个要播放的多媒体 |
| getCurrentPosition | 得到当前播放位置 |
| getDuration | 得到文件的时间 |
| getVideoHeight | 得到视频的高度 |
| getVideoWidth | 得到视频的宽度 |
| isLooping | 是否循环播放 |
| isPlaying | 是否正在播放 |
| pause | 暂停 |
| prepare | 准备(同步) |
| prepareAsync | 准备(异步) |
| release | 释放MediaPlayer对象相关的资源 |
| reset | 重置MediaPlayer对象为刚刚创建的状态 |
| seekTo | 指定播放的位置(以毫秒为单位的时间) |
| setAudioStreamType | 设置流媒体的类型 |
| setDataSource | 设置多媒体数据来源(位置) |
| setDisplay | 设置用SurfaceHolder来显示多媒体 |
| setLooping | 设置是否循环播放 |
| setOnButteringUpdateListener | 网络流媒体的缓冲监听 |
| setOnErrorListener | 设置错误信息监听 |
| setOnVideoSizeChangedListener | 视频尺寸监听 |
| setScreenOnWhilePlaying | 设置是否使用SurfaceHolder来保持屏幕显示 |
| setVolume | 设置音量 |
| start | 开始播放 |
| stop | 停止播放 |
(二) VideoView和MediaPlaer也比较类似,主要有以下常用方法:
| MediaPlayer | 构造方法 |
|---|---|
| setVideoPath() | 设置要播放的视频文件的位置。 |
| start() | 开始或继续播放视频。 |
| pause() | 暂停播放视频。 |
| resume() | 将视频重头开始播放。 |
| seekTo() | 从指定的位置开始播放视频。 |
| isPlaying() | 判断当前是否正在播放视频。 |
| getDuration() | 获取载入的视频文件的时长。 |
1. 播放音频
activity_main.xml文件代码
package com.dak.administrator.firstcode.multi_media;
import android.Manifest;
import android.content.pm.PackageManager;
import android.media.MediaPlayer;
import android.os.Environment;
import android.support.annotation.NonNull;
import android.support.v4.app.ActivityCompat;
import android.support.v4.content.ContextCompat;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.Toast;
import com.dak.administrator.firstcode.R;
import java.io.File;
import java.io.IOException;
public class MediaActivity extends AppCompatActivity implements View.OnClickListener {
private MediaPlayer mediaPlayer = new MediaPlayer();
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_media);
Button play = findViewById(R.id.play);
Button pause = findViewById(R.id.pause);
Button stop = findViewById(R.id.stop);
play.setOnClickListener(this);
pause.setOnClickListener(this);
stop.setOnClickListener(this);
if (ContextCompat.checkSelfPermission(this, Manifest.permission.WRITE_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED) {
ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE}, 1);
}else {
initMediaPlayer();
}
}
private void initMediaPlayer() {
try {
File file = new File(Environment.getExternalStorageDirectory(), "music.mp3");//music.mp3不存在
mediaPlayer.setDataSource(file.getPath());
mediaPlayer.prepare();
} catch (IOException e) {
e.printStackTrace();
}
}
@Override
public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
super.onRequestPermissionsResult(requestCode, permissions, grantResults);
if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
initMediaPlayer();
}else {
Toast.makeText(this, "请获取存储权限", Toast.LENGTH_SHORT).show();
finish();
}
}
@Override
public void onClick(View v) {
switch (v.getId()) {
case R.id.play:
if (!mediaPlayer.isPlaying()) {
mediaPlayer.start();
}
break;
case R.id.pause:
if (mediaPlayer.isPlaying()) {
mediaPlayer.pause();
}
break;
case R.id.stop:
if (!mediaPlayer.isPlaying()) {
mediaPlayer.reset();
initMediaPlayer();
}
break;
}
}
@Override
protected void onDestroy() {
super.onDestroy();
if (mediaPlayer != null) {
mediaPlayer.stop();
mediaPlayer.release();
}
}
}
activity_main.xml文件代码:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
tools:context="com.dak.administrator.firstcode.multi_media.MediaActivity">
<Button
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:id="@+id/play"
android:text="play"
/>
<Button
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:id="@+id/pause"
android:text="pause"
/>
<Button
android:id="@+id/stop"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="stop" />
</LinearLayout>
2.播放视频
MainActivity.java文件代码
package com.dak.administrator.firstcode.multi_media;
import android.Manifest;
import android.content.pm.PackageManager;
import android.os.Environment;
import android.support.annotation.NonNull;
import android.support.v4.app.ActivityCompat;
import android.support.v4.content.ContextCompat;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.Toast;
import android.widget.VideoView;
import com.dak.administrator.firstcode.R;
import java.io.File;
public class VideoActivity extends AppCompatActivity implements View.OnClickListener {
private VideoView videoView;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_video);
Button play = findViewById(R.id.play);
Button pause = findViewById(R.id.pause);
Button replay = findViewById(R.id.replay);
videoView = findViewById(R.id.video_view);
play.setOnClickListener(this);
pause.setOnClickListener(this);
replay.setOnClickListener(this);
if (ContextCompat.checkSelfPermission(this, Manifest.permission.WRITE_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED) {
ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE}, 1);
}else {
initVideoPath();
}
}
private void initVideoPath() {
File file = new File(Environment.getExternalStorageDirectory(), "movie.mp4");
videoView.setVideoPath(file.getPath());
}
@Override
public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
super.onRequestPermissionsResult(requestCode, permissions, grantResults);
if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
initVideoPath();
}else {
Toast.makeText(this, "请获取存储权限", Toast.LENGTH_SHORT).show();
finish();
}
}
@Override
public void onClick(View v) {
switch (v.getId()) {
case R.id.play:
if (!videoView.isPlaying()) {
videoView.start();
}
break;
case R.id.pause:
if (videoView.isPlaying()) {
videoView.pause();
}
break;
case R.id.replay:
if (videoView.isPlaying()) {
videoView.resume();//重新播放
}
break;
}
}
@Override
protected void onDestroy() {
super.onDestroy();
if (videoView != null) {
videoView.suspend();//释放资源
}
}
}
activity_main.xml文件代码:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:layout_width="match_parent"
android:layout_height="match_parent">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="horizontal">
<Button
android:id="@+id/play"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_weight="1"
android:text="play" />
<Button
android:id="@+id/pause"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_weight="1"
android:text="pause" />
<Button
android:id="@+id/replay"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_weight="1"
android:text="replay" />
</LinearLayout>
<VideoView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:id="@+id/video_view"
/>
</LinearLayout>
三、程序运行
1.在模拟器上运行
(1)选择下载好的模拟器,点击运行

(2)模拟器页面布局

(3)模拟器运行结果,点击按下Take Photo按钮,打开模拟器相机

(4)点击按下Choose from Album按钮,打开模拟器相册

2.在真实机上运行
(1)我本人用的手机型号是小米手机,到设置打开手机的开发者选项,由于各个手机厂商的打开方式都不同,下面列出一些常用手机:(如有错误的或是打不开的百度搜索一下)
小米手机:连续点击三下"MIUI 版本"
华为手机:连续点击"版本号"多次,直到屏幕提示已进入开发者模式。
三星手机:连续快速点击多次“软件信息”按钮,直到屏幕提示已进入开发者模式。
OPPO手机:连续点击"版本号"多次
VIVO手机:连续点击"软件版本号"多次
魅族手机:连续点击"版本号"多次
锤子手机:连续点击"软件版本"多次
努比亚手机:连续点击"版本号"多次
(2)进入开发者选项,打开USB调试,部分手机还需要打开USB安装。而我的就一定要打开才能安装,刚开始还没打开时USB安装时,怎么都安装不上,在Android Studio软件还报了一堆错误,通过自己查找资料、翻译,最终自己遇到的这问题解决了。

(3)手机运行结果


被折叠的 条评论
为什么被折叠?



