1、自定义xml 如下:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="horizontal"
>
<ImageView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center"
android:src="@mipmap/ic_launcher" />
<TextView
android:id="@+id/tvTitle"
style="@style/TextAppearance.Compat.Notification.Title"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_gravity="center"
android:layout_weight="1"
android:ellipsize="end"
android:maxLength="15"
android:paddingLeft="5dp"
android:paddingRight="5dp"
android:singleLine="true"
android:text="点击关闭音频" />
<ImageView
android:id="@+id/ivStop"
android:layout_width="wrap_content"
android:layout_height="match_parent"
android:src="@drawable/ic_baseline_stop_circle_24" />
</LinearLayout>
注意:style="@style/TextAppearance.Compat.Notification.Title" 这是google官方的建议、一般加到我们Textview中。
2、加入权限
<uses-permission android:name="android.permission.FOREGROUND_SERVICE" />
部分设备需要加入 悬浮窗权限
<uses-permission android:name="android.permission.SYSTEM_ALERT_WINDOW" />
3、详细代码
public void createMusicNotification(Context context) {
NotificationManager notificationManager = (NotificationManager) context.getSystemService(Context.NOTIFICATION_SERVICE);
//android 8.0的判断、需要加入NotificationChannel
if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.O) {
NotificationChannel channel = new NotificationChannel("qiqile", "齐齐乐渠道",
NotificationManager.IMPORTANCE_DEFAULT);
notificationManager.createNotificationChannel(channel);
}
NotificationCompat.Builder builder = new NotificationCompat.Builder(context, "qiqile");
//自定义布局必须加上、否则布局会有显示问题、可以自己try try
builder.setSmallIcon(R.mipmap.ic_launcher);
builder.setOngoing(true);//代表是常驻的,主要是配合服务
RemoteViews remoteViews = new RemoteViews(context.getPackageName(), R.layout.notify_custom);
//自定义点击事件、会在Service. onStartCommand中回调
Intent stopIntent = new Intent(context, MediaService.class);
stopIntent.setAction(STOP_PLAY_SERVICE);
PendingIntent startOrPauseP = PendingIntent.getService(context, MediaService.RELEASE, stopIntent, 0);
remoteViews.setOnClickPendingIntent(R.id.ivStop, startOrPauseP);
builder.setContent(remoteViews);
Notification notification = builder.build();
//0x11 为通知id 自定义可
startForeground(0x11, notification);
}