RN APP 打开通知权限
在React Native中,开启通知权限需要使用原生代码。以下是针对iOS和Android的示例代码。
iOS
在AppDelegate.m
中添加以下代码:
#import <UserNotifications/UserNotifications.h>
- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions
{
if (@available(iOS 10.0, *)) {
[UNUserNotificationCenter requestAuthorizationWithOptions:(UNAuthorizationOptionBadge | UNAuthorizationOptionSound | UNAuthorizationOptionAlert) completionHandler:^(BOOL granted, NSError * _Nullable error) {
}];
} else {
// Fallback on earlier versions
}
return YES;
}
Android
在MainActivity.java
中添加以下代码:
import android.content.Intent;
import android.os.Bundle;
import androidx.core.app.NotificationManagerCompat;
import android.widget.Toast;
import com.facebook.react.ReactActivity;
import com.facebook.react.ReactInstanceManager;
public class MainActivity extends ReactActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
}
@Override
protected String getMainComponentName() {
return "YourAppName";
}
@Override
protected ReactInstanceManager createReactInstanceManager() {
ReactInstanceManager instanceManager = super.createReactInstanceManager();
instanceManager.addReactInstanceEventListener(instanceManager);
return instanceManager;
}
// Check and request permissions
public void requestNotificationPermissions() {
if (NotificationManagerCompat.from(this).areNotificationsEnabled()) {
// Notifications are enabled for this app
} else {
// Notifications are disabled for this app
// You can either navigate the user to the settings page, or show an in-app dialog explaining why you need notifications enabled
Intent intent = new Intent();
intent.setAction("android.settings.APP_NOTIFICATION_SETTINGS");
intent.putExtra("app_package", getPackageName());
intent.
评论已关闭