极光推送是我第一款接触的第三方推送,刚开始接触难免会遇到坑。下面我记录一下C#极光推送的主要布置。
第一步:项目需要引用 cn.jpush.api.dll(这里直接从nuget包中引用就好)
第二步:推送配置(具体设置参照官方文档,我这里只是我用到的配置)
/// <summary>
/// 推送配置
/// </summary>
/// <param name="registerid">推送列表(设备别号)</param>
/// <param name="pushAlert">标题</param>
/// <param name="pushList">推送附加参数</param>
/// <returns></returns>
private static PushPayload PushObject_RegisterID(HashSet<string> registerid, string pushAlert, List<Push> pushList)
{
PushPayload pushPayload = new PushPayload();
pushPayload.platform = Platform.all();
pushPayload.audience = Audience.s_registrationId(registerid);
//通知获取
var notification = new Notification().setAlert(pushAlert);
notification.AndroidNotification = new AndroidNotification();
notification.IosNotification = new IosNotification();
foreach (var model in pushList)
{
notification.AndroidNotification.AddExtra(model.Key, model.Value);// Android推送消息
notification.IosNotification.AddExtra(model.Key, model.Value);// IOS推送消息
notification.IosNotification.setSound("happy"); // 苹果声音提示
pushPayload.notification = notification.Check();
}
return pushPayload;
}
第三步:推送
/// <summary>
/// 推送
/// </summary>
/// <param name="pushTitle">标题</param>
/// <param name="registerId">设备识别号列表</param>
/// <param name="pushList">附加参数</param>
/// <returns></returns>
public static bool JPushByRegiserID(string pushTitle, HashSet<string> registerId, List<Push> pushList)
{
if (!isAllew)
{
return false;
}
string appKey = AppKey.SystemSetValue;//极光推送appkey官网配置
string masterSecret = MasterSecret.SystemSetValue;//极光推送秘钥官网配置
JPushClient client = new JPushClient(appKey, masterSecret);
PushPayload payload = PushObject_RegisterID(registerId, pushTitle, pushList);
try
{
var result = client.SendPush(payload);
//由于统计数据并非非是即时的,所以等待一小段时间再执行下面的获取结果方法
if (result.sendno.ToString() == "0")
{
return true;
}
return false;
}
catch (APIRequestException e)
{
return false;
}
}
注意:极光推送某些安卓手机因为静置一段时间会杀死程序的原因会收不到推送(略坑,当时项目经理非要解决这问题,跟手机端用尽浑身解数都没能解决,然后翻找官方记录才发现原来是一直存在的问题,小的无能啊)