android 自定义常驻通知栏

1、自定义xml 如下:





    

    

    



注意:style="@style/TextAppearance.Compat.Notification.Title" 这是google官方的建议、一般加到我们Textview中。

2、加入权限 

部分设备需要加入 悬浮窗权限


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);
    }

 

你可能感兴趣的:(android)