频道栏目
首页 > 资讯 > 其他综合 > 正文

百度云推送消息(范例)

15-09-24        来源:[db:作者]  
收藏   我要投稿

百度云推送 然后导入所需要的权限jar包so包等eclipse可全部放在lib下然而Android Studio则需要在srcmain下创建一个jniLibs文件夹来存放所有的so包 设置完后创建一个主类 在创建一个接收类拷贝百度Demo中的代码 注意public void onNotificationClicked下的代码其中customJson new JSONObjectcustomContentString这一段代码这段代码中的JSONObject是根据在推送消息下的高级设置下添加字段得到的JSONObject的到的Value的值 数据统计所用类 辅助类 配置类 然后就可以在网页推送消息了

百度云推送

首先进入
 百度云首页,然后根据文档进行设置,

然后导入所需要的权限,jar包,so包等,eclipse可全部放在lib下,然而Android Studio则需要在src/main/下创建一个jniLibs文件夹来存放所有的so包

设置完后,创建一个主类

package com.test.mypush;

import android.support.v7.app.ActionBarActivity;

import com.baidu.android.pushservice.PushConstants;
import com.baidu.android.pushservice.PushManager;

import android.app.Activity;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;

public class MainActivity extends BaseActivity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        PushManager.startWork(getApplicationContext(),PushConstants.LOGIN_TYPE_API_KEY,ZCzREkMaQIXifUqtuXkL1hgN);
    }


}

在创建一个接收类(拷贝百度Demo中的代码)

注意public void onNotificationClicked下的代码,其中customJson = new JSONObject(customContentString);这一段代码,这段代码中的JSONObject是根据在推送消息下的高级设置下,添加字段得到的JSONObject的到的Value的值


package com.test.mypush;

import java.util.List;

import com.baidu.android.pushservice.PushMessageReceiver;

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;

import org.json.JSONException;
import org.json.JSONObject;

import android.content.Context;
import android.content.Intent;
import android.text.TextUtils;
import android.util.Log;
import android.widget.Toast;

import com.baidu.android.pushservice.PushMessageReceiver;

/*
 * Push消息处理receiver。请编写您需要的回调函数, 一般来说: onBind是必须的,用来处理startWork返回值;
 *onMessage用来接收透传消息; onSetTags、onDelTags、onListTags是tag相关操作的回调;
 *onNotificationClicked在通知被点击时回调; onUnbind是stopWork接口的返回值回调

 * 返回值中的errorCode,解释如下:
 *0 - Success
 *10001 - Network Problem
 *10101  Integrate Check Error
 *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 PushMsg extends PushMessageReceiver {
    /** TAG to Log */


    /**
     * 调用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);

        if (errorCode == 0) {
            // 绑定成功
        }
        // 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) {
            Toast.makeText(context, 123+title+description, Toast.LENGTH_SHORT);
            try {
                JSONObject obj=new JSONObject(customContentString);
                String classname=obj.getString(startActivity);
                Intent intent=new Intent(context,Class.forName(context.getPackageName()+.+classname));
                intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
                context.startActivity(intent);

            } catch (JSONException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            } catch (ClassNotFoundException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }

//        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);
    }

    /**
     * 接收通知到达的函数。
     *
     * @param context
     *            上下文
     * @param title
     *            推送的通知的标题
     * @param description
     *            推送的通知的描述
     * @param customContentString
     *            自定义内容,为空或者json字符串
     */

    @Override
    public void onNotificationArrived(Context context, String title,
            String description, String customContentString) {

        String notifyString = onNotificationArrived  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更新界面展示代码,应用请在这里加入自己的处理逻辑
        // 你可以參考 onNotificationClicked中的提示从自定义内容获取具体值
        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 sucessTags, List 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 sucessTags, List 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 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);

        if (errorCode == 0) {
            // 解绑定成功
        }
        // Demo更新界面展示代码,应用请在这里加入自己的处理逻辑
        updateContent(context, responseString);
    }

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

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

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

        Utils.logStringCache = logText;


    }

}

数据统计所用类

package com.test.mypush;

import com.baidu.mobstat.StatService;

import android.app.Activity;

public class BaseActivity extends Activity{
    @Override
    protected void onPause() {
        // TODO Auto-generated method stub
        super.onPause();
        StatService.onPause(this);
    }
    @Override
    protected void onResume() {
        // TODO Auto-generated method stub
        super.onResume();
        StatService.onResume(this);
    }
}

辅助类

package com.test.mypush;

import java.util.ArrayList;
import java.util.List;

import android.content.Context;
import android.content.SharedPreferences;
import android.content.SharedPreferences.Editor;
import android.content.pm.ApplicationInfo;
import android.content.pm.PackageManager;
import android.content.pm.PackageManager.NameNotFoundException;
import android.os.Bundle;
import android.preference.PreferenceManager;

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;
    }

    public static List getTagsList(String originalText) {
        if (originalText == null || originalText.equals()) {
            return null;
        }
        List tags = new ArrayList();
        int indexOfComma = originalText.indexOf(',');
        String tag;
        while (indexOfComma != -1) {
            tag = originalText.substring(0, indexOfComma);
            tags.add(tag);

            originalText = originalText.substring(indexOfComma + 1);
            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();
    }

}

配置类




    
   

然后就可以在网页推送消息了

 

相关TAG标签
上一篇:C++中类的构造函数调用顺序
下一篇:GDAL库扩展Landsat系列MTL文件格式支持
相关文章
图文推荐

关于我们 | 联系我们 | 广告服务 | 投资合作 | 版权申明 | 在线帮助 | 网站地图 | 作品发布 | Vip技术培训 | 举报中心

版权所有: 红黑联盟--致力于做实用的IT技术学习网站