zoukankan      html  css  js  c++  java
  • 【Android异常】关于Notification启动时,startForeground报错

    遇到两个报错:

    第一个权限问题报错,好解决

    startForeground requires android.permission.FOREGROUND_SERVICE

    Manifest给下权限就行

    <manifest ...>
         ...
         <uses-permission android:name="android.permission.FOREGROUND_SERVICE" />
         ...
         <application ...>
         ...
    </manifest>

    第二个问题,Android 8.0以上需要Notification需要设置个Channel

    android.app.RemoteServiceException: Bad notification for startForeground


    解决方法如下:原博客

    //以下为新增---------------------------------------------
     String CHANNEL_ONE_ID = "com.primedu.cn";
     String CHANNEL_ONE_NAME = "Channel One";
            NotificationChannel notificationChannel = null;
            if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.O) {
                notificationChannel = new NotificationChannel(CHANNEL_ONE_ID,
                        CHANNEL_ONE_NAME, NotificationManager.IMPORTANCE_HIGH);
                notificationChannel.enableLights(true);
                notificationChannel.setLightColor(Color.RED);
                notificationChannel.setShowBadge(true);
                notificationChannel.setLockscreenVisibility(Notification.VISIBILITY_PUBLIC);
                NotificationManager manager = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
                manager.createNotificationChannel(notificationChannel);
            }
    //--------------------------------------------------------以上为新增
    
     PendingIntent pendingIntent = PendingIntent.getActivity(this, 0, intent, 0);
            notification = new Notification.Builder(this).setChannelId(CHANNEL_ONE_ID)
                    .setTicker("Nature")
                    .setSmallIcon(R.mipmap.ic_launcher)
                    .setContentTitle("xxxx")
                    .setContentText(musicList.size() > 0 && musicList != null ? musicList.get(currentMusic).radio_en_desc:"xxxxx")
                    .setContentIntent(pendingIntent)
                    .getNotification();
            notification.flags |= Notification.FLAG_NO_CLEAR;
            startForeground(1, notification);

    我标记了一下哪些地方是新增的
    同新增了一句.setChannelId(CHANNEL_ONE_ID)
    就ok了,在运行就没问题了,通知正常开启

  • 相关阅读:
    C# Net Core 使用 ClientWebSocket 实现 WebSocket 客户端
    C# Net 使用 RSA 加密解密 OpenSSL 生成的密码
    VS 代码提示默认不选中 解决办法
    C# While 超时设置
    C# 比较日期格式中的年月大小
    C#实现QQ邮箱IMAP之邮件处理
    Windwos服务之定时发送邮件(一)
    js基于“合成大西瓜的”碰撞模型(一)
    Windows下,通过运行直接打开软件
    C#爬取国家统计局五级地址
  • 原文地址:https://www.cnblogs.com/zFrankie/p/14406546.html
Copyright © 2011-2022 走看看