通知(Notification)
基本使用
1. android 8以上的系统创建通知之前先要设置渠道
// 通知管理器,可以通过之后创建的通知id指定管理某个通知
NotificationManager manager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
String channelID = "my_channel_ID"; //渠道id唯一
String channelNAME = "my_channel_NAME"; // 渠道名
int level = NotificationManager.IMPORTANCE_HIGH;
// 8.0以上必须先创建通道,获取当前api和android 8的api进行比较,判断是否大于等于android8
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
NotificationChannel channel = new NotificationChannel(channelID, channelNAME, level);
manager.createNotificationChannel(channel);
}
- 创建基本的通知
NotificationCompat.Builder builder =
new NotificationCompat.Builder(NotificationActivity.this, channelID)
.setSmallIcon(R.drawable.lock) //添加小图标,该图标通知必须透明
.setContentTitle("Notification") //添加通知标题
.setContentText("hjh") //添加通知内容
.setWhen(System.currentTimeMillis()) //添加通知显示时间
.setLargeIcon(BitmapFactory.decodeResource(getResources(), R.drawable.zhibao)) //添加大图标
manager.notify(1, builder.build());// 唤醒通知
移除通知
NotificationCompat.Builder builder =
new NotificationCompat.Builder(NotificationActivity.this, channelID)
.setSmallIcon(R.drawable.lock) //添加小图标,该图标通知必须透明
.setContentTitle("Notification") //添加通知标题
.setContentText("hjh") //添加通知内容
.setWhen(System.currentTimeMillis()) //添加通知事件
.setLargeIcon(BitmapFactory.decodeResource(getResources(), R.drawable.zhibao)) //添加大图标
.setAutoCancel(true);//通知经过点击后自动取消
NotificationManager manager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
manager.cancel(1); //根据notify唤醒的id来指定关闭哪一个通知
设置通知震动
// 创建NotificationManager
NotificationManager manager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
String channelID = "my_channel_ID";
String channelNAME = "my_channel_NAME";
int level = NotificationManager.IMPORTANCE_HIGH;
// 8.0以上必须先创建通道
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
NotificationChannel channel = new NotificationChannel(channelID, channelNAME, level);
// 设置手机震动,以及震动频率
channel.enableVibration(true);
channel.setVibrationPattern(new long[]{0, 2000000000, 0, 2000000000, 0});
manager.createNotificationChannel(channel);
}
实现通知跳转activity
// 1. 添加跳转意图,点击通知跳转到指定页面
Intent intent = new Intent(NotificationActivity.this, AnotherActivity.class);
PendingIntent pendingIntent = PendingIntent.getActivity(NotificationActivity.this, 0, intent, PendingIntent.FLAG_IMMUTABLE);
NotificationCompat.Builder builder =
new NotificationCompat.Builder(NotificationActivity.this, channelID)
.setSmallIcon(R.drawable.lock) //添加小图标,该图标通知必须透明
.setContentTitle("Notification") //添加通知标题
.setContentText("hjh") //添加通知内容
.setWhen(System.currentTimeMillis()) //添加通知事件
.setLargeIcon(BitmapFactory.decodeResource(getResources(), R.drawable.zhibao)) //添加大图标
.setContentIntent(pendingIntent)//2. 添加意图
.setAutoCancel(true)//通知经过点击后自动取消
实现通知操作按钮
大概就是通过添加一个按钮发送广播,然后被广播接收器接收到然后进行各种操作
- 创建一个接收器,并通过动态注册接收器,这边就不演示具体代码
- 创建一个intent,并且设置action属性,这边的action与注册广播接收器的action要对应
// 添加跳转意图,点击通知跳转到指定页面
Intent Actionintent = new Intent();
Actionintent.setAction(ACTION_SNOOZE);
Actionintent.putExtra("a", "1");
PendingIntent snoozePendingIntent =
PendingIntent.getBroadcast(NotificationActivity.this, 0, Actionintent, PendingIntent.FLAG_IMMUTABLE);
NotificationCompat.Builder builder =
new NotificationCompat.Builder(NotificationActivity.this, channelID)
.setSmallIcon(R.drawable.lock) //添加小图标,该图标通知必须透明
.setContentTitle("Notification") //添加通知标题
.setContentText("hjh") //添加通知内容
.setWhen(System.currentTimeMillis()) //添加通知事件
.setLargeIcon(BitmapFactory.decodeResource(getResources(), R.drawable.zhibao)) //添加大图标
.setContentIntent(pendingIntent)//添加意图
.setAutoCancel(true)//通知经过点击后自动取消
.addAction(R.drawable.abc, "按钮", Actionintent);
// .setStyle(new NotificationCompat.BigTextStyle().bigText("lllllllllllllll
播放音视频文件
播放音频文件
常用方法
使用例子
public class MainActivity extends AppCompatActivity {
ActivityMainBinding activityMainBinding;
// 创建音频播放器
private final MediaPlayer mediaPlayer = new MediaPlayer();
@Override
protected void onCreate(Bundle savedInstanceState) {
....
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 {
try {
initMediaPlayer();
} catch (IOException e) {
throw new RuntimeException(e);
}
}
activityMainBinding.play.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
if (!mediaPlayer.isPlaying()){
mediaPlayer.start();//开始播放
}
}
});
activityMainBinding.pause.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
if (mediaPlayer.isPlaying()){
mediaPlayer.pause();//暂停播放
}
}
});
activityMainBinding.stop.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
if (mediaPlayer.isPlaying()){
mediaPlayer.reset();//停止播放
try {
initMediaPlayer();
} catch (IOException e) {
throw new RuntimeException(e);
}
}
}
});
}
private void initMediaPlayer() throws IOException {
mediaPlayer.setDataSource(getResources().openRawResourceFd(R.raw.a));
mediaPlayer.prepare();
}
@Override
public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
super.onRequestPermissionsResult(requestCode, permissions, grantResults);
switch (requestCode) {
case 1:
if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
try {
initMediaPlayer();
} catch (IOException e) {
throw new RuntimeException(e);
}
} else {
Toast.makeText(this, "拒绝权限将无法使用程序", Toast.LENGTH_SHORT).show();
finish();
}
}
}
//释放资源
@Override
protected void onDestroy() {
if (mediaPlayer!=null){
mediaPlayer.stop();
mediaPlayer.release();
}
super.onDestroy();
}
}
<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout 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:id="@+id/main"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".MainActivity">
<Button
android:id="@+id/stop"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Stop"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintHorizontal_bias="0.5"
app:layout_constraintStart_toEndOf="@+id/pause"
app:layout_constraintTop_toTopOf="parent" />
<Button
android:id="@+id/play"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Play"
app:layout_constraintEnd_toStartOf="@+id/pause"
app:layout_constraintHorizontal_bias="0.5"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent" />
<Button
android:id="@+id/pause"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Pause"
app:layout_constraintEnd_toStartOf="@+id/play"
app:layout_constraintHorizontal_bias="0.5"
app:layout_constraintStart_toEndOf="@+id/stop"
app:layout_constraintTop_toTopOf="parent" />
</androidx.constraintlayout.widget.ConstraintLayout>
播放视频
常用方法
使用例子
因为使用的是程序自带的视频文件就不需要访问外部资源,所以不需要赋予权限.
<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout 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:id="@+id/main"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".VideoTestActivity">
<Button
android:id="@+id/playVideo"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="Play"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent" />
<Button
android:id="@+id/pauseVideo"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="Pause"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toBottomOf="@+id/playVideo" />
<Button
android:id="@+id/replayVideo"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="Replay"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toBottomOf="@+id/pauseVideo" />
<VideoView
app:layout_constraintTop_toBottomOf="@+id/replayVideo"
android:id="@+id/video_view"
android:layout_width="match_parent"
android:layout_height="0dp"
app:layout_constraintHeight_percent="0.5"
/>
</androidx.constraintlayout.widget.ConstraintLayout>
public class VideoTestActivity extends AppCompatActivity {
ActivityVideoTestBinding activityVideoTestBinding;
@Override
protected void onCreate(Bundle savedInstanceState) {
....
initVidwoPath();
activityVideoTestBinding.playVideo.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
if (!activityVideoTestBinding.videoView.isPlaying()){
activityVideoTestBinding.videoView.start();
}}
});
activityVideoTestBinding.pauseVideo.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
if (activityVideoTestBinding.videoView.isPlaying()){
activityVideoTestBinding.videoView.pause();
}
}
});
activityVideoTestBinding.replayVideo.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
if (activityVideoTestBinding.videoView.isPlaying()){
activityVideoTestBinding.videoView.resume();
}
}
});
}
//准备播放
private void initVidwoPath(){
int videoResId = R.raw.b;
// 构建视频文件的 URI
Uri videoUri = Uri.parse("android.resource://" + getPackageName() + "/" + videoResId);
// 将视频 URI 设置给 VideoView
activityVideoTestBinding.videoView.setVideoURI(videoUri);
}
}