1. 程式人生 > >React Native之通知欄訊息提示(android)

React Native之通知欄訊息提示(android)

React Native之通知欄訊息提示(android)

 

一,需求分析與概述

1.1,推送作為手機應用的基本功能,是手機應用的重要部分,如果自己實現一套推送系統費時費力,所以大部分的應用都會選擇使用第三方的推送服務,如極光推送。

1.2,jpush-react-native 是極光推送官方開發的 React Native 版本外掛,可以快速整合推送功能。現在最新版本的 JPush SDK 分離了 JPush 及 JCore,讓開發者可以分開整合 JMessage 及 JPush(以前 JMessage 包含了 JPush)。

API:

 1 #初始化JPush 必須先初始化才能執行其他操作(only android)
2 initPush 3 4 getInfo 5 6 #執行該方法後,無法接收到通知 7 stopPush 8 9 #stopPush後,執行該方法,可接收通知(only android) 10 resumePush 11 12 #引數是func,func的引數是registrationId 13 getRegistrationID 14 15 #設定標籤 16 setTags 17 18 #新增標籤 19 addTags 20 21 #刪除標籤 22 deleteTags 23 24 #檢查標籤的狀態 25 checkTagBindState 26 27 #清除所有標籤
28 cleanTags 29 30 #設定別名 31 setAlias 32 33 #刪除別名 34 deleteAlias 35 36 #獲取別名 37 getAlias 38 39 #通知欄樣式:Basic 40 setStyleBasic 41 42 #通知欄樣式:Custom 43 setStyleCustom

1.3,推送通知可以及時地提醒使用者.

二,極光推送註冊與整合

2.1,註冊

首先,登入極光官網系統,如果還沒有賬號可以註冊一個,登入成功我們就可以建立和管理我們的應用了。  

2.2,整合(android)

第一步:安裝

開啟終端,進入專案根目錄資料夾下,執行以下命令:

1  npm install jpush-react-native --save
2  jpush-react-native 1.4.2 版本以後需要同時安裝 jcore-react-native
3  npm install jcore-react-native --save 

第二步:配置

自動關聯配置

1 # 針對性的link,避免之前手動配置的其它外掛重複配置造成報錯
2  react-native link jpush-react-native
3  react-native link jcore-react-native

執行完 link 專案後可能會出現報錯,這沒關係,需要手動配置一下 build.gradle 檔案。如自動配置沒有成功或沒有完善,可根據手動配置檢查

手動配置

(1),檢查 android 專案下的 settings.gradle 配置有沒有包含以下內容(project/android/settings.gradle):

1 include ':jcore-react-native'
2 project(':jcore-react-native').projectDir = new File(rootProject.projectDir, '../node_modules/jcore-react-native/android')
3 
4 include ':jpush-react-native'
5 project(':jpush-react-native').projectDir = new File(rootProject.projectDir, '../node_modules/jpush-react-native/android')

 (2),project/android/app/build.gradle:

 1 android {
 2     ...
 3     defaultConfig {
 4         applicationId "yourApplicationId" // 此處改成你在極光官網上申請應用時填寫的包名
 5         ...
 6         manifestPlaceholders = [
 7                 JPUSH_APPKEY: "yourAppKey", //在此替換你極光官網上申請的 APPKey
 8                 APP_CHANNEL: "developer-default"    //應用渠道號, 預設即可
 9         ]
10     }
11 }
12 ...
13 dependencies {
14     compile project(':jpush-react-native')  // 新增 jpush 依賴
15     compile project(':jcore-react-native')  // 新增 jcore 依賴
16     compile fileTree(dir: "libs", include: ["*.jar"])
17     compile "com.android.support:appcompat-v7:23.0.1"
18     compile "com.facebook.react:react-native:+"  // From node_modules
19 }

(3),檢查一下 app 下的 AndroidManifest 配置,有沒有增加 <meta-data> 部分。 project/android/app/src/main/AndroidManifest.xml:

1 <application
2     ...
3     <!-- Required . Enable it you can get statistics data with channel -->
4     <meta-data android:name="JPUSH_CHANNEL" android:value="${APP_CHANNEL}"/>
5     <meta-data android:name="JPUSH_APPKEY" android:value="${JPUSH_APPKEY}"/>
6  
7 </application>

