work_weipa_百度云推送

2014-09-05 17:55 7人阅读 评论(0) 收藏 举报

问题:怎么实现消息推送?

回答:下载sdk,根据文档操作即可

资料:http://developer.baidu.com/wiki/index.php?title=docs/cplat/push/sdk/clientsdk看文档和sdk(客户端+服务端)

例子:

导包:

配置:

AndroidManifest.xml

    <?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.example.weipa"
android:versionCode=""
android:versionName="1.0" > <uses-sdk android:minSdkVersion="" android:targetSdkVersion=""/>
<!-- Push service 运行需要的权限 -->
<uses-permission android:name="android.permission.INTERNET"/>
<uses-permission android:name="android.permission.READ_PHONE_STATE" />
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
<uses-permission android:name="android.permission.RECEIVE_BOOT_COMPLETED" />
<uses-permission android:name="android.permission.WRITE_SETTINGS" />
<uses-permission android:name="android.permission.VIBRATE" />
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.ACCESS_DOWNLOAD_MANAGER"/>
<uses-permission android:name="android.permission.DOWNLOAD_WITHOUT_NOTIFICATION" />
<uses-permission android:name="android.permission.DISABLE_KEYGUARD" />
<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" />
<uses-permission android:name="android.permission.ACCESS_WIFI_STATE" /> <application android:name="com.baidu.push.example.DemoApplication"
android:icon="@drawable/ic_launcher"
android:label="@string/app_name">
<activity
android:name="com.baidu.push.example.PushDemoActivity"
android:launchMode="singleTask"
android:screenOrientation="portrait"
android:label="@string/app_name" >
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<activity
android:name="com.baidu.push.example.LoginActivity"
android:configChanges="orientation|keyboardHidden"
android:label="@string/login" >
</activity> <activity
android:name="com.baidu.push.example.CustomActivity"
android:launchMode="singleTask"
android:configChanges="orientation|keyboardHidden" >
</activity> <!-- push富媒体,不使用富媒体推送不需要 -->
<activity
android:name="com.baidu.android.pushservice.richmedia.MediaViewActivity"
android:configChanges="orientation|keyboardHidden"
android:label="MediaViewActivity" >
</activity>
<activity
android:name="com.baidu.android.pushservice.richmedia.MediaListActivity"
android:configChanges="orientation|keyboardHidden"
android:label="MediaListActivity"
android:launchMode="singleTask" >
</activity>
<!-- push富媒体结束 --> <!-- push应用定义消息receiver声明 -->
<receiver android:name="你的包名.MyPushMessageReceiver">
<intent-filter>
<!-- 接收push消息 -->
<action android:name="com.baidu.android.pushservice.action.MESSAGE" />
<!-- 接收bind,unbind,fetch,delete等反馈消息 -->
<action android:name="com.baidu.android.pushservice.action.RECEIVE" />
<action android:name="com.baidu.android.pushservice.action.notification.CLICK" />
</intent-filter>
</receiver> <!-- push必须的receviver和service声明 -->
<receiver android:name="com.baidu.android.pushservice.PushServiceReceiver"
android:process=":bdservice_v1">
<intent-filter>
<action android:name="android.intent.action.BOOT_COMPLETED" />
<action android:name="android.net.conn.CONNECTIVITY_CHANGE" />
<action android:name="com.baidu.android.pushservice.action.notification.SHOW" />
<action android:name="com.baidu.android.pushservice.action.media.CLICK" />
</intent-filter>
</receiver>
<receiver android:name="com.baidu.android.pushservice.RegistrationReceiver"
android:process=":bdservice_v1">
<intent-filter>
<action android:name="com.baidu.android.pushservice.action.METHOD" />
<action android:name="com.baidu.android.pushservice.action.BIND_SYNC" />
</intent-filter>
<intent-filter>
<action android:name="android.intent.action.PACKAGE_REMOVED"/>
<data android:scheme="package" />
</intent-filter>
</receiver>
<service
android:name="com.baidu.android.pushservice.PushService"
android:exported="true"
android:process=":bdservice_v1" >
<intent-filter>
<action android:name="com.baidu.android.pushservice.action.PUSH_SERVICE" />
</intent-filter>
</service>
<!-- push结束 --> <!-- 在百度开发者中心查询应用的API Key -->
<meta-data android:name="api_key" android:value="URzcY5unGHBQb8o8fLS1wGHu" />
</application> </manifest>
MyPushMessageReceiver.java
    import com.baidu.frontia.api.FrontiaPushMessageReceiver;  

    /**
* Push消息处理receiver。请编写您需要的回调函数, 一般来说: onBind是必须的,用来处理startWork返回值;
* onMessage用来接收透传消息; onSetTags、onDelTags、onListTags是tag相关操作的回调;
* onNotificationClicked在通知被点击时回调; onUnbind是stopWork接口的返回值回调
*
* 返回值中的errorCode,解释如下:
* 0 - Success
* 10001 - Network Problem
* 30600 - Internal Server Error
* 30601 - Method Not Allowed
* 30602 - Request Params Not Valid
* 30603 - Authentication Failed
* 30604 - Quota Use Up Payment Required
* 30605 - Data Required Not Found
* 30606 - Request Time Expires Timeout
* 30607 - Channel Token Timeout
* 30608 - Bind Relation Not Found
* 30609 - Bind Number Too Many
*
* 当您遇到以上返回错误时,如果解释不了您的问题,请用同一请求的返回值requestId和errorCode联系我们追查问题。
*
*/
public class MyPushMessageReceiver extends FrontiaPushMessageReceiver {
/** TAG to Log */
public static final String TAG = MyPushMessageReceiver.class
.getSimpleName(); /**
* 调用PushManager.startWork后,sdk将对push
* server发起绑定请求,这个过程是异步的。绑定请求的结果通过onBind返回。 如果您需要用单播推送,需要把这里获取的channel
* id和user id上传到应用server中,再调用server接口用channel id和user id给单个手机或者用户推送。
*
* @param context
* BroadcastReceiver的执行Context
* @param errorCode
* 绑定接口返回值,0 - 成功
* @param appid
* 应用id。errorCode非0时为null
* @param userId
* 应用user id。errorCode非0时为null
* @param channelId
* 应用channel id。errorCode非0时为null
* @param requestId
* 向服务端发起的请求id。在追查问题时有用;
* @return none
*/
@Override
public void onBind(Context context, int errorCode, String appid,
String userId, String channelId, String requestId) {
String responseString = "onBind errorCode=" + errorCode + " appid="
+ appid + " userId=" + userId + " channelId=" + channelId
+ " requestId=" + requestId;
Log.d(TAG, responseString); // 绑定成功,设置已绑定flag,可以有效的减少不必要的绑定请求
if (errorCode == ) {
Utils.setBind(context, true);
}
// Demo更新界面展示代码,应用请在这里加入自己的处理逻辑
updateContent(context, responseString);
} /**
* 接收透传消息的函数。
*
* @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);
} /**
* 接收通知点击的函数。注:推送通知被用户点击前,应用无法通过接口获取通知的内容。
*
* @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);
} /**
* setTags() 的回调函数。
*
* @param context
* 上下文
* @param errorCode
* 错误码。0表示某些tag已经设置成功;非0表示所有tag的设置均失败。
* @param successTags
* 设置成功的tag
* @param failTags
* 设置失败的tag
* @param requestId
* 分配给对云推送的请求的id
*/
@Override
public void onSetTags(Context context, int errorCode,
List<String> sucessTags, List<String> failTags, String requestId) {
String responseString = "onSetTags errorCode=" + errorCode
+ " sucessTags=" + sucessTags + " failTags=" + failTags
+ " requestId=" + requestId;
Log.d(TAG, responseString); // Demo更新界面展示代码,应用请在这里加入自己的处理逻辑
updateContent(context, responseString);
} /**
* delTags() 的回调函数。
*
* @param context
* 上下文
* @param errorCode
* 错误码。0表示某些tag已经删除成功;非0表示所有tag均删除失败。
* @param successTags
* 成功删除的tag
* @param failTags
* 删除失败的tag
* @param requestId
* 分配给对云推送的请求的id
*/
@Override
public void onDelTags(Context context, int errorCode,
List<String> sucessTags, List<String> failTags, String requestId) {
String responseString = "onDelTags errorCode=" + errorCode
+ " sucessTags=" + sucessTags + " failTags=" + failTags
+ " requestId=" + requestId;
Log.d(TAG, responseString); // Demo更新界面展示代码,应用请在这里加入自己的处理逻辑
updateContent(context, responseString);
} /**
* listTags() 的回调函数。
*
* @param context
* 上下文
* @param errorCode
* 错误码。0表示列举tag成功;非0表示失败。
* @param tags
* 当前应用设置的所有tag。
* @param requestId
* 分配给对云推送的请求的id
*/
@Override
public void onListTags(Context context, int errorCode, List<String> tags,
String requestId) {
String responseString = "onListTags errorCode=" + errorCode + " tags="
+ tags;
Log.d(TAG, responseString); // Demo更新界面展示代码,应用请在这里加入自己的处理逻辑
updateContent(context, responseString);
} /**
* PushManager.stopWork() 的回调函数。
*
* @param context
* 上下文
* @param errorCode
* 错误码。0表示从云推送解绑定成功;非0表示失败。
* @param requestId
* 分配给对云推送的请求的id
*/
@Override
public void onUnbind(Context context, int errorCode, String requestId) {
String responseString = "onUnbind errorCode=" + errorCode
+ " requestId = " + requestId;
Log.d(TAG, responseString); // 解绑定成功,设置未绑定flag,
if (errorCode == ) {
Utils.setBind(context, false);
}
// Demo更新界面展示代码,应用请在这里加入自己的处理逻辑
updateContent(context, responseString);
} 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; // Intent intent = new Intent();
// intent.setClass(context.getApplicationContext(), MainActivity.class);
// intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
// context.getApplicationContext().startActivity(intent);
} }

