用jpush-react-native插件快速集成推送功能(Android篇)

概述

jpush-react-native 是極光推送官方開發(fā)的 React Native 版本插件,可以快速集成推送功能?,F(xiàn)在最新版本的 JPush SDK 分離了 JPush 及 JCore,讓開發(fā)者可以分開集成 JMessage 及 JPush(以前 JMessage 包含了 JPush)。下面就來具體說一下如何快速集成以及使用 jpush-react-native 插件。

創(chuàng)新互聯(lián)建站主營平城網(wǎng)站建設(shè)的網(wǎng)絡(luò)公司,主營網(wǎng)站建設(shè)方案,重慶APP軟件開發(fā),平城h5微信平臺小程序開發(fā)搭建,平城網(wǎng)站營銷推廣歡迎平城等地區(qū)企業(yè)咨詢


安裝

打開終端,進入項目文件夾,執(zhí)行以下命令:

npm install jcore-react-native --save
npm install jpush-react-native --save

npm run configureJPush <yourAppKey> <yourModuleName>
//module name 指的是你 Android 項目中的模塊名字(對 iOS 沒有影響,不填寫的話默認值為 app,會影響到查找 AndroidManifest 問題,
//如果沒找到 AndroidManifest,則需要手動修改,參考下面的 AndroidManifest 配置相關(guān)說明)
//舉個例子:
npm run configureJPush d4ee2375846bc30fa51334f5 app

react-native link

執(zhí)行完 link 項目后可能會出現(xiàn)報錯,這沒關(guān)系,需要手動配置一下 build.gradle 文件。在 Android Studio 中打開你的項目,然后找到 app 或者你自己定義的需要集成 jpush-react-native 的模塊,打開此模塊下的 build.gradle 文件,做以下改動:

app/build.gradle

android {
    ...
    defaultConfig {
        applicationId "com.pushdemo" // 此處改成你在極光官網(wǎng)上申請應(yīng)用時填寫的包名
        ...
        manifestPlaceholders = [
                JPUSH_APPKEY: "d4ee2375846bc30fa51334f5",   //在此替換你的APPKey
                APP_CHANNEL: "developer-default"        //應(yīng)用渠道號
        ]
    }
}

檢查一下在 dependencies 中有沒有加入 jpush-react-native 以及 jcore-react-native 這兩個依賴,如果沒有,則需要加上:

dependencies {
    ...
    compile project(':jpush-react-native')
    compile project(':jcore-react-native')
    ...
}

接下來打開項目的 settings.gradle,看看有沒有包含 jpush-react-native 以及 jcore-react-native,如果沒有,則需要加上:

include ':app', ':jpush-react-native', ':jcore-react-native'
project(':jpush-react-native').projectDir = new File(rootProject.projectDir, '../node_modules/jpush-react-native/android')
project(':jcore-react-native').projectDir = new File(rootProject.projectDir, '../node_modules/jcore-react-native/android')

做完以上步驟,這時可以同步(sync)一下項目,然后應(yīng)該可以看到 jpush-react-native 以及 jcore-react-native 作為 Library 項目導(dǎo)進來了。

將react native項目導(dǎo)入android studio方法: File-->New-->Import Project-->選擇react native項目下的android

用 jpush-react-native 插件快速集成推送功能(Android 篇)

接下來打開模塊的 MainApplication.java 文件,加入 JPushPackage:

app/src.../MainApplication.java

    private boolean SHUTDOWN_TOAST = false;
    private boolean SHUTDOWN_LOG = false;

    private final ReactNativeHost mReactNativeHost = new ReactNativeHost(this) {

        @Override
        protected boolean getUseDeveloperSupport() {
            return BuildConfig.DEBUG;
        }


        @Override
        protected List<ReactPackage> getPackages() {
            return Arrays.<ReactPackage>asList(
                    new MainReactPackage(),
                    //加入 JPushPackage
                    new JPushPackage(SHUTDOWN_TOAST, SHUTDOWN_LOG)
            );
        }
    };

然后在 MainActivity 中加入一些初始化代碼即可:

app/src.../MainActivity.java

import android.os.Bundle;
import cn.jpush.android.api.JPushInterface;