(4),開啟 project/android/app/src/main/java/com/專案名/下的 MainApplication.java 檔案,然後加入 JPushPackage

 1 ...
 2 
 3 import com.rt2zz.reactnativecontacts.ReactNativeContacts;
 4 import cn.jpush.reactnativejpush.JPushPackage; 
 5 
 6 ...
 7 
 8 public class MainApplication extends Application implements ReactApplication {
 9 // 設定為 true 將不會彈出 toast
10     private boolean SHUTDOWN_TOAST = false;
11     // 設定為 true 將不會列印 log
12     private boolean SHUTDOWN_LOG = false;
13   private final ReactNativeHost mReactNativeHost = new ReactNativeHost(this) {
14     @Override
15     public boolean getUseDeveloperSupport() {
16       return BuildConfig.DEBUG;
17     }
18 
19     @Override
20     protected List<ReactPackage> getPackages() {
21       return Arrays.<ReactPackage>asList(
22             new MainReactPackage(),
23                new JPushPackage(SHUTDOWN_TOAST, SHUTDOWN_LOG) 
24       );
25     }
26 
27    ...
28 
29 }

(5),開啟 project/android/app/src/main/java/com/專案名/下的MainActivity.java 檔案,然後加入 如下程式碼:

 1 ...
 2 
 3 
 4 import android.os.Bundle;
 5 import com.facebook.react.ReactActivity;
 6 import cn.jpush.android.api.JPushInterface;
 7 
 8 public class MainActivity extends ReactActivity {
 9 
10 ...
11 
12     @Override
13     protected void onCreate(Bundle savedInstanceState) {
14         super.onCreate(savedInstanceState);
15         JPushInterface.init(this);
16     }
17  
18     @Override
19     protected void onPause() {
20         super.onPause();
21         JPushInterface.onPause(this);
22     }
23  
24     @Override
25     protected void onResume() {
26         super.onResume();
27         JPushInterface.onResume(this);
28     }
29  
30     @Override
31     protected void onDestroy() {
32         super.onDestroy();
33     }
34 }

 (6),開啟  project/android/app/src/main/下的AndroidManifest.xml 檔案,然後新增訪問通知的許可權:

1 <!--新增通知許可權,${ApplicationID}替換成你的applicationID!-->
2     <premission 
3         android:name="${ApplicationID}.permission.JPUSH_MESSAGE"
4         android:protectionLevel="signature"/>

 這樣就基本完成了所有的配置。接下來就可以在 JS 中呼叫外掛提供的 API 了。

三,使用與實現

3.1,使用

(1),在js中 1 import React, { PureComponent } from 'react';

 2 import {
 3   Linking,
 4   Alert
 5 } from 'react-native';
 6 import JPushModule from 'jpush-react-native'
 7 
 8 ...
 9 
10 
11 componentDidMount() { 
12 /****************************通知 start **************************************************/
13     if (Platform.OS === 'android') {
14       JPushModule.initPush()
15    // 新版本必需寫回調函式
16       JPushModule.notifyJSDidLoad(resultCode => {
17         if (resultCode === 0) {
18         }
19       })
20     } else {
21       JPushModule.setupPush()
22     }
23     // 接收自定義訊息
24     this.receiveCustomMsgListener = map => {
25       this.setState({
26         pushMsg: map.content
27       })
28       console.log('extras: ' + map.extras)
29     }
30 
31         // 接收自定義訊息JPushModule.addReceiveCustomMsgListener(this.receiveCustomMsgListener)
32     this.receiveNotificationListener = map => {
33       console.log('alertContent: ' + map.alertContent)
34       console.log('extras: ' + map.extras)
35     }
36     // 接收推送通知
37 JPushModule.addReceiveNotificationListener(this.receiveNotificationListener)
38  // 開啟通知
39     this.openNotificationListener = map => {
40       // console.log('Opening notification!')
41     //  console.log('map.extra: ' + map.extras)
42      let webUrl= JSON.parse(map.extras).webUrl
43       let url = webUrl.replace(new RegExp("\/", 'g'), "/")
44       Linking.canOpenURL(url).then(supported => {
45         if (!supported) {
46           Alert.alert('您的系統不支援開啟瀏覽器!')
47         } else {
48           return Linking.openURL(url);
49         }
50       }).catch(err => { });
51 
52     }
53     JPushModule.addReceiveOpenNotificationListener(this.openNotificationListener)
54 
55     // this.getRegistrationIdListener = registrationId => {
56     //   console.log('Device register succeed, registrationId ' + registrationId)
57     // }
58     // JPushModule.addGetRegistrationIdListener(this.getRegistrationIdListener)
59     /****************************通知 end **************************************************/
60 
61 
62   }
63   componentWillUnmount() {
64     JPushModule.removeReceiveCustomMsgListener(this.receiveCustomMsgListener)
65     JPushModule.removeReceiveNotificationListener(this.receiveNotificationListener)
66     JPushModule.removeReceiveOpenNotificationListener(this.openNotificationListener)
67     // JPushModule.removeGetRegistrationIdListener(this.getRegistrationIdListener)
68     // console.log('Will clear all notifications')
69     // JPushModule.clearAllNotifications()
70   }
71   
72 }
73 
74 ...

(2),在極光官網上推送

 

3.2,實現的效果

 

 

問題:

1,真機沒接收到通知

解決:開啟node_modules/jpush_react-native/android/src/AndroidManifest.xml,將所有的${applicationId}替換成你的包名。或將project/android/src/AndroidManifest.xml,的${applicationId}替換成你的包名。

...

<application
        android:name=".MainApplication"
        android:allowBackup="true"
        android:icon="@drawable/ic_launcher"
        android:label="@string/app_name"
        android:theme="@style/AppTheme">
        <activity
            android:name=".MainActivity"
            android:configChanges="keyboard|keyboardHidden|orientation|screenSize"
            android:label="@string/app_name">
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />
                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>

   ...

        <!-- Required . Enable it you can get statistics data with channel -->
        <meta-data android:name="JPUSH_CHANNEL" android:value="${APP_CHANNEL}"/>
        <meta-data android:name="JPUSH_APPKEY" android:value="${JPUSH_APPKEY}"/>

    </application>

.MainApplication和.MainActivity前新增包名