Utils.java

public class Utils {
public static final String TAG = "PushDemoActivity";
public static final String RESPONSE_METHOD = "method";
public static final String RESPONSE_CONTENT = "content";
public static final String RESPONSE_ERRCODE = "errcode";
protected static final String ACTION_LOGIN = "com.baidu.pushdemo.action.LOGIN";
public static final String ACTION_MESSAGE = "com.baiud.pushdemo.action.MESSAGE";
public static final String ACTION_RESPONSE = "bccsclient.action.RESPONSE";
public static final String ACTION_SHOW_MESSAGE = "bccsclient.action.SHOW_MESSAGE";
protected static final String EXTRA_ACCESS_TOKEN = "access_token";
public static final String EXTRA_MESSAGE = "message"; public static String logStringCache = ""; // 获取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) { }
return apiKey;
} // 用share preference来实现是否绑定的开关。在ionBind且成功时设置true,unBind且成功时设置false
public static boolean hasBind(Context context) {
SharedPreferences sp = PreferenceManager
.getDefaultSharedPreferences(context);
String flag = sp.getString("bind_flag", "");
if ("ok".equalsIgnoreCase(flag)) {
return true;
}
return false;
} public static void setBind(Context context, boolean flag) {
String flagStr = "not";
if (flag) {
flagStr = "ok";
}
SharedPreferences sp = PreferenceManager
.getDefaultSharedPreferences(context);
Editor editor = sp.edit();
editor.putString("bind_flag", flagStr);
editor.commit();
} public static List<String> getTagsList(String originalText) {
if (originalText == null || originalText.equals("")) {
return null;
}
List<String> tags = new ArrayList<String>();
int indexOfComma = originalText.indexOf(',');
String tag;
while (indexOfComma != -) {
tag = originalText.substring(, indexOfComma);
tags.add(tag); originalText = originalText.substring(indexOfComma + );
indexOfComma = originalText.indexOf(',');
} tags.add(originalText);
return tags;
} public static String getLogText(Context context) {
SharedPreferences sp = PreferenceManager
.getDefaultSharedPreferences(context);
return sp.getString("log_text", "");
} public static void setLogText(Context context, String text) {
SharedPreferences sp = PreferenceManager
.getDefaultSharedPreferences(context);
Editor editor = sp.edit();
editor.putString("log_text", text);
editor.commit();
} }