public class MainActivity extends ReactActivity {    
    ...
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        JPushInterface.init(this);
    }

    @Override
    protected void onPause() {
        super.onPause();
        JPushInterface.onPause(this);
    }

    @Override
    protected void onResume() {
        super.onResume();
        JPushInterface.onResume(this);
    }
}

這樣就完成了所有的配置。接下來就可以在 JS 中調(diào)用插件提供的 API 了。

使用

收到推送

添加了此事件后,在收到推送時將會觸發(fā)此事件。

example/react-native-android/push_activity.js

...
import JPushModule from 'jpush-react-native';
...
export default class PushActivity extends React.Component {
    componentDidMount() {
        JPushModule.addReceiveNotificationListener((map) => {
            console.log("alertContent: " + map.alertContent);
            console.log("extras: " + map.extras);
            // var extra = JSON.parse(map.extras);
            // console.log(extra.key + ": " + extra.value);
        });
}
點擊推送

在用戶點擊通知后,將會觸發(fā)此事件。

...
componentDidMount() {
    JPushModule.addReceiveOpenNotificationListener((map) => {
            console.log("Opening notification!");
            console.log("map.extra: " + map.key);
        });
}
高級應(yīng)用

修改 JPushModule 中收到點擊通知的事件,可以自定義用戶點擊通知后跳轉(zhuǎn)的界面(現(xiàn)在默認是直接啟動應(yīng)用),只需要修改一點點原生的代碼:

jpush-react-native/src.../JPushModule.java

public static class JPushReceiver extends BroadcastReceiver {    
    public JPushReceiver() {        
        HeadlessJsTaskService.acquireWakeLockNow(mRAC);    
    }    
    
    @Override    
    public void onReceive(Context context, Intent data) {
    ...
    } else if (JPushInterface.ACTION_NOTIFICATION_OPENED.equals(data.getAction())) {    
        Logger.d(TAG, "用戶點擊打開了通知");
        Intent intent = new Intent();
        intent.setClassName(context.getPackageName(), context.getPackageName() + ".MainActivity");
        intent.putExtras(bundle);
        intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TOP);
        // 如果需要跳轉(zhuǎn)到指定的界面,那么需要同時啟動 MainActivity 及指定界面(SecondActivity):
        // If you need to open appointed Activity, you need to start MainActivity and
        // appointed Activity at the same time.
        Intent detailIntent = new Intent();
        detailIntent.setClassName(context.getPackageName(), context.getPackageName() + ".SecondActivity");
        detailIntent.putExtras(bundle);
        Intent[] intents = {intent, detailIntent};
        // 同時啟動 MainActivity 以及 SecondActivity
        context.startActivities(intents);
        // 或者回調(diào) JS 的某個方法
    }
}

...

 @ReactMethod
 public void finishActivity() {
     Activity activity = getCurrentActivity();
     if (activity != null) {
         activity.finish();
     }
 }

如果修改了此處跳轉(zhuǎn)的界面,需要在 Native 中聲明一個 Activity,如 demo 中的 SecondActivity,而 SecondActivity 的界面仍然用 JS 來渲染。只需要改動一下 SecondActivity,讓它繼承自 ReactActivity 即可:

example/android/app/src.../SecondActivity.java

public class SecondActivity extends ReactActivity {

    @Override
    protected String getMainComponentName() {
        return "SecondActivity";
    }

}

然后使用上面返回的字符串注冊一個 Component 即可:

example/react-native-android/second.js

'use strict';

import React from 'react';
import ReactNative from 'react-native';

const {
  AppRegistry,
  View,
  Text,
  TouchableHighlight,
  StyleSheet,
  NativeModules,
} = ReactNative;

var JPushModule = NativeModules.JPushModule;


export default class second extends React.Component {
  constructor(props) {
    super(props);
  }

  onBackPress = () => {
    let navigator = this.props.navigator;
    if (navigator != undefined) {
      this.props.navigator.pop();
    } else {
      console.log("finishing second activity");
      JPushModule.finishActivity();
    }
  }

  onButtonPress = () => {
    console.log("will jump to setting page");
    let navigator = this.props.navigator;
    if (navigator != undefined) {
      this.props.navigator.push({
        name: "setActivity"
      });
    } else {

    }

  }

  render() {
    return (
      <View>
        <TouchableHighlight
          style={styles.backBtn}
          underlayColor = '#e4083f'
          activeOpacity = {0.5}
          onPress = {this.onBackPress}>
          <Text>
            Back
          </Text>
        </TouchableHighlight>
        <Text
          style={styles.welcome}> 
          Welcome ! 
        </Text> 
        <TouchableHighlight underlayColor = '#e4083f'
          activeOpacity = {0.5}
          style = {styles.btnStyle}
          onPress = {this.onButtonPress}>
          <Text style={styles.btnTextStyle}>
            Jump To Setting page!
          </Text> 
        </TouchableHighlight>
        </View>
    );
  }
}

var styles = StyleSheet.create({
  backBtn: {
    padding: 10,
    marginTop: 10,
    marginLeft: 10,
    borderWidth: 1,
    borderColor: '#3e83d7',
    backgroundColor: '#3e83d7',
    borderRadius: 8,
    alignSelf: 'flex-start'
  },
  welcome: {
    textAlign: 'center',
    margin: 10,
  },
  btnStyle: {
    marginTop: 10,
    borderWidth: 1,
    borderColor: '#3e83d7',
    borderRadius: 8,
    backgroundColor: '#3e83d7',
    alignSelf: 'center',
    justifyContent: 'center'
  },
  btnTextStyle: {
    textAlign: 'center',
    fontSize: 25,
    color: '#ffffff'
  },
});

AppRegistry.registerComponent('SecondActivity', () => second);

這樣就完成了用戶點擊通知后的自定義跳轉(zhuǎn)界面。

接收自定義消息

在用戶收到自定義消息后觸發(fā)。

example/react-native-android/push_activity.js

 ...
    componentDidMount() {
        JPushModule.addReceiveCustomMsgListener((map) => {
            this.setState({
                pushMsg: map.message
            });
            console.log("extras: " + map.extras);
    });
...
得到 RegistrationId

用戶注冊成功后(一般在用戶啟動應(yīng)用后),如果訂閱了這個事件,將會收到這個 registrationId。

...
    componentDidMount() {
        JPushModule.addGetRegistrationIdListener((registrationId) => {
            console.log("Device register succeed, registrationId " + registrationId);
        });
    }
清除所有通知

建議在用戶退出前臺后調(diào)用。

    ...
    componentWillUnmount() {
        console.log("Will clear all notifications");
        JPushModule.clearAllNotifications();
    }
設(shè)置標簽

example/react-native-android/set_activity.js

    ...
    setTag() {
        if (this.state.tag !== undefined) {
            /*
            * 請注意這個接口要傳一個數(shù)組過去,這里只是個簡單的示范
            */      
            JPushModule.setTags(["VIP", "NOTVIP"], () => {
                console.log("Set tag succeed");
            }, () => {
                console.log("Set tag failed");
            });
        }
    }
設(shè)置別名
    ...
    setAlias() {
        if (this.state.alias !== undefined) {
            JPushModule.setAlias(this.state.alias, () => {
                console.log("Set alias succeed");
            }, () => {
                console.log("Set alias failed");
            });
        }
    }

以上就是插件提供的主要接口的示例??偟膩碚f,配置和使用都比較簡單,適合開發(fā)者快速集成推送功能。

當前標題:用jpush-react-native插件快速集成推送功能(Android篇)
標題路徑:http://bm7419.com/article48/igdghp.html

成都網(wǎng)站建設(shè)公司_創(chuàng)新互聯(lián),為您提供網(wǎng)站排名、響應(yīng)式網(wǎng)站、用戶體驗、虛擬主機、GoogleChatGPT

廣告

聲明:本網(wǎng)站發(fā)布的內(nèi)容(圖片、視頻和文字)以用戶投稿、用戶轉(zhuǎn)載內(nèi)容為主,如果涉及侵權(quán)請盡快告知,我們將會在第一時間刪除。文章觀點不代表本網(wǎng)站立場,如需處理請聯(lián)系客服。電話:028-86922220;郵箱:631063699@qq.com。內(nèi)容未經(jīng)允許不得轉(zhuǎn)載,或轉(zhuǎn)載時需注明來源: 創(chuàng)新互聯(lián)

外貿(mào)網(wǎng)站制作