需要帮助, 我想在锁定屏幕上像音乐播放器一样显示通知。我已经尝试过使用此代码来构建通知及其功能,但是在某些设备中,通知未在锁定屏幕中显示。
此代码在Motorola设备中有效,但在MI设备中无效。
这是代码:-
private fun showNotification() {
val mNotificationManager = this.getSystemService(Context.NOTIFICATION_SERVICE) as NotificationManager
val contentView = RemoteViews(packageName, R.layout.layout_notification)
contentView.setTextViewText(R.id.tvTitleKey, "Test")
contentView.setTextViewText(
R.id.tvTitleText,
"Hello Testing"
)
val mBuilder = NotificationCompat.Builder(this, "channel_01")
.setSmallIcon(R.drawable.ic_launcher_background)
.setOngoing(true)
.setAutoCancel(true)
.setShowWhen(true)
.setChannelId("channel_01")
.setVisibility(NotificationCompat.VISIBILITY_PUBLIC)
.setContent(contentView)
.setStyle(androidx.media.app.NotificationCompat.MediaStyle())
val notification = mBuilder.build()
notification.flags = notification.flags or Notification.FLAG_ONGOING_EVENT
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
val name = getString(R.string.app_name)
val mChannel = NotificationChannel("channel_01", name, NotificationManager.IMPORTANCE_HIGH)
mChannel.lockscreenVisibility = NotificationCompat.VISIBILITY_PUBLIC
mBuilder.setChannelId(CHANNEL_ID)
mNotificationManager.createNotificationChannel(mChannel)
mNotificationManager.notify(10, notification) //0 = ID of notification
} else {
mNotificationManager.notify(10, notification) //0 = ID of notification
}
}
这是布局文件layout_notification.xml
<RelativeLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:padding="8dp">
<ImageView
android:id="@+id/ivQR"
android:layout_width="70dp"
android:layout_height="70dp"
android:layout_centerVertical="true"
android:layout_margin="8dp"
android:src="@drawable/ic_launcher_background"
android:scaleType="fitXY"/>
<LinearLayout
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:orientation="vertical"
android:layout_centerVertical="true"
android:layout_toEndOf="@+id/ivQR">
<TextView
android:id="@+id/tvTitleKey"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginEnd="10dp"
android:textSize="18dp"/>
<TextView
android:id="@+id/tvTitleText"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginEnd="10dp"
android:textSize="18sp"/>
</LinearLayout>