MainActivity.java

        PushManager.startWork(getApplicationContext(),
PushConstants.LOGIN_TYPE_API_KEY,
"URzcY5unGHBQb8o8fLS1wGHu");

Utils 工具 推送的更多相关文章

  1. SEO优化:WordPress发布文章主动推送到百度,加快收录保护原创

    工作实在太忙,也没时间打理网站.最近公司额外交待了一些网站 SEO 方面的优化任务让我关注(这就是啥都要会.啥都要做的苦逼运维的真实写照了...). 于是抽空看了下百度站长平台,至少看到了2个新消息: ...

  2. delphi xe 10.3 利用Git组群开发,Git服务器安装,Git 拉取,提交,推送相关设置操作

    1. Git服务器安装, 参考 https://blog.csdn.net/u012842630/article/details/97175397 Git服务器官方网站,要FQ. 2. 工具软件 gi ...

  3. 【开源一个小工具】一键将网页内容推送到Kindle

    最近工作上稍微闲点,这一周利用下班时间写了一个小工具,其实功能挺简单但也小折腾了会. 工具名称:Simple Send to Kindle Github地址:https://github.com/zh ...

  4. 自动化运维工具ansible学习+使用ansible批量推送公钥到远程主机

    目录: 一.ansible简介 1.1.ansible是什么 1.2.ansible如何工作 1.3.ansible优缺点 1.4.ansible安装方式 1.5.ansible文件简单介绍 1.6. ...

  5. cos migration工具webhook推送

    上一篇讲了腾讯云同步工具的使用,这篇主要是补充如何将同步结果主动消息通知. 因为cos migration 工具是java语言,并在github开源的,所以可以直接修改源码,添加webhook推送代码 ...

  6. Pusher 消息推送测试工具

    1.Pusher 简介 Pusher 是一款为 iOS.Mac App 提供推送测试的小工具. 其它下载地址 Pusher v0.7.3 for Mac,密码:p19i. 2.使用方法 使用方法简介 ...

  7. Easy APNs Provider 消息推送测试工具

    1.Easy APNs Provider 简介 Easy APNs Provider 是一款为 iOS.Mac App 提供推送测试的小工具. App Store 下载地址 Easy APNs Pro ...

  8. 【PM面试题】设计一个股价推送工具

    这一轮面试时间比较短,问题在短时间内不能很全面展开,因此抓住一些关键点变得尤其重要,这里我记录下当时是怎么想这个问题的. 问题解析 子问题1:推送什么?从问题中看出我们需要推送的是股价,用户可以自定义 ...

  9. 采集电脑摄像头和mic,rtp端口推送音视频工具

    介绍:这个是我在做一个rtmp播放的项目中自己写的rtp推送的工具,可选择摄像头,可选择推送rtp的端口和ip 下载地址: github:https://github.com/alexhegang/s ...

