使用通知
在Android 8.0(API26)后对通知更改了一些内容,以前是通过Notification,Builder(Context context).se.来设置通知的震动、灯光、音效的设置,新内容加了NotificationChannel(通知渠道),通过NotificatonChannel来进行震动、灯光、音效的设置,且通知必须添加通知渠道,同样需进行版本判断,否则通知不会被发送。
- 首先创建NotificationManager对象
- .创建Notificationchannel对象,指定id,name,importance(根据这个播放对应的效果),也可以设置相应的震动、音效、如果没设置按默认的importance,调用NotificationManager的createNotificationChannel(NotificationChannel channel)方法
- 通过Notificationcompat.Builder(Context.Notification)对象指定channel并设置通知的各项信息,调用buid()方法创建Notifcation对象
- 调用NotificationManager的notify(id,Notification)方法发送通知
基础用法
新建NotificationTest项目
修改activity中的代码:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:id="@+id/main"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical">
<Button
android:id="@+id/send_notice"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Send notice"/>
</LinearLayout>
简单加了一个Send notice按钮
下来修改MainActivity中的代码:
public class MainActivity extends AppCompatActivity implements View.OnClickListener {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Button sendNotice = (Button) findViewById(R.id.send_notice);
sendNotice.setOnClickListener(this);
}
@SuppressLint("NotificationPermission")
@Override
public void onClick(View v) {
if (v.getId() == R.id.send_notice) {
NotificationManager manager = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
Notification notification = new NotificationCompat.Builder(this)
.setContentTitle("This is content title")
.setContentText("This is content text")
.setWhen(System.currentTimeMillis())
.setSmallIcon(R.mipmap.ic_launcher)
.setLargeIcon(BitmapFactory.decodeResource(getResources(), R.mipmap.ic_launcher))
.build();
manager.notify(1, notification);
}
}
}
上面是Android8.0版本前才能使用
在Android13,版本通知的使用发生了新的变化:
public class MainActivity extends AppCompatActivity implements View.OnClickListener {
private static final String CHANNEL_ID = "notification_channel";
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Button sendNotice = findViewById(R.id.send_notice);
sendNotice.setOnClickListener(this);
createNotificationChannel();
}
// 创建通知渠道
private void createNotificationChannel() {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
CharSequence name = "Notification Channel";
String description = "Channel for notifications";
int importance = NotificationManager.IMPORTANCE_DEFAULT;
NotificationChannel channel = new NotificationChannel(CHANNEL_ID, name, importance);
channel.setDescription(description);
NotificationManager notificationManager = getSystemService(NotificationManager.class);
notificationManager.createNotificationChannel(channel);
}
}
@SuppressLint("NotificationPermission")
@Override
public void onClick(View v) {
// 申请通知权限
if (ContextCompat.checkSelfPermission(MainActivity.this,
android.Manifest.permission.POST_NOTIFICATIONS) != PackageManager.PERMISSION_GRANTED) {
ActivityCompat.requestPermissions(MainActivity.this, new String[]{android.Manifest.permission.POST_NOTIFICATIONS}, 1);
}
if (v.getId() == R.id.send_notice) {
NotificationCompat.Builder builder = new NotificationCompat.Builder(this, CHANNEL_ID)
.setSmallIcon(R.mipmap.ic_launcher) // 设置小图标
.setContentTitle("This is content title") // 设置通知标题
.setContentText("This is content text") // 设置通知内容
.setPriority(NotificationCompat.PRIORITY_DEFAULT) // 设置通知优先级
.setLargeIcon(BitmapFactory.decodeResource(getResources(), R.mipmap.ic_launcher)) // 设置大图标
.setWhen(System.currentTimeMillis()); // 设置通知时间
NotificationManager notificationManager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
notificationManager.notify(1, builder.build()); // 发送通知
}
}
}
现在可以为弹出的消息设置点击事件:
public class MainActivity extends AppCompatActivity implements View.OnClickListener {
private static final String CHANNEL_ID = "notification_channel";
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Button sendNotice = findViewById(R.id.send_notice);
sendNotice.setOnClickListener(this);
createNotificationChannel();
}
private void createNotificationChannel() {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
CharSequence name = "Notification Channel";
String description = "Channel for notifications";
int importance = NotificationManager.IMPORTANCE_DEFAULT;
NotificationChannel channel = new NotificationChannel(CHANNEL_ID, name, importance);
channel.setDescription(description);
NotificationManager notificationManager = getSystemService(NotificationManager.class);
notificationManager.createNotificationChannel(channel);
}
}
@SuppressLint("NotificationPermission")
@Override
public void onClick(View v) {
//点击通知后跳转页面
Intent intent = new Intent(MainActivity.this,MainActivity2.class);
PendingIntent pi = PendingIntent.getActivity(MainActivity.this, 0, intent, PendingIntent.FLAG_IMMUTABLE);
//申请通知权限
if (ContextCompat.checkSelfPermission(MainActivity.this,
android.Manifest.permission.POST_NOTIFICATIONS) != PackageManager.PERMISSION_GRANTED) {
ActivityCompat.requestPermissions(MainActivity.this, new String[]{android.Manifest.permission.POST_NOTIFICATIONS}, 1);
}
if (v.getId() == R.id.send_notice) {
NotificationCompat.Builder builder = new NotificationCompat.Builder(this, CHANNEL_ID)
.setSmallIcon(R.mipmap.ic_launcher)
.setContentTitle("This is content title")
.setContentText("This is content text")
.setPriority(NotificationCompat.PRIORITY_DEFAULT)
.setLargeIcon(BitmapFactory.decodeResource(getResources(), R.mipmap.ic_launcher))
.setWhen(System.currentTimeMillis())
.setContentIntent(pi);
NotificationManager notificationManager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
notificationManager.notify(1, builder.build());
}
}
}
但是我们发现,在点击了消息后,虽然跳进了新活动,但是消息却没有消失
我们可以在NotificationCompat.Builder中加上一个setAutoCancel方法(填true)
NotificationCompat.Builder builder = new NotificationCompat.Builder(this, CHANNEL_ID)
.setSmallIcon(R.mipmap.ic_launcher)
.setContentTitle("This is content title")
.setContentText("This is content text")
.setPriority(NotificationCompat.PRIORITY_DEFAULT)
.setLargeIcon(BitmapFactory.decodeResource(getResources(), R.mipmap.ic_launcher))
.setWhen(System.currentTimeMillis())
.setContentIntent(pi)
.setAutoCancel(true);
然后是setPriority()方法,可以用于设置通知的重要程度。
一共可以选择五个常量值
我们用PRIORITY_MAX(用户必须立刻看到甚至需要做出响应)来举例:
NotificationCompat.Builder builder = new NotificationCompat.Builder(this, CHANNEL_ID)
.setSmallIcon(R.mipmap.ic_launcher)
.setContentTitle("This is content title")
.setContentText("This is content text")
.setPriority(NotificationCompat.PRIORITY_DEFAULT)
.setLargeIcon(largeIcon)
.setWhen(System.currentTimeMillis())
.setContentIntent(pi)
.setAutoCancel(true)
.setStyle(new NotificationCompat.BigTextStyle().bigText("1234567891011121314151617181920"))
.setPriority(NotificationCompat.PRIORITY_MAX);
如果没有弹出来则可能是没有授权该项目弹出消息的权限,可以再通知权限中设置
方法定义与功能说明
方法定义 | 功能说明 |
---|---|
setWhen(long) | 设置通知时间,默认为系统发出通知的时间,一般不设置。 |
setSound(Uri) | 设置自定义音乐。 |
setLargeIcon(Bitmap) | 设置通知栏下拉后的大图标。 |
setContentIntent(PendingIntent) | 设置点击通知后跳转的 Activity,即延迟 Intent 实现。 |
setAutoCancel(boolean) | 设置点击通知后是否消失,true 为消失。 |
setStyle(Notification.Style) | 设置通知的样式,如:大文本样式、大视图样式。 |
setPriority(int) | 设置通知优先级,用于 Android 8.0 以下版本。 |
setDefaults(int) | 设置通知的 LED 灯、音乐、震动等默认设置。 |
更新通知
- 使用NotificationCompat.Builder构造其创建有更新内容的通知
- 将相同的通知ld和更新内容后的通知传递给notify()方法即可实现
更新- 若之前的通知仍然可见,则系统更新
- 若之前的通知已被取消,则发送新的通知
锁屏通知
-
Android 5.0(APllevel 21)开始,通知可以显示在锁屏上。用户可以通过设置选择是否允许敏感的通知内容显示在安全的锁屏上。
-
android5.0加入一种新的模式Notification的显示等级,共有三种:
VISIBILITY PUBLIC 任何情况都会显示通知
VISIBILITY PRIVATE 显示基本信息隐藏通知内部信息
VISIBILITY SECRET 在没有锁屏的情况下才能够显示
-
调用setVisibility方法
builder.setVisibility(Notification.VSIBILITY_PUBLIC);
前台服务
- 前台服务是那些被认为用户知道且在系统内存不足的时候不允许系统杀死的服务。
- 前台服务必须给状态栏提供一个通知,它被放到正在运行(Ongoing)标题之下
- 这就意味着通知只有在这个服务被终止或从前台主动移除通知后才能被解除
调用摄像头和相册
调用摄像头拍照
新建CameraAlbumTest项目
修改activity_main中的代码:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:id="@+id/main"
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; // 显示拍照图片的ImageView
private Uri imageuri; // 拍照图片的URI
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Button takephoto = findViewById(R.id.take_photo); // 获取拍照按钮
picture = findViewById(R.id.picture); // 获取显示图片的ImageView
takephoto.setOnClickListener(new View.OnClickListener() { // 设置按钮点击事件监听器
@Override
public void onClick(View v) {
// 创建保存图片的File对象
File outputImage = new File(getExternalCacheDir(), "out_image.jpg");
try {
if (outputImage.exists()) {
outputImage.delete(); // 如果文件存在,删除旧文件
}
outputImage.createNewFile(); // 创建新文件
} catch (IOException e) {
e.printStackTrace(); // 处理IO异常
}
// 获取文件的URI
if (Build.VERSION.SDK_INT >= 24) {
// Android 7.0及以上使用FileProvider
imageuri = FileProvider.getUriForFile(MainActivity.this, "com.example.cameraalbumtest.fileprovider", outputImage);
} else {
// Android 7.0以下直接获取文件的URI
imageuri = Uri.fromFile(outputImage);
}
// 启动系统相机应用
Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
intent.putExtra(MediaStore.EXTRA_OUTPUT, imageuri);
startActivityForResult(intent, Take_Photo);
}
});
}
@SuppressLint("MissingSuperCall")
@Override
protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
if (requestCode == Take_Photo && resultCode == RESULT_OK) { // 检查请求码和结果码
try {
// 显示拍摄的照片
Bitmap bitmap = BitmapFactory.decodeStream(getContentResolver().openInputStream(imageuri));
picture.setImageBitmap(bitmap);
} catch (FileNotFoundException e) {
e.printStackTrace(); // 处理文件未找到异常
}
}
}
}
还需要在AndroidManifest中对内容提供器进行注册:
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools">
<application
android:allowBackup="true"
android:dataExtractionRules="@xml/data_extraction_rules"
android:fullBackupContent="@xml/backup_rules"
android:icon="@mipmap/ic_launcher"
android:label="@string/app_name"
android:roundIcon="@mipmap/ic_launcher_round"
android:supportsRtl="true"
android:theme="@style/Theme.CameraAlbumTest"
tools:targetApi="31">
<!-- 定义MainActivity为应用的启动Activity -->
<activity
android:name=".MainActivity"
android:exported="true">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<!-- 配置FileProvider -->
<provider
android:authorities="com.example.cameraalbumtest.fileprovider"
android:name="androidx.core.content.FileProvider"
android:exported="false"
android:grantUriPermissions="true">
<meta-data
android:name="android.support.FILE_PROVIDER_PATHS"
android:resource="@xml/file_paths"/>
</provider>
</application>
</manifest>
下来再在xml目录下新建一个file_paths文件:
<?xml version="1.0" encoding="utf-8"?>
<paths xmlns:android="http://schemas.android.com/apk/res/android">
<!-- 定义external-path以允许访问外部存储的路径 -->
<external-path
name="external_files"
path="." />
</paths>
从相册中选择照片
修改activity_main中的代码:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:id="@+id/main"
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"/>
<Button
android:id="@+id/choose_from_album"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="Choose From Album"/>
<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; // 显示图片的ImageView
private Uri imageuri; // 存储图片的Uri
public static final int CHOOSE_PHOTO = 2; // 选择照片请求码
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main); // 设置布局
Button takephoto = (Button) findViewById(R.id.take_photo); // 拍照按钮
Button chooseFromAlbum = (Button) findViewById(R.id.choose_from_album); // 从相册选择照片按钮
picture = (ImageView) findViewById(R.id.picture); // 初始化ImageView
// 设置拍照按钮点击事件
takephoto.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
File outputImage = new File(getExternalCacheDir(), "out_image.jpg"); // 创建图片文件
try {
if (outputImage.exists()) {
outputImage.delete(); // 如果文件存在,则删除
}
outputImage.createNewFile(); // 创建新文件
} catch (IOException e) {
e.printStackTrace();
}
// 处理 Android 7.0 及以上版本的文件Uri
if (Build.VERSION.SDK_INT >= 24) {
imageuri = FileProvider.getUriForFile(MainActivity.this, "com.example.cameraalbumtest.fileprovider", outputImage);
} else {
imageuri = Uri.fromFile(outputImage);
}
// 启动相机应用
Intent intent = new Intent("android.media.action.IMAGE_CAPTURE");
intent.putExtra(MediaStore.EXTRA_OUTPUT, imageuri);
startActivityForResult(intent, Take_Photo);
}
});
// 设置从相册选择照片按钮点击事件
chooseFromAlbum.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
// 检查权限
if (ContextCompat.checkSelfPermission(v.getContext(), Manifest.permission.CAMERA) != PackageManager.PERMISSION_GRANTED ||
ContextCompat.checkSelfPermission(v.getContext(), Manifest.permission.READ_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED ||
ContextCompat.checkSelfPermission(v.getContext(), Manifest.permission.WRITE_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED) {
// 请求权限
ActivityCompat.requestPermissions(MainActivity.this, new String[]{
Manifest.permission.CAMERA,
Manifest.permission.READ_EXTERNAL_STORAGE,
Manifest.permission.WRITE_EXTERNAL_STORAGE}, 10);
} else {
openAlbum(); // 打开相册
}
}
});
}
@SuppressLint("MissingSuperCall")
@Override
protected void onActivityResult(int requestCode, int resultCode, @Nullable 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;
case CHOOSE_PHOTO:
if (resultCode == RESULT_OK) {
// 处理选择的照片
if (Build.VERSION.SDK_INT >= 19) {
handleImageOnKitKat(data);
} else {
handleImageBeforeKitKat(data);
}
}
break;
default:
break;
}
}
private void handleImageBeforeKitKat(Intent data) {
Uri uri = data.getData();
String imagePath = getImagePath(uri, null);
displayImage(imagePath); // 显示照片
}
@SuppressLint("Range")
private String getImagePath(Uri uri, String selection) {
String path = null;
Cursor cursor = getContentResolver().query(uri, null, selection, null, null);
if (cursor != null) {
if (cursor.moveToFirst()) {
path = cursor.getString(cursor.getColumnIndex(MediaStore.Images.Media.DATA)); // 获取图片路径
}
cursor.close();
}
return path;
}
private void handleImageOnKitKat(Intent data) {
String imagePath = null;
Uri uri = data.getData();
if (DocumentsContract.isDocumentUri(this, uri)) {
String docId = DocumentsContract.getDocumentId(uri);
if ("com.android.providers.media.documents".equals(uri.getAuthority())) {
String id = docId.split(":")[1];
String selection = MediaStore.Images.Media._ID + "=" + id;
imagePath = getImagePath(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, selection);
} else if ("com.android.providers.downloads.documents".equals(uri.getAuthority())) {
Uri contentUri = ContentUris.withAppendedId(Uri.parse("content://downloads/public_downloads"), Long.valueOf(docId));
imagePath = getImagePath(contentUri, null);
}
} else if ("content".equalsIgnoreCase(uri.getScheme())) {
imagePath = getImagePath(uri, null); // 修正此处调用getImagePath
} else if ("file".equalsIgnoreCase(uri.getScheme())) {
imagePath = uri.getPath();
}
displayImage(imagePath); // 显示照片
}
private void displayImage(String imagePath) {
if (imagePath != null) {
Bitmap bitmap = BitmapFactory.decodeFile(imagePath);
picture.setImageBitmap(bitmap); // 设置图片到ImageView
} else {
播放多媒体文件
播放音频
新建PlayAudioTest项目
修改activity_main中的代码:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:id="@+id/main"
android:orientation="vertical"
android:layout_width="match_parent"
android:layout_height="match_parent">
<Button
android:id="@+id/play"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="Play"/>
<Button
android:id="@+id/pause"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="Pause"/>
<Button
android:id="@+id/stop"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="Stop"/>
</LinearLayout>
简单放置了三个按钮
修改MainActivity中的代码:
public class MainActivity extends AppCompatActivity implements View.OnClickListener {
private MediaPlayer mediaPlayer = new MediaPlayer(); // 创建MediaPlayer对象
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main); // 设置布局文件
Button play = (Button) findViewById(R.id.play); // 获取播放按钮
Button pause = (Button) findViewById(R.id.pause); // 获取暂停按钮
Button stop = (Button) findViewById(R.id.stop); // 获取停止按钮
play.setOnClickListener(this); // 设置播放按钮的点击监听
pause.setOnClickListener(this); // 设置暂停按钮的点击监听
stop.setOnClickListener(this); // 设置停止按钮的点击监听
// 检查写入外部存储权限
if (ContextCompat.checkSelfPermission(MainActivity.this, Manifest.permission.WRITE_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED) {
// 请求写入外部存储权限
ActivityCompat.requestPermissions(MainActivity.this, new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE}, 1);
} else {
initMediaPlayer(); // 初始化MediaPlayer
}
}
private void initMediaPlayer() {
try {
// 设置音乐文件路径
File file = new File(Environment.getExternalStorageDirectory(), "music.mp3");
mediaPlayer.setDataSource(file.getPath()); // 设置音频文件的数据源
mediaPlayer.prepare();
// 准备MediaPlayer
} catch (Exception e) {
e.printStackTrace(); // 捕获异常并打印堆栈信息
}
}
@SuppressLint("MissingSuperCall")
@Override
public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
switch (requestCode) {
case 1:
if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
initMediaPlayer(); // 如果用户授予权限,初始化MediaPlayer
} else {
Toast.makeText(this, "拒绝权限将无法使用程序", Toast.LENGTH_SHORT).show(); // 显示权限拒绝提示
finish(); // 关闭Activity
}
break;
default:
}
}
@Override
public void onClick(View v) {
if (v.getId() == R.id.play) { // 播放按钮点击事件
if (!mediaPlayer.isPlaying()) {
mediaPlayer.start(); // 开始播放音乐
}
} else if (v.getId() == R.id.pause) { // 暂停按钮点击事件
if (mediaPlayer.isPlaying()) {
mediaPlayer.pause(); // 暂停播放音乐
}
} else if (v.getId() == R.id.stop) { // 停止按钮点击事件
if (mediaPlayer.isPlaying()) {
mediaPlayer.stop(); // 停止播放音乐
initMediaPlayer(); // 重新初始化MediaPlayer
}
}
}
@Override
protected void onDestroy() {
super.onDestroy();
if (mediaPlayer != null) {
mediaPlayer.stop(); // 停止播放音乐
mediaPlayer.release(); // 释放MediaPlayer资源
}
}
}
播放视频
新建PlayAudioTest项目
修改activity_main代码:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:id="@+id/main"
android:layout_width="match_parent"
android:layout_height="match_parent">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="vertical">
<Button
android:id="@+id/play"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="Play"/>
<Button
android:id="@+id/pause"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="Pause"/>
<Button
android:id="@+id/replay"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="Replay"/>
</LinearLayout>
<VideoView
android:id="@+id/video_view"
android:layout_width="match_parent"
android:layout_height="wrap_content"/>
</LinearLayout>
修改MainActivity中的代码;
public class MainActivity extends AppCompatActivity implements View.OnClickListener {
private VideoView videoView; // 声明 VideoView 对象,用于播放视频
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main); // 设置布局文件
videoView = (VideoView) findViewById(R.id.video_view); // 获取布局中的 VideoView 控件
Button play = (Button) findViewById(R.id.play); // 获取播放按钮
Button pause = (Button) findViewById(R.id.pause); // 获取暂停按钮
Button replay = (Button) findViewById(R.id.replay); // 获取重播按钮
// 为按钮设置点击监听器
play.setOnClickListener(this);
pause.setOnClickListener(this);
replay.setOnClickListener(this);
// 检查并请求写入外部存储的权限
if (ContextCompat.checkSelfPermission(MainActivity.this, Manifest.permission.WRITE_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED) {
ActivityCompat.requestPermissions(MainActivity.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()); // 设置视频路径
}
// 处理权限请求的结果
@SuppressLint("MissingSuperCall")
@Override
public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
switch (requestCode) {
case 1:
if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
initVideoPath(); // 如果权限被授予,初始化视频路径
} else {
Toast.makeText(this, "拒绝权限将无法使用程序", Toast.LENGTH_SHORT).show(); // 提示用户权限被拒绝
finish(); // 关闭活动
}
break;
default:
}
}
// 按钮点击事件处理
@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;
default:
break;
}
}
// 在活动销毁时释放资源
@Override
protected void onDestroy() {
super.onDestroy();
if (videoView != null) {
videoView.suspend(); // 暂停视频播放
}
}
}
已经到底啦!!