开发中有时需要实现各种样式的通知栏通知功能,比如
1、浮动通知
/**
* 浮动通知 在[5.0,8.0)的系统中浮动通知的产生条件
* 是NotificationCompat.Builder中设置setPriority()的参数
* 必须在NotificationCompat.PRIORITY_HIGH及以上并且有铃声或者震动才能有效果
* 但在[8.0,8.0+)的时候因为NotificationChannel中的设置高于一切 所以
* NotificationChannel中的importance必须要在NotificationManager.IMPORTANCE_HIGH及以上(!注意 此时会有默认的铃声和震动的效果哦~)
* 5.0以下的系统就不支持啦
*
* @param noticationId
* @param pendingIntent
* @param largeIcon
* @param smallIcon
* @param ticker
* @param subText
* @param contentTitle
* @param contentText
* @param sound
* @param vibrate
* @param light
*/
public void notifyHeadUp(int noticationId, PendingIntent pendingIntent, @DrawableRes int largeIcon, @DrawableRes int smallIcon, String ticker, String subText, String contentTitle, String contentText, boolean sound, boolean vibrate, boolean light) {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
if (notificationChannel.getImportance() < NotificationManager.IMPORTANCE_HIGH) {
notificationChannel.setImportance(NotificationManager.IMPORTANCE_HIGH);
notificationManager.createNotificationChannel(notificationChannel);
}
}
// else if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
//
//
// }
builderNotification(pendingIntent, largeIcon, smallIcon, ticker, subText, contentTitle, contentText, NotificationCompat.PRIORITY_HIGH, sound, vibrate, light);
notifyNotification(noticationId);
}
2、带进度条通知
/**
* 在5.0的系统以下没有进度条显示 8.0及以上显示进度条是没有铃声和震动的效果的
*
* @param noticationId
* @param pendingIntent
* @param largeIcon
* @param smallIcon
* @param ticker
* @param subText
* @param contentTitle
* @param contentText
* @param maxProgress
* @param curProgress
*/
public void notifyProgress(int noticationId, PendingIntent pendingIntent, @DrawableRes int largeIcon, @DrawableRes int smallIcon, String ticker, String subText, String contentTitle, String contentText, int maxProgress, int curProgress) {
builderNotification(pendingIntent, largeIcon, smallIcon, ticker, subText, contentTitle, contentText, NotificationCompat.PRIORITY_HIGH, false, true, false);
if (curProgress >= maxProgress) {
builder.setProgress(0, 0, false);
} else {
builder.setProgress(maxProgress, curProgress, false);
}
notifyNotification(noticationId);
}
3、消息类通知
/**
* 发送一个消息类的通知7.0以上有效 7.0以下效果不友好
*
* @param noticationId
* @param pendingIntent
* @param largeIcon
* @param smallIcon
* @param ticker
* @param subText
* @param contentTitle
* @param contentText
* @param priority
* @param sound
* @param vibrate
* @param light
*/
public void notifyMessageType(int noticationId, PendingIntent pendingIntent, @DrawableRes int largeIcon, @DrawableRes int smallIcon, String ticker, String subText, String contentTitle, String contentText, int priority, boolean sound, boolean vibrate, boolean light) {
builderNotification(pendingIntent, largeIcon, smallIcon, ticker, subText, contentTitle, contentText, priority, sound, vibrate, light);
builder.setStyle(new NotificationCompat.MessagingStyle(contentTitle).setConversationTitle("xx")
.addMessage(new NotificationCompat.MessagingStyle.Message(contentText, System.currentTimeMillis(), "wo")));
notifyNotification(noticationId);
}
4、带按钮通知
/**
* 添加两个左右的按钮 发送通知
* <p>
* 按钮最多可以加到三个
*
* @param noticationId
* @param pendingIntent
* @param leftPendingIntent
* @param leftIcon
* @param leftBtnText
* @param rightPendingIntent
* @param rightIcon
* @param rightBtnText
* @param largeIcon
* @param smallIcon
* @param ticker
* @param subText
* @param contentTitle
* @param contentText
* @param priority
* @param sound
* @param vibrate
* @param light
*/
public void notifyButton(int noticationId, PendingIntent pendingIntent, PendingIntent leftPendingIntent, int leftIcon, CharSequence leftBtnText, PendingIntent rightPendingIntent, int rightIcon, CharSequence rightBtnText, @DrawableRes int largeIcon, @DrawableRes int smallIcon, String ticker, String subText, String contentTitle, String contentText, int priority, boolean sound, boolean vibrate, boolean light) {
builderNotification(pendingIntent, largeIcon, smallIcon, ticker, subText, contentTitle, contentText, priority, sound, vibrate, light);
builder.addAction(leftIcon, leftBtnText, leftPendingIntent);
builder.addAction(rightIcon, rightBtnText, rightPendingIntent);
notifyNotification(noticationId);
}
5、带大图通知
/**
* 大图的通知类型
*
* @param noticationId
* @param pendingIntent
* @param largeIcon
* @param bigPicFilePath 大图的绝对路径地址
* @param smallIcon
* @param ticker
* @param subText
* @param contentTitle
* @param contentText
* @param priority
* @param sound
* @param vibrate
* @param light
*/
public void notifyBigPic(Context context, int noticationId, PendingIntent pendingIntent, @DrawableRes int largeIcon, String bigPicFilePath, @DrawableRes int smallIcon, String ticker, String subText, String contentTitle, String contentText, int priority, boolean sound, boolean vibrate, boolean light) {
builderNotification(pendingIntent, largeIcon, smallIcon, ticker, subText, contentTitle, contentText, priority, sound, vibrate, light);
NotificationCompat.BigPictureStyle bigPictureStyle = new NotificationCompat.BigPictureStyle();
BitmapFactory.Options options = new BitmapFactory.Options();
options.inSampleSize = 2;
options.inScaled = true;
// Calculate inSampleSize
// Decode bitmap with inSampleSize set
options.inJustDecodeBounds = false;
//避免出现内存溢出的情况,进行相应的属性设置。
options.inPreferredConfig = Bitmap.Config.RGB_565;
options.inDither = true;
// Bitmap bitmap = BitmapFactory.decodeFile(bigPicFilePath, options);
Bitmap bitmap = BitmapFactory.decodeResource(context.getResources(), R.mipmap.bg_man);
bigPictureStyle.bigLargeIcon(bitmap);
bigPictureStyle.bigPicture(bitmap);
// bigPictureStyle.setBigContentTitle("这是大图");
// bigPictureStyle.setSummaryText("这是大图的Summary");
builder.setStyle(bigPictureStyle);
notifyNotification(noticationId);
}
6、文字类型折叠通知
/**
* 发送长文字类型的通知 5.0以下长文字会全部显示出来 5.0以上会折叠
*
* @param noticationId
* @param pendingIntent
* @param largeIcon
* @param smallIcon
* @param ticker
* @param subText
* @param contentTitle
* @param contentText
* @param priority
* @param sound
* @param vibrate
* @param light
*/
public void notifyBigText(int noticationId, PendingIntent pendingIntent, @DrawableRes int largeIcon, @DrawableRes int smallIcon, String ticker, String subText, String contentTitle, String contentText, int priority, boolean sound, boolean vibrate, boolean light) {
builderNotification(pendingIntent, largeIcon, smallIcon, ticker, subText, contentTitle, contentText, priority, sound, vibrate, light);
// if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN) {
NotificationCompat.BigTextStyle bigTextStyle = new NotificationCompat.BigTextStyle();
bigTextStyle.bigText(contentText);
builder.setStyle(bigTextStyle);
// }
notifyNotification(noticationId);
}
7、普通通知
8、自定义view的通知
因为可以自定义,所以该工具类基本满足了所有的通知栏样式需求。
使用也非常简单,只需要调用不同方法即可。
示例布局代码
<?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:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".MainActivity">
<Button
android:id="@+id/btn1"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginTop="10dp"
android:layout_marginLeft="50dp"
android:layout_marginRight="50dp"
android:text="普通通知"
app:layout_constraintTop_toTopOf="parent"
app:layout_constraintLeft_toLeftOf="parent"/>
<Button
android:id="@+id/btn2"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginTop="10dp"
android:layout_marginLeft="50dp"
android:layout_marginRight="50dp"
android:text="带大图通知"
app:layout_constraintLeft_toLeftOf="parent"
app:layout_constraintTop_toBottomOf="@id/btn1"/>
<Button
android:id="@+id/btn3"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginTop="10dp"
android:layout_marginLeft="50dp"
android:layout_marginRight="50dp"
android:text="文字类型折叠通知"
app:layout_constraintLeft_toLeftOf="parent"
app:layout_constraintTop_toBottomOf="@id/btn2"/>
<Button
android:id="@+id/btn4"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginTop="10dp"
android:layout_marginLeft="50dp"
android:layout_marginRight="50dp"
android:text="带进度条通知"
app:layout_constraintLeft_toLeftOf="parent"
app:layout_constraintTop_toBottomOf="@id/btn3"/>
<Button
android:id="@+id/btn5"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginTop="10dp"
android:layout_marginLeft="50dp"
android:layout_marginRight="50dp"
android:text="带按钮通知"
app:layout_constraintLeft_toLeftOf="parent"
app:layout_constraintTop_toBottomOf="@id/btn4"/>
<Button
android:id="@+id/btn6"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginTop="10dp"
android:layout_marginLeft="50dp"
android:layout_marginRight="50dp"
android:text="消息类通知"
app:layout_constraintLeft_toLeftOf="parent"
app:layout_constraintTop_toBottomOf="@id/btn5"/>
<Button
android:id="@+id/btn7"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginTop="10dp"
android:layout_marginLeft="50dp"
android:layout_marginRight="50dp"
android:text="浮动通知"
app:layout_constraintLeft_toLeftOf="parent"
app:layout_constraintTop_toBottomOf="@id/btn6"/>
<Button
android:id="@+id/btn8"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginTop="10dp"
android:layout_marginLeft="50dp"
android:layout_marginRight="50dp"
android:text="自定义view通知"
app:layout_constraintLeft_toLeftOf="parent"
app:layout_constraintTop_toBottomOf="@id/btn7"/>
</androidx.constraintlayout.widget.ConstraintLayout>
示例调用代码
package com.leqiku.myapplication;
import androidx.annotation.DrawableRes;
import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;
import androidx.core.app.ActivityCompat;
import androidx.core.app.NotificationCompat;
import android.Manifest;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.graphics.Color;
import android.os.Bundle;
import android.os.SystemClock;
import android.telecom.Call;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import java.util.ArrayList;
import java.util.List;
public class MainActivity extends AppCompatActivity {
private NotificationUtils notificationUtils, twoUtils;
private NotificationUtils.ChannelBuilder channelBuilder, twoChannelBuilder;
private boolean sound, light, vibrate;
String mTitle = "标题";
String mContent = "内容";
int mEntityId = 1000;
String mType = "类型";
private int requestCode = (int) SystemClock.uptimeMillis();
Intent intent = null;
private static final int PERMISSION_REQUEST = 1001;
String[] permissions = {Manifest.permission.WRITE_EXTERNAL_STORAGE,Manifest.permission.CAMERA,Manifest.permission.CALL_PHONE,Manifest.permission.READ_EXTERNAL_STORAGE};
List<String> permissionsList = new ArrayList<>();
/**
* 请求权限
*/
private void initPermissions() {
permissionsList.clear();
//判断哪些权限未授予
for(String permission : permissions){
if(ActivityCompat.checkSelfPermission(this,permission)!= PackageManager.PERMISSION_GRANTED){
permissionsList.add(permission);
}
}
//请求权限
if(!permissionsList.isEmpty()){
String[] permissions = permissionsList.toArray(new String[permissionsList.size()]);//将List转为数组
ActivityCompat.requestPermissions(MainActivity.this, permissions, PERMISSION_REQUEST);
}
}
/**
* 权限回调,
* @param requestCode
* @param permissions
* @param grantResults
*/
@Override
public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
super.onRequestPermissionsResult(requestCode, permissions, grantResults);
switch (requestCode){
case PERMISSION_REQUEST:
break;
default:
break;
}
}
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
//请求权限
initPermissions();
twoChannelBuilder = new NotificationUtils.ChannelBuilder("channelGroupId", "channelId", "channelName", NotificationManager.IMPORTANCE_HIGH)
.setChannelName("channelName").setByPassDnd(true).setLightColor(Color.GREEN)
.setShowBadge(false).setEnableLight(false).setEnableSound(false).setEnableVibrate(false)
.setVisibility(NotificationCompat.VISIBILITY_PUBLIC);
twoUtils = new NotificationUtils(this, twoChannelBuilder);
twoUtils.init("channelId", "channelName", "channelGroupId", "channelGroupName");
//根据type去跳转页面
intent = new Intent(MainActivity.this, DetailActivity.class);
// intent.setFlags(Intent.FLAG_ACTIVITY_RESET_TASK_IF_NEEDED);
PendingIntent pIntent = PendingIntent.getActivity(MainActivity.this,
requestCode, intent, PendingIntent.FLAG_UPDATE_CURRENT);
int largeIcon = R.mipmap.ic_launcher;
int smallIcon = R.mipmap.ic_launcher;
String ticker = mType;
String title = mTitle;
String content = mContent;
// 普通通知
Button btn1 = findViewById(R.id.btn1);
btn1.setOnClickListener(v -> {
//实例化工具类,并且调用接口
twoUtils.notifyMessage(mEntityId, pIntent, largeIcon, smallIcon, ticker, "普通通知", title, content, NotificationCompat.PRIORITY_HIGH, sound, vibrate, light);
});
// 带大图通知
Button btn2 = findViewById(R.id.btn2);
btn2.setOnClickListener(v -> {
//实例化工具类,并且调用接口
twoUtils.notifyBigPic(this,mEntityId, pIntent, largeIcon, "D:\\LeqiCode\\android\\MyApplication\\app\\src\\main\\assets\\bg_man.png",smallIcon, ticker, "带大图通知", title, content, NotificationCompat.PRIORITY_HIGH, sound, vibrate, light);
});
// 文字类型折叠通知
Button btn3 = findViewById(R.id.btn3);
btn3.setOnClickListener(v -> {
//实例化工具类,并且调用接口
twoUtils.notifyBigText(mEntityId, pIntent, largeIcon, smallIcon, ticker, "文字类型折叠通知", "标题", "很长很长的内容很长很长的内容很长很长的内容很长很长的内容很长很长的内容很长很长的内容很长很长的内容很长很长的内容很长很长的内容很长很长的内容很长很长的内容很长很长的内容", NotificationCompat.PRIORITY_HIGH, sound, vibrate, light);
});
// 带进度条通知
Button btn4 = findViewById(R.id.btn4);
btn4.setOnClickListener(v -> {
//实例化工具类,并且调用接口
twoUtils.notifyProgress(mEntityId, pIntent, largeIcon, smallIcon, ticker, "带进度条通知", title, content, 100,40);
});
// 带按钮通知
Button btn5 = findViewById(R.id.btn5);
btn5.setOnClickListener(v -> {
//实例化工具类,并且调用接口
twoUtils.notifyButton(mEntityId, pIntent, pIntent,largeIcon, "按钮1",pIntent,largeIcon,"按钮2",largeIcon,smallIcon,ticker,"带按钮通知",title,content, NotificationCompat.PRIORITY_HIGH, sound, vibrate, light);
});
// 消息类通知
Button btn6 = findViewById(R.id.btn6);
btn6.setOnClickListener(v -> {
//实例化工具类,并且调用接口
twoUtils.notifyMessageType(mEntityId, pIntent, largeIcon, smallIcon, ticker, "消息类通知", title, content, NotificationCompat.PRIORITY_HIGH, sound, vibrate, light);
});
// 浮动通知
Button btn7 = findViewById(R.id.btn7);
btn7.setOnClickListener(v -> {
//实例化工具类,并且调用接口
twoUtils.notifyHeadUp(mEntityId, pIntent, largeIcon, smallIcon, ticker, "浮动通知", title, content,sound, vibrate, light);
});
// 自定义通知
Button btn8 = findViewById(R.id.btn8);
btn8.setOnClickListener(v -> {
//实例化工具类,并且调用接口
twoUtils.notifyBigPic(this,mEntityId, pIntent, largeIcon, "D:\\LeqiCode\\android\\MyApplication\\app\\src\\main\\assets\\bg_man.png",smallIcon, ticker, "自定义通知", title, content, NotificationCompat.PRIORITY_HIGH, sound, vibrate, light);
});
}
}