随机推荐

  1. html 任意表格

    <!DOCTYPE html><html>    <head>        <meta charset="utf-8" />   ...

  2. hdu_5705_Clock("巴卡斯杯" 中国大学生程序设计竞赛 - 女生专场)

    题目连接:http://acm.hdu.edu.cn/showproblem.php?pid=5705 题意:给你一个时间和一个角度,问你下一个时针和分针形成给出的角度是什么时候 题解:我们可以将这个 ...

  3. android网络开发之测试机连接到服务器上面

    1:本人使用Tomcat作为服务器软件,首先打开Tomcat.(可以在浏览器中输入http://www.127.0.0.1:8080/查看) 2:服务器后台使用Servelt开发,这里不再讲解. 3: ...

  4. 【Python爬虫实战--1】深入理解urllib;urllib2;requests

    摘自:http://1oscar.github.io/blog/2015/07/05/%E6%B7%B1%E5%85%A5%E7%90%86%E8%A7%A3urllib;urllib2;reques ...

  5. karma+jasmine自动化测试

    1.安装nodejs,进入项目目录 2.安装karma和相关插件 npm install karma --save-dev npm install karma-jasmine karma-chrome ...

  6. login/logout切换

    1. 前端按钮 <img border="0" width="18" height="18" src="<%=base ...

  7. groupbox 下的datagridview的列标题字体修改混乱

        groupbox 下的datagridview的列标题字体修改混乱

  8. Git 版本管理基本操作

    Git是一个版本管理操作的工具 非常N,可以很智能的分布式管理, 本网站学习笔记 来自于廖雪峰老师的内容借鉴 安装 yum -y install git 本地设置全局 告知是谁提交代码 信息 # gi ...

  9. UITextfield的一些属性

    //设置左视图 不用设置frame UIImageView *imageV = [[UIImageView alloc] initWithImage:[UIImage imageNamed:@&quo ...

  10. 报错 BeanFactory not initialized or already closed - call 'refresh' before accessing beans via the ApplicationContext 的解决方法

    这个普遍是因为tomcat 的 jar包问题,重新导入一下tomcat的jar包就OK了.