您的位置:首页 > 其它

百度云推送的研究

2016-05-17 16:36 141 查看
0.下一个百度云推送的demo

1.准备一个自己的API KEY,否则绑定失败,无法接收到推送的消息。

2.在androidManifest.xml 中将api_key修改并且保存。

<meta-data
android:name="api_key"
android:value="my_api_key"
/>


3.修改之后就可以进行运行了,运行的是百度云推送的demo.

4.注意:如果您的Android工程使用的是Android API level 21及以上的版本,您的通知图标背景必须是透明的,否则在Android5.0及以上的机器上通知图标可能会变成白色的方块。

5.运行App

右键点击当前工程,选择Run As –> Android Application,选中已连接的设备或Android虚拟机,运行该程序。如果在logcat中的回调函数中的errorCode为0,说明已经绑定成功,并返回userid和channelid,我们就可以在云控制台推送通知和透传消息到该app了。

6.通知到达时,当通知被用户点击时,会回调onNotificationClicked函数。

以下开始云推送的使用流程。

1.在主Activity中初始化PushManager.startWork();方法。

注:这个初始化通常在刚启动的时候进行。

2.

private void initBaiduPush() {
String pkgName = this.getPackageName();
// Push: 以apikey的方式登录,一般放在主Activity的onCreate中。
// 这里把apikey存放于manifest文件中,只是一种存放方式,
// 您可以用自定义常量等其它方式实现,来替换参数中的Utils.getMetaValue(PushDemoActivity.this,
// "api_key")
//        !! 请将AndroidManifest.xml 128 api_key 字段值修改为自己的 api_key 方可使用 !!
//        !! ATTENTION:You need to modify the value of api_key to your own at row 128 in AndroidManifest.xml to use this Demo !!

//这里加载了PushManager重载时候的参数项目
PushManager.startWork(getApplicationContext(), PushConstants.LOGIN_TYPE_API_KEY,
Utils.getMetaValue(this, "api_key"));
// Push: 如果想基于地理位置推送,可以打开支持地理位置的推送的开关
// PushManager.enableLbs(getApplicationContext());
//PushManager类定义的方法,开启精确LBS推送模式,覆盖最近半小时内在指定区域出现过的终端。
// Push: 设置自定义的通知样式,具体API介绍见用户手册,如果想使用系统默认的可以不加这段代码
// 请在通知推送界面中,高级设置->通知栏样式->自定义样式,选中并且填写值:1,
// 与下方代码中 PushManager.setNotificationBuilder(this, 1, cBuilder)中的第二个参数对应
CustomPushNotificationBuilder cBuilder = new CustomPushNotificationBuilder(
getResources().getIdentifier(
"notification_custom_builder", "layout", pkgName),
getResources().getIdentifier("notification_icon", "id", pkgName),
getResources().getIdentifier("notification_title", "id", pkgName),
getResources().getIdentifier("notification_text", "id", pkgName));
cBuilder.setNotificationFlags(Notification.FLAG_AUTO_CANCEL);
cBuilder.setNotificationDefaults(Notification.DEFAULT_VIBRATE);
cBuilder.setStatusbarIcon(this.getApplicationInfo().icon);
cBuilder.setLayoutDrawable(getResources().getIdentifier(
"simple_notification_icon", "drawable", pkgName));
cBuilder.setNotificationSound(Uri.withAppendedPath(
MediaStore.Audio.Media.INTERNAL_CONTENT_URI, "6").toString());
// 推送高级设置,通知栏样式设置为下面的ID
PushManager.setNotificationBuilder(this, 1, cBuilder);

}


补充

1.使用AndroidManifast存放数据信息如

<meta-data
android:name="api_key"
android:value="IEelqeBI554Yll5l776MO0jb0UN31iFx" />


存放了开发者的api_key

// 获取ApiKey
public static String getMetaValue(Context context, String metaKey) {
Bundle metaData = null;
String apiKey = null;
if (context == null || metaKey == null) {
return null;
}
try {
ApplicationInfo ai = context.getPackageManager()
.getApplicationInfo(context.getPackageName(),
PackageManager.GET_META_DATA);
if (null != ai) {
metaData = ai.metaData;
}
if (null != metaData) {
apiKey = metaData.getString(metaKey);
}
} catch (NameNotFoundException e) {
Log.e(TAG, "error " + e.getMessage());
}
return apiKey;
}


使用上面的静态方法进行获取androidmainfast.xml中的数据

以上为在主程序中初始化pushManager 主要进行数据显示内容的绑定。

绑定之后会回调onBind方法来

错误码说明

error_code 描述

0 绑定成功

10001 当前网络不可用,请检查网络

10002 服务不可用,连接server失败

10003 服务不可用,503错误

10101 应用集成方式错误,请检查各项声明和权限

20001 未知错误

30600 服务内部错误

30601 非法函数请求,请检查您的请求内容

30602 请求参数错误,请检查您的参数

30603 非法构造请求,服务端验证失败

30605 请求的数据在服务端不存在

30608 绑定关系不存在或未找到

30609 一个百度账户绑定设备超出个数限制(多台设备登录同一个百度账户)

30612 百度账户绑定应用时被禁止,需要白名单授权

以上为在检测打开绑定之后的绑定状态,根据协议进行查看为什么错误。

在public class MyPushMessageReceiver extends PushMessageReceiver中的第一个回调方法。

@Override
public void onBind(Context context, int errorCode, String appid,
String userId, String channelId, String requestId) {

this.context=context;
String responseString = "onBind errorCode=" + errorCode + " appid="
+ appid + " userId=" + userId + " channelId=" + channelId
+ " requestId=" + requestId;
Log.d(TAG, responseString);

strURL=context.getString(R.string.myip)+ "index.php?m=api&c=member&a=login";

if (errorCode == 0) {
SharedPreferences spbdinfo =context.getSharedPreferences("bdinfo", context.MODE_PRIVATE);
//1
SharedPreferences.Editor edit = spbdinfo.edit();
edit.putString("appid", appid).commit();
edit.putString("userId", userId).commit();
edit.putString("channelId", channelId).commit();
// 绑定成功
//            SharedPreferences.Editor edit = preferences.edit();
//            edit.putString("appid", appid).commit();
//            edit.putString("bduserid", userId).commit();
//            edit.putString("channelId", channelId).commit();
Log.d(TAG, "绑定成功");

struserbdid="";
if(userId!=null&&!userId.equals("")){
struserbdid=userId;
}
strchanellid="";
if(channelId!=null&&!channelId.equals("")){
strchanellid=channelId;
}
}
SharedPreferences preferences =context.getSharedPreferences("usr", context.MODE_PRIVATE);
String strislogin = preferences.getString("islogin", null);
if(strislogin!=null&&strislogin.equals("1")) {
strusername = preferences.getString("username", null);
struserpwd= preferences.getString("password", null);
struserappid="";
if(appid!=null&&!appid.equals("")){
struserappid=appid;
}
struserbdid="";
if(userId!=null&&!userId.equals("")){
struserbdid=userId;
}
strchanellid="";
if(channelId!=null&&!channelId.equals("")){
strchanellid=channelId;
}
new MyLonginTask().execute(strURL);
}
//        onBind errorCode=0 appid=7965237 userId=778716642974133117 channelId=3872589929068272117 requestId=531300769
// Demo更新界面展示代码,应用请在这里加入自己的处理逻辑
//        updateContent(context, responseString);
}


对于以上内容返回的信息 其中appid=8142786 是在申请应用云推送的时候建立的。

而channelId是根据绑定成功而新建立的。

以上就完成了接手服务器发送通知的准备工作了!

然后开始做接收信息的准备

推送透传消息

当设备接收到透传消息时,消息不会在通知栏展示,只是静默回调开发者自定义Receiver中的onMessage函数。手机收到消息后不会有任何现象,因为透传消息对用户完全透明,用户无法感知,便于开发者在不影响用户的情况下对app进行操作。开发者可以通过log内容和自定义的回调函数onMessage中打印该内容,确认消息到达,并执行开发者指定操作。

/**
* 接收透传消息的函数。
*
* @param context
*            上下文
* @param message
*            推送的消息
* @param customContentString
*            自定义内容,为空或者json字符串
*/
@Override
public void onMessage(Context context, String message,
String customContentString) {
String messageString = "透传消息 message=\"" + message
+ "\" customContentString=" + customContentString;
Log.d(TAG, messageString);

// 自定义内容获取方式,mykey和myvalue对应透传消息推送时自定义内容中设置的键和值
if (!TextUtils.isEmpty(customContentString)) {
JSONObject customJson = null;
try {
customJson = new JSONObject(customContentString);
String myvalue = null;
if (!customJson.isNull("mykey")) {
myvalue = customJson.getString("mykey");
}
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}

// Demo更新界面展示代码,应用请在这里加入自己的处理逻辑
updateContent(context, messageString);
}


在对信息处理之后

进行updateContent 验证之后显示

private void updateContent(Context context, String content) {
Log.d(TAG, "updateContent");
String logText = "" + Utils.logStringCache;

if (!logText.equals("")) {
logText += "\n";
}

SimpleDateFormat sDateFormat = new SimpleDateFormat("HH-mm-ss");
logText += sDateFormat.format(new Date()) + ": ";
logText += content;

Utils.logStringCache = logText;

Log.d(TAG, "updateContent:"+logText);
//        Intent intent = new Intent();
//        intent.setClass(context.getApplicationContext(), PushDemoActivity.class);
//        intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
//        context.getApplicationContext().startActivity(intent);
}


/**

* 接收通知点击的函数。

*

* @param context

* 上下文

* @param title

* 推送的通知的标题

* @param description

* 推送的通知的描述

* @param customContentString

* 自定义内容,为空或者json字符串

*/

@Override

public void onNotificationClicked(Context context, String title,

String description, String customContentString) {

String notifyString = “通知点击 title=\”” + title + “\” description=\””

+ description + “\” customContent=” + customContentString;

Log.d(TAG, notifyString);

// 自定义内容获取方式,mykey和myvalue对应通知推送时自定义内容中设置的键和值
if (!TextUtils.isEmpty(customContentString)) {
JSONObject customJson = null;
try {
customJson = new JSONObject(customContentString);
String myvalue = null;
if (!customJson.isNull("mykey")) {
myvalue = customJson.getString("mykey");
}
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}

// Demo更新界面展示代码,应用请在这里加入自己的处理逻辑
updateContent(context, notifyString);

}


其他的一些常用方法可以在使用的API文档中查找。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: