开源:ReactNative设置应用角标库

2,570 阅读1分钟

背景

项目开发需要RN项目可以设置应用角标,搜索相关资料后发现目前没有第三方库直接支持,所以想到自己通过桥接双端原生进行实现,本着不重复造轮子的思想,将库进行开源。

过程中遇到的问题

Android问题

首先已有前辈做了原生对应的库,但是小米、荣耀等机型需要单独适配,采用的方案是添加原生依赖库,并单独对小米,荣耀机型进行适配工作。

其次,Android 13(API 级别 33)及更高版本上的通知权限改成了运行时获取,应用的通知默认处于关闭状态,需要单独添加权限,并在应用启动页进行用户提示。

解决方案,在项目的MainActivity.java文件中添加如下代码,并在onCreate函数中进行调用,

private void setupNotificationChannel() {
    NotificationManager mNotificationManager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
    Notification notification = null;
    if(Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
        NotificationChannel channel = new NotificationChannel("com.chengfenghuoyun.crm", "notification_channel",
                NotificationManager.IMPORTANCE_HIGH);
        mNotificationManager.createNotificationChannel(channel);
        notification = new Notification.Builder(getApplicationContext(), "com.chengfenghuoyun.crm")
                .setContentTitle("")
                .setContentText("")
                .setSmallIcon(R.mipmap.ic_launcher)
                .build();
    } else {
        notification = new Notification.Builder(getApplicationContext())
                .setContentTitle("")
                .setContentText("")
                .setSmallIcon(R.mipmap.ic_launcher)
                .build();
    }
    mNotificationManager.notify(1, notification);
}

ios问题

ios端没有机型适配问题,但是需要开启通知权限,需要在AppDelegate.m文件添加如下代码,

1. 导入UNUserNotificationCenter
#import <UserNotifications/UNUserNotificationCenter.h>
2. 在AppDelegate中引用
@interface AppDelegate () <RCTBridgeDelegate, UNUserNotificationCenterDelegate>
3. 申请通知权限
  UNUserNotificationCenter *center = [UNUserNotificationCenter currentNotificationCenter];
    center.delegate = self;
    [center requestAuthorizationWithOptions:(UNAuthorizationOptionSound | UNAuthorizationOptionAlert | UNAuthorizationOptionBadge) completionHandler:^(BOOL granted, NSError * _Nullable error) {
    }];

角标库导入及使用

添加依赖

yarn add react-native-wayne-badge

ios端
cd ios && pod install

使用

// 导入包
import RNWayneBadge from 'react-native-wayne-badge';

// 使用包
RNWayneBadge.setBadge(1);

项目库地址

https://github.com/wayne214/react-native-wayne-badge

欢迎👏🏻各位大佬star⭐️。

参考资料: 1.www.jianshu.com/p/2566fdebc… 2.blog.csdn.net/gongsunjinq… 3.github.com/leolin31014… 4.developer.android.com/guide/topic…