简介
消息推送(Push)指运营人员通过自己的产品或第三方工具对用户移动设备进行的主动消息推送。用户可以在移动设备锁定屏幕和通知栏看到push消息通知,通知栏点击可唤起APP并去往相应页面。我们平时在锁屏上看到的微信消息等等都属于APP消息推送行列。使用极光推送, C# 服务端推送到 Demo App,Android 手机收到推送,整理为十个步骤,使用十分钟左右,完成从注册账号到 Android 手机上的 Demo App 收到推送。.
步骤
1.注册极光账号 注册页面:https://www.jiguang.cn/accounts/register/form
2.创建应用 控制台:https://www.jiguang.cn/dev/#/app/list
创建应用:https://www.jiguang.cn/dev/#/app/create
创建之后回到应用管理:https://www.jiguang.cn/dev/#/app/list
3.获取 AppKey 和 Master Secret 点击应用管理界面的应用详情 获取 AppKey 和 Master Secret
4.下载 Demo 在上一步骤的同一界面下载 Demo 点击扫描下载安装包
手机下载安装即可,安装好之后打开 Demo App。
5.下载 jpush-api-csharp-client 项目地址:https://github.com/jpush/jpush-api-csharp-client/releases
-
VS 打开项目,安装依赖 NuGet 包管理工具会下载 jpush-api-csharp-client 和 Newtonsoft 依赖。
7.替换 AppKey 和 Master Secret
主要方法
添加标签
public Result AddDeviceTags(string userId, HashSet<string> tags)
{
return SetDeviceTags(userId, tags, Action.AddDeviceTags);
}
移除标签
public Result RemoveDeviceTags(string userId, HashSet<string> tags)
{
return SetDeviceTags(userId, tags, Action.RemoveDeviceTags);
}
添加别名
public void AddAlias(string registrationId, string alias)
{
if (string.IsNullOrWhiteSpace(registrationId) || string.IsNullOrWhiteSpace(alias))
throw new Exception("设备标识和别名不能为空。");
var result = DeviceClient.UpdateDeviceInfo(registrationId, new DevicePayload { Alias = alias });
if (result.StatusCode == HttpStatusCode.OK)
return;
var errorMsg =
$"别名添加失败,HTTP 状态码:{result.StatusCode}" +
$",返回信息:{result.Content}" +
$",别名:{alias},设备标识:{registrationId}";
WriteErrorLog(errorMsg);
}
生成标签推送信息
private PushPayload PushPayloadForTag()
{
var notification = GetNotification();
SetIosSoundSilent(notification);
if (Audiences.Count > 20)
{
Audiences.RemoveRange(20, Audiences.Count - 20);
WriteErrorLog("消息推送标签超过20个,自动取前20个进行推送。");
}
return new PushPayload
{
Platform = new List<string> { "android", "ios" },
Audience = new { tag = Audiences.ToArray() },//"all",//
Notification = notification,
Options = new Options { TimeToLive = TimeToLive, IsApnsProduction = IsApnsProduction() }
};
}
发送消息推送
public bool Send()
{
PushPayload payload;
switch (PushType)
{
case PushType.Tag:
if (Audiences == null || Audiences.Count == 0)
throw new Exception("推送目标集合不能为空。");
payload = PushPayloadForTag();
break;
case PushType.Alias:
if (Audiences == null || Audiences.Count == 0)
throw new Exception("推送目标集合不能为空。");
payload = PushPayloadForAlias();
break;
case PushType.All:
// 极光免费版限制了广播次数,每天10次,现改为标签推送代替
//payload = PushPayloadForAll();
//zsj 2021-01-19 先兼容下之前调用此处代码没给Category赋值的Category== ProgramCategory.None,后续排查完后这段代码这删掉
if (Category == ProgramCategory.Basketball || Category == ProgramCategory.None)
Audiences = new List<string> { UserBll.BroadcastTagBasketball };
else if (Category == ProgramCategory.Football)
Audiences = new List<string> { UserBll.BroadcastTagFootball };
else if (Category == ProgramCategory.ESports)
Audiences = new List<string> { UserBll.BroadcastTagESports };
payload = PushPayloadForTag();
break;
default:
return false;
}
try
{
//zsj 2021-05-31 计算推送前后的时间差
DateTime dtNow = DateTime.Now;
// WriteErrorLog("极光开始推送,JPushClient,推送前时间:" + dtNow + ";ContentId[即AssociateId]=" + ContentId + ";Title=" + Title + ";Message=" + Message + ";ContentTitle=" + ContentTitle, Xmzy.Common.Tools.Log.LogSource.ApiExecute, "极光推送");
if (payload.Options == null)
{
payload.Options = new Options() { TimeToLive = 60 * 60 * 3 };
}
else
{
payload.Options.TimeToLive = 60 * 60 * 3;
}
if (isdisand == "0")
{
List<string> p = new List<string>();
p.Add("ios");
//["android", "ios","quickapp"]
payload.Platform = p.ToArray();
// "platform": "all",
}
var result = JPushClient.SendPush(payload);
DateTime dtNow2 = DateTime.Now;
TimeSpan ts = dtNow2 - dtNow;
// WriteErrorLog("极光开始推送,JPushClient,推送后时间:" + dtNow2 + ";间隔相差" + ts.TotalSeconds + "秒" + ";ContentId[即AssociateId]=" + ContentId + ";Title=" + Title + ";Message=" + Message + ";ContentTitle=" + ContentTitle, Xmzy.Common.Tools.Log.LogSource.ApiExecute, "极光推送");
_Logger.Error("payload------" + JsonConvert.SerializeObject(payload));
_Logger.Error("result-----------" + JsonConvert.SerializeObject(result));
if (result.StatusCode != HttpStatusCode.OK)
{
WriteErrorLog("消息推送失败,HTTP 状态码:" + result.StatusCode
+ ",返回信息:" + result.Content + "。");
}
return true;
}
catch (Exception e)
{
WriteErrorLog(e.Message);
return false;
}
}