1.Unity快速接入
进入官网,下载最新版本,然后按接入文档接入
1.baseProjectTemplate的设置
// GENERATED BY UNITY. REMOVE THIS COMMENT TO PREVENT OVERWRITING WHEN EXPORTING AGAIN
allprojects {
buildscript {
repositories {**ARTIFACTORYREPOSITORY**
google()
jcenter()
// hms, 若不集成华为厂商通道,可直接跳过
maven { url 'http://developer.huawei.com/repo/'}
// fcm, 若不集成 FCM 通道,可直接跳过
maven { url "https://maven.google.com" }
}
dependencies {
// If you are changing the Android Gradle Plugin version, make sure it is compatible with the Gradle version preinstalled with Unity
// See which Gradle version is preinstalled with Unity here https://docs.unity3d.com/Manual/android-gradle-overview.html
// See official Gradle and Android Gradle Plugin compatibility table here https://developer.android.com/studio/releases/gradle-plugin
// To specify a custom Gradle version in Unity, go do "Preferences > External Tools", uncheck "Gradle Installed with Unity (recommended)" and specify a path to a custom Gradle version
classpath 'com.android.tools.build:gradle:4.0.1'
// fcm,若不集成 FCM 通道,可直接跳过
//classpath 'com.google.gms:google-services:4.3.8'
// hms,若不集成华为厂商通道,可直接跳过
classpath 'com.huawei.agconnect:agcp:1.6.0.300'
**BUILD_SCRIPT_DEPS**
}
}
repositories {**ARTIFACTORYREPOSITORY**
google()
jcenter()
// hms, 若不集成华为厂商通道,可直接跳过
maven { url 'http://developer.huawei.com/repo/'}
// fcm, 若不集成 FCM 通道,可直接跳过
maven { url "https://maven.google.com" }
flatDir {
dirs "${project(':unityLibrary').projectDir}/libs"
}
}
}
task clean(type: Delete) {
delete rootProject.buildDir
}
2.mainTemplate.gradle 的设置
// GENERATED BY UNITY. REMOVE THIS COMMENT TO PREVENT OVERWRITING WHEN EXPORTING AGAIN
apply plugin: 'com.android.library'
//apply plugin: 'com.google.gms.google-services'
apply plugin: 'com.huawei.agconnect'
**APPLY_PLUGINS**
dependencies {
implementation fileTree(dir: 'libs', include: ['*.jar'])
//方便控制一些jar包,直接将一些jar包放置到libs目录下即可
// 此处以JCore 3.2.2 版本为例。
//implementation 'cn.jiguang.sdk:jcore:3.2.2'
// 此处以JPush 4.6.2 版本为例
//implementation 'cn.jiguang.sdk:jpush:4.6.2'
//若不集成厂商通道,可直接跳过以下依赖
// 接入华为厂商
//implementation 'com.huawei.hms:push:6.1.0.300'
//仅使用 com.huawei.hms:push:6.1.0.XXX 版本需要加 base 依赖,其他版本不需要
//implementation 'com.huawei.hms:base:6.2.0.300'
// 极光厂商插件版本与接入 JPush 版本保持一致,下同
//implementation 'cn.jiguang.sdk.plugin:huawei:4.6.2'
// 接入 FCM 厂商
//implementation 'com.google.firebase:firebase-messaging:23.0.0'
//implementation 'cn.jiguang.sdk.plugin:fcm:4.6.2'
// 接入魅族厂商
//implementation 'cn.jiguang.sdk.plugin:meizu:4.6.2'
// 接入 VIVO 厂商
//implementation 'cn.jiguang.sdk.plugin:vivo:4.6.2'
// 接入小米厂商
//implementation 'cn.jiguang.sdk.plugin:xiaomi:4.6.2'
// 接入 OPPO 厂商
//implementation 'cn.jiguang.sdk.plugin:oppo:4.6.2'
// oppo 厂商 aar 需要单独引入,请将 jpush-android-xxx-release/third-push/oppo/libs 下 com.heytap.msp-push-x.x.x.aar 单独拷贝一份到应用 module/libs 下
implementation(name: 'com.heytap.msp-push-3.0.0', ext: 'aar')
//以下为 OPPO 3.0.0 aar需要依赖
implementation 'com.google.code.gson:gson:2.6.2'
implementation 'commons-codec:commons-codec:1.6'
implementation 'androidx.annotation:annotation:1.1.0'
//AAPT: error: style attribute 'attr/colorPrimary (aka com.szw.jg0412:attr/colorPrimary)' not found.
//implementation 'androidx.appcompat:appcompat:1.0.0-alpha1'
**DEPS**}
android {
compileSdkVersion **APIVERSION**
buildToolsVersion '**BUILDTOOLS**'
compileOptions {
sourceCompatibility JavaVersion.VERSION_1_8
targetCompatibility JavaVersion.VERSION_1_8
}
defaultConfig {
minSdkVersion **MINSDKVERSION**
targetSdkVersion **TARGETSDKVERSION**
ndk {
abiFilters **ABIFILTERS**
}
versionCode **VERSIONCODE**
versionName '**VERSIONNAME**'
consumerProguardFiles 'proguard-unity.txt'**USER_PROGUARD**
}
lintOptions {
abortOnError false
}
aaptOptions {
noCompress = ['.ress', '.resource', '.obb'] + unityStreamingAssets.tokenize(', ')
ignoreAssetsPattern = "!.svn:!.git:!.ds_store:!*.scc:.*:!CVS:!thumbs.db:!picasa.ini:!*~"
}**PACKAGING_OPTIONS**
}**REPOSITORIES**
**IL_CPP_BUILD_SETUP**
**SOURCE_BUILD_SETUP**
**EXTERNAL_SOURCES**
3.Android/libs 的配置
直接拷贝极光的libs和src到unity的Android目录
4.AndroidManifest的配置
Activity的设置
<activity android:name="com.longtugame.rjsdk.MainActivity"
android:configChanges="orientation|keyboard|keyboardHidden|screenLayout|screenSize"
android:allowEmbedded="@string/app_name"
android:exported = "true"
android:theme="@android:style/Theme.NoTitleBar">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
<meta-data android:name="unityplayer.UnityActivity"
android:value="true" />
</activity>
自定义PushService(必要)
unity中的配置
<service
android:name=".PushService"
android:exported="true"
android:enabled="true"
>
<intent-filter>
<action android:name="cn.jiguang.user.service.action" />
</intent-filter>
</service>
Android 直接定义即可
自定义PushMessageReceiver(必要)
unity 配置:
<receiver android:name=".PushMessageReceiver"
android:exported="true"
android:enabled="true">
<intent-filter>
<action android:name="cn.jpush.android.intent.RECEIVE_MESSAGE" />
<category android:name="${applicationId}"></category>
</intent-filter>
</receiver>
android 侧参考:
package cn.kkvideos;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.util.Log;
import cn.jpush.android.api.CmdMessage;
import cn.jpush.android.api.CustomMessage;
import cn.jpush.android.api.JPushInterface;
import cn.jpush.android.api.JPushMessage;
import cn.jpush.android.api.NotificationMessage;
import cn.jpush.android.service.JPushMessageReceiver;
public class PushMessageReceiver extends JPushMessageReceiver {
private static final String TAG = "PushMessageReceiver";
@Override
public void onMessage(Context context, CustomMessage customMessage) {
Log.e(TAG, "[onMessage] " + customMessage);
Intent intent = new Intent("com.jiguang.demo.message");
intent.putExtra("msg", customMessage.message);
context.sendBroadcast(intent);
}
@Override
public void onNotifyMessageOpened(Context context, NotificationMessage message) {
Log.e(TAG, "[onNotifyMessageOpened] " + message);
try{
//打开自定义的Activity
Intent i = new Intent(context, TestActivity.class);
Bundle bundle = new Bundle();
bundle.putString(JPushInterface.EXTRA_NOTIFICATION_TITLE,message.notificationTitle);
bundle.putString(JPushInterface.EXTRA_ALERT,message.notificationContent);
i.putExtras(bundle);
i.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TOP );
context.startActivity(i);
}catch (Throwable throwable){
}
}
@Override
public void onMultiActionClicked(Context context, Intent intent) {
Log.e(TAG, "[onMultiActionClicked] 用户点击了通知栏按钮");
String nActionExtra = intent.getExtras().getString(JPushInterface.EXTRA_NOTIFICATION_ACTION_EXTRA);
//开发者根据不同 Action 携带的 extra 字段来分配不同的动作。
if (nActionExtra == null) {
Log.d(TAG, "ACTION_NOTIFICATION_CLICK_ACTION nActionExtra is null");
return;
}
if (nActionExtra.equals("my_extra1")) {
Log.e(TAG, "[onMultiActionClicked] 用户点击通知栏按钮一");
} else if (nActionExtra.equals("my_extra2")) {
Log.e(TAG, "[onMultiActionClicked] 用户点击通知栏按钮二");
} else if (nActionExtra.equals("my_extra3")) {
Log.e(TAG, "[onMultiActionClicked] 用户点击通知栏按钮三");
} else {
Log.e(TAG, "[onMultiActionClicked] 用户点击通知栏按钮未定义");
}
}
//消息到达消息信息
@Override
public void onNotifyMessageArrived(Context context, NotificationMessage message) {
Log.e(TAG, "[onNotifyMessageArrived] " + message);
}
@Override
public void onNotifyMessageDismiss(Context context, NotificationMessage message) {
Log.e(TAG, "[onNotifyMessageDismiss] " + message);
}
@Override
public void onRegister(Context context, String registrationId) {
Log.e(TAG, "[onRegister] " + registrationId);
Intent intent = new Intent("com.jiguang.demo.register");
context.sendBroadcast(intent);
}
@Override
public void onConnected(Context context, boolean isConnected) {
Log.e(TAG, "[onConnected] " + isConnected);
}
@Override
public void onCommandResult(Context context, CmdMessage cmdMessage) {
Log.e(TAG, "[onCommandResult] " + cmdMessage);
}
@Override
public void onTagOperatorResult(Context context, JPushMessage jPushMessage) {
//TagAliasOperatorHelper.getInstance().onTagOperatorResult(context,jPushMessage);
super.onTagOperatorResult(context, jPushMessage);
}
@Override
public void onCheckTagOperatorResult(Context context, JPushMessage jPushMessage) {
//TagAliasOperatorHelper.getInstance().onCheckTagOperatorResult(context,jPushMessage);
super.onCheckTagOperatorResult(context, jPushMessage);
}
@Override
public void onAliasOperatorResult(Context context, JPushMessage jPushMessage) {
//TagAliasOperatorHelper.getInstance().onAliasOperatorResult(context,jPushMessage);
super.onAliasOperatorResult(context, jPushMessage);
}
@Override
public void onMobileNumberOperatorResult(Context context, JPushMessage jPushMessage) {
//TagAliasOperatorHelper.getInstance().onMobileNumberOperatorResult(context,jPushMessage);
super.onMobileNumberOperatorResult(context, jPushMessage);
}
@Override
public void onNotificationSettingsCheck(Context context, boolean isOn, int source) {
super.onNotificationSettingsCheck(context, isOn, source);
Log.e(TAG, "[onNotificationSettingsCheck] isOn:" + isOn + ",source:" + source);
}
}
2.官网包的离线推送:
官网包需要有各个渠道推送相关的jar包,要不离线推送不好使 1.小米后台有多渠道的配置,直接将官网包的包名配置上即可 2.华为渠道,需要在华为后台创建官网渠道包包名的应用 3.华为官网下载的类库不全,推介grade下载到本地,提供个脚本
apply plugin: 'java'
def dest = "test"
repositories {
maven {url 'http://developer.huawei.com/repo/'}
}
dependencies {
compile 'com.huawei.hms:base:6.2.0.300'
compile 'com.huawei.hms:push:6.1.0.300'
}
task downloadJars(type: Copy) {
println dest
from configurations.runtime
into 'libs'
}
//gradle downloadJars
3.各个渠道包的离线推送:
OPPO:
1.OPPO手机安装时默认通知权限关闭,测试时注意先打开通知权限,不然无法收到。 2.点击通知打不开应用(android11)(Intent方式),已反馈感觉他们无心解决的样子
华为:
1.外网开发接入还好,内网开发,需要搭marven仓库做中转 2.华为appid定义,其它参数同理按需添加
<meta-data
android:name="com.huawei.hms.client.appid"
android:value="testid" />
3.agconnect-services.json unity读取(实际测试不需要) 参考网址: https://github.com/Unity-Technologies/HMSSDKSample 脚本位置:Assets/HuaweiHms/src/Editor/AfterBuildToDo.cs
using System;
using UnityEngine;
using UnityEditor;
using System.IO;
using System.Text;
using UnityEditor.Callbacks;
using UnityEditor.Android;
public class AfterBuildToDO : IPostGenerateGradleAndroidProject
{
public int callbackOrder
{
get { return 0; }
}
private bool compareVersion(string version1, string version2)
{
string[] version1List = version1.Split('.');
string[] version2List = version2.Split('.');
int v1year = Int32.Parse(version1List[0]);
int v2year = Int32.Parse(version2List[0]);
if (v1year != v2year)
{
return v1year > v2year;
}
int v1sub = Int32.Parse(version1List[1]);
int v2sub = Int32.Parse(version2List[1]);
return v1sub > v2sub;
}
private string getOutputPath(string path)
{
if (compareVersion("2019.3", Application.unityVersion))
{
return path;
}
DirectoryInfo parent = new DirectoryInfo(path).Parent;
return Path.Combine(parent.FullName, "launcher");
}
public void CopyResource(string path)
{
string sourceDir = Application.dataPath + "/HuaweiService/Android/res/xml/";
if (!Directory.Exists(sourceDir))
{
return;
}
var fileList = Directory.GetFiles(sourceDir, "*.xml");
if (fileList.Length <= 0)
{
return;
}
string targetDir = path + "/src/main/res/xml/";
if (!Directory.Exists(targetDir))
{
Directory.CreateDirectory(targetDir);
}
foreach (var file in fileList)
{
string fileName = Path.GetFileName(file);
File.Copy(Path.Combine(sourceDir, fileName), Path.Combine(targetDir, fileName), true);
}
}
public void OnPostGenerateGradleAndroidProject(string path)
{
Debug.Log(path);
string launcherPath = getOutputPath(path);
Debug.Log(launcherPath);
//读取源文件路径
string sourcePath = Application.dataPath + "/Plugins/Android/agconnect-services.json";
//拷贝文件(源路径及文件名, 拷贝路径及文件名, 若该文件名已存在,是否替换)
File.Copy(sourcePath, launcherPath + "/agconnect-services.json", true);
CopyResource(path);
AddAuthFile(sourcePath, path);
}
public void AddAuthFile(string sourcePath,string path)
{
File.Copy(sourcePath,path+ "/agconnect-services.json", true);
AddWxEntryActivityToAndroid(path);
AddxmltoAndroid(path);
}
private void AddxmltoAndroid(string path)
{
var basePath = path + "/src/main/res/values";
if (!Directory.Exists(basePath))
{
Directory.CreateDirectory(basePath);
}
var codePath = basePath + "/strings.xml";
if (!Directory.Exists(basePath))
{
Directory.CreateDirectory(basePath);
}
string sourceFilePath = Application.dataPath + "/HuaweiService/Android/res/Auth/strings.txt";
if (File.Exists(sourceFilePath))
{
if (File.Exists(codePath))
{
string stringsFile = File.ReadAllText(codePath);
string appendContent = File.ReadAllText(sourceFilePath);
stringsFile = stringsFile.Replace("</resources>", appendContent);
File.WriteAllText(codePath, stringsFile);
}
else
{
string appendContent = "<?xml version=\"1.0\" encoding=\"utf-8\"?>"+"\r\n"+"<resources>"+"\r\n" +File.ReadAllText(sourceFilePath);
File.WriteAllText(codePath, appendContent);
}
}
}
private void AddWxEntryActivityToAndroid(string proejectPath)
{
var basePath = GetPackagePath(proejectPath, Application.identifier) + "/wxapi";
if (!Directory.Exists(basePath))
{
Directory.CreateDirectory(basePath);
}
var codePath = basePath + "/WXEntryActivity.java";
if (File.Exists(codePath)) // do not overwrite what has been done by developer
{
return;
}
var code = Resources.Load<TextAsset>("WXEntryActivity");
if (code != null)
{
var generatedCode = code.text.Replace("com.unity.EndlessRunnerSampleGame.TkeDemo", Application.identifier);
var writer = new StreamWriter(codePath, false);
writer.Write(generatedCode);
writer.Close();
}
}
private string GetPackagePath(string basePath, string package)
{
var pathBuilder = new StringBuilder(basePath);
pathBuilder.Append(Path.DirectorySeparatorChar).Append("src");
pathBuilder.Append(Path.DirectorySeparatorChar).Append("main");
pathBuilder.Append(Path.DirectorySeparatorChar).Append("java");
var codePath = package.Split('.');
foreach (var p in codePath)
{
pathBuilder.Append(Path.DirectorySeparatorChar).Append(p);
}
return pathBuilder.ToString();
}
}
VIVO
1.未正式上架的需要添加测试设备 2.需要服务器配合发送推送测试消息,具体见极光官方文档
4.集成结果判断
https://docs.jiguang.cn/jpush/client/Android/android_3rd_guide 极光集成结果
D/JIGUANG-JPush: [ActionHelper] doAction:init
......
I/JIGUANG-JCore: [ConnectingHelper] Register succeed - juid:58446897155, registrationId:1104a89792620fb0b02, deviceId:null
渠道集成结果
I/JIGUANG-JPush: [HWPushHelper] get huawei token:IQAAAACy0aL1AABEZ3l2C7jluCGX5XriooCvoOwK9TrjG1MTpH0CD47WPXFcAbtt3DdOeOPvX6d7xfAVctoyaOCGKRllRa-0RBP7WQrYI6SxnOp1GA
I/JIGUANG-JPush: [HWPushHelper] isNeedReport:true
D/JIGUANG-JPush: [ActionHelper] doAction:third_action
D/JIGUANG-JPush: [ThirdPushManager] doAction,action:action_register_token,bundle:Bundle[{third_key_action=action_register_token, token=IQAAAACy0aL1AABEZ3l2C7jluCGX5XriooCvoOwK9TrjG1MTpH0CD47WPXFcAbtt3DdOeOPvX6d7xfAVctoyaOCGKRllRa-0RBP7WQrYI6SxnOp1GA, platform=2}],enable:true
I/JIGUANG-JPush: [ThirdPushManager] uploadRegID regid:IQAAAACy0aL1AABEZ3l2C7jluCGX5XriooCvoOwK9TrjG1MTpH0CD47WPXFcAbtt3DdOeOPvX6d7xfAVctoyaOCGKRllRa-0RBP7WQrYI6SxnOp1GA
|