前两天开始搞phonegap与百度云推送的集成插件,之前没搞过移动端,哎做的时候被坑了好久,说多了都是泪啊,为了其他小伙伴不再被坑特意共享出来,废话不多说了直接开始做插件开发吧

第一步在集成phonegap的安卓项目src下创建com.cmpsoft.mobile.plugin.pushnotification包,紧接着拷贝以下代码

package com.cmpsoft.mobile.plugin.pushnotification;

 import oa.mobile.MyPushMessageReceiver;
 import oa.mobile.OA;
 import oa.mobile.OAApplication;

 import org.apache.cordova.CallbackContext;
 import org.apache.cordova.CordovaPlugin;
 import org.apache.cordova.PluginResult;
 import org.json.JSONArray;
 import org.json.JSONException;
 import org.json.JSONObject;

 import android.app.AlertDialog;
 import android.app.Dialog;
 import android.content.BroadcastReceiver;
 import android.content.Context;
 import android.content.Intent;
 import android.content.IntentFilter;
 import android.content.SharedPreferences;
 import android.content.SharedPreferences.Editor;
 import android.content.res.Resources;
 import android.preference.PreferenceManager;
 import android.widget.TextView;
 import android.widget.Toast;

 import com.baidu.android.common.logging.Log;
 import com.baidu.android.pushservice.PushConstants;
 import com.baidu.android.pushservice.PushManager;

 public class PushNotification extends CordovaPlugin
 {
     private BroadcastReceiver receiver = null;
     private CallbackContext pushCallbackContext = null;
     
     public static final String ACTION_RESPONSE = "bccsclient.action.RESPONSE";
     public static final String RESPONSE_METHOD = "method";
     public static final String RESPONSE_CONTENT = "content";
     public static final String RESPONSE_ERRCODE = "errcode";
     
     public boolean execute(String action, JSONArray args, CallbackContext callbackContext) throws JSONException
     {
         if(action.equals("init"))
         {
             
             this.pushCallbackContext = callbackContext;
             super.initialize(cordova, webView);
             IntentFilter intentFilter = new IntentFilter();
             intentFilter.addAction(PushConstants.ACTION_RECEIVE);
             intentFilter.addAction(PushConstants.ACTION_RECEIVE);
             intentFilter.addAction(PushConstants.ACTION_MESSAGE);
             intentFilter.addAction(PushConstants.ACTION_RECEIVER_NOTIFICATION_CLICK);
             if (this.receiver == null)
             {
                 this.receiver = new MyPushMessageReceiver()
                 {
                     @Override
                     public void onReceive(Context context, Intent intent)
                     {
                         if (intent.getAction().equals(PushConstants.ACTION_RECEIVE))
                         {
                             //处理绑定等方法的返回数据
                             //PushManager.startWork()的返回值通过 PushConstants.METHOD_BIND得到
                             //获取方法
                             final String method = intent.getStringExtra(PushConstants.EXTRA_METHOD);
                             //方法返回错误码。若绑定返回错误(非 0),则应用将不能正常接收消息。
                             //绑定失败的原因有多种,如网络原因,或 access token 过期。
                             //请不要在出错时进行简单的 startWork 调用,这有可能导致死循环。
                             //可以通过限制重试次数,或者在其他时机重新调用来解决。
                             int errorCode = intent.getIntExtra(PushConstants.EXTRA_ERROR_CODE,PushConstants.ERROR_SUCCESS);
                             String content = "";
                             if (intent.getByteArrayExtra(PushConstants.EXTRA_CONTENT) != null) {
                                 //返回内容
                                 content = new String(intent.getByteArrayExtra(PushConstants.EXTRA_CONTENT));
                             }
                             try {  
                                 JSONObject jsonContent = new JSONObject(content);
                                 JSONObject params = jsonContent
                                         .getJSONObject("response_params");
                                 String appid = params.getString("appid");
                                 String channelid = params.getString("channel_id");
                                 String userid = params.getString("user_id");
                                 OAApplication.appId = appid;
                                 OAApplication.channelId = channelid;
                                 OAApplication.userId = userid;
                                 JSONObject r = new JSONObject();
                                 r.put("appId",OAApplication.appId);
                                 r.put("channelId",OAApplication.channelId);
                                 r.put("userId", OAApplication.userId);
                                 pushCallbackContext.success(r);
                             } catch (JSONException e) {  
                                 // TODO Auto-generated catch block  
                                 e.printStackTrace();  
                             }  
                         }else if (intent.getAction().equals(
                                 PushConstants.ACTION_RECEIVER_NOTIFICATION_CLICK)) {
 //                            Log.d(TAG, "intent=" + intent.toUri(0));
                             String title = intent.getStringExtra(PushConstants.EXTRA_NOTIFICATION_TITLE);
                             String content = intent.getStringExtra(PushConstants.EXTRA_NOTIFICATION_CONTENT);
 //                            String customString = intent.getStringExtra()
 //                            webView.loadUrl("http://www.baidu.com");
                             String customString = intent.getStringExtra(PushConstants.EXTRA_EXTRA);
                             JSONObject customJson = null;  
                             try {  
                                 customJson = new JSONObject(customString);  
                                 String myvalue = null; 
                                 myvalue = customJson.getString("messageId"); 
                                 String messageId = myvalue;
                                 OAApplication.messageId=messageId;
                                 //webView.loadUrl("javascript:MPDL.util.Func.fetch_Notice_single("+messageId+")");
                                 Intent intentView = new Intent();  
                                 intentView.setClass(context.getApplicationContext(), OA.class);
                                 intentView.setAction(Intent.ACTION_MAIN);
                                 intentView.addCategory(Intent.CATEGORY_LAUNCHER);  
                                 intentView.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK| Intent.FLAG_ACTIVITY_RESET_TASK_IF_NEEDED);  
                                 context.getApplicationContext().startActivity(intentView);  
                             } catch (JSONException e) {  
                                 // TODO Auto-generated catch block  
                                 e.printStackTrace();  
                             }  
                              
 //                             
                             
                         }
                     }
                 };
                 cordova.getActivity().registerReceiver(this.receiver, intentFilter);
             }

             PluginResult pluginResult = new PluginResult(PluginResult.Status.NO_RESULT);
             pluginResult.setKeepCallback(true);
             callbackContext.sendPluginResult(pluginResult);
             PushManager.startWork(cordova.getActivity().getApplicationContext(), 0, args.getString(0));
             return true;
         }else if (action.equals("getInfo")) {
             JSONObject r = new JSONObject();
             SharedPreferences sp = PreferenceManager
                     .getDefaultSharedPreferences(cordova.getActivity());
             //appId = sp.getString("appid", "");
             /*channelId = sp.getString("channel_id", "");
             clientId = sp.getString("user_id", "");*/    
             r.put("appId", sp.getString("appid", ""));
             r.put("channelId",sp.getString("channel_id", ""));
             r.put("clientId", sp.getString("user_id", ""));
             callbackContext.success(r);
             return true;
         }
         return false;
     }
     
     private void sendPushInfo(Context context, Intent intent)
     {
         String content = "";
         JSONObject info = null;
         if (intent.getByteArrayExtra(PushConstants.EXTRA_CONTENT) != null)
         {
             content = new String(intent.getByteArrayExtra(PushConstants.EXTRA_CONTENT));
             try
             {
                 info = (JSONObject)new JSONObject(content).get("response_params");
                 info.put("deviceType", 3);
             }
             catch (JSONException e)
             {
                 e.printStackTrace();
             }
         }
         if (this.pushCallbackContext != null) 
         {
             PluginResult result = new PluginResult(PluginResult.Status.OK, info);
             result.setKeepCallback(false);
             this.pushCallbackContext.sendPluginResult(result);
         }
         if (this.receiver != null) {
             try {
                 this.cordova.getActivity().unregisterReceiver(this.receiver);
                 this.receiver = null;
             } catch (Exception e) {
                 //
             }
         }
     }
     /**
      * 处理Intent
      * 
      * @param intent
      *            intent
      */
     private void handleIntent(Intent intent) {
         String action = intent.getAction();

         if (ACTION_RESPONSE.equals(action)) {

             String method = intent.getStringExtra(RESPONSE_METHOD);

             if (PushConstants.METHOD_BIND.equals(method)) {
                 String toastStr = "";
                 int errorCode = intent.getIntExtra(RESPONSE_ERRCODE, 0);
                 if (errorCode == 0) {
                     String content = intent
                             .getStringExtra(RESPONSE_CONTENT);
                     String appid = "";
                     String channelid = "";
                     String userid = "";

                     try {
                         JSONObject jsonContent = new JSONObject(content);
                         JSONObject params = jsonContent
                                 .getJSONObject("response_params");
                         appid = params.getString("appid");
                         channelid = params.getString("channel_id");
                         userid = params.getString("user_id");
                     } catch (JSONException e) {
                         
                     }

                     SharedPreferences sp = PreferenceManager
                             .getDefaultSharedPreferences(cordova.getActivity());
                     Editor editor = sp.edit();
                     editor.putString("appid", appid);
                     editor.putString("channel_id", channelid);
                     editor.putString("user_id", userid);
                     editor.commit();

                     toastStr = "Bind Success";
                 } else {
                     toastStr = "Bind Fail, Error Code: " + errorCode;
                     if (errorCode == 30607) {
                         Log.d("Bind Fail", "update channel token-----!");
                     }
                 }
             }
         } 
     }
 }

第二步开始拷贝js 在plugins文件夹下创建com.cmpsoft.mobile.plugin.pushnotification包,然后在该包下创建www包,在www包下拷贝PushNotification.js

cordova.define("com.cmpsoft.mobile.plugin.pushnotification.FGPushNotification", function(require, exports, module) {
 var argscheck = require('cordova/argscheck'),
     cordova = require('cordova'),
     exec = require('cordova/exec');

 var FGPushNotification = function() {
     this.registered = false;
     //
     this.appId = null;
     this.channelId = null;
     this.clientId = null;
     
     var me = this;

      me.getInfo(function(info) {
             me.appId = info.appId;
             me.channelId = info.channelId;
             me.clientId = info.clientId;
         });
     
 };
 FGPushNotification.prototype.init = function(api_key)
 {
     exec(fastgoPushNotification.successFn, fastgoPushNotification.failureFn, 'FGPushNotification', 'init', [api_key]);
 };

 FGPushNotification.prototype.successFn = function(info)
 {
     if(info){
         fastgoPushNotification.registered = true;
         cordova.fireDocumentEvent("cloudPushRegistered", info);
     }
 };

 FGPushNotification.prototype.failureFn = function(info)
 {
     fastgoPushNotification.registered = false;
 };

 FGPushNotification.prototype.getInfo = function(successCallback, errorCallback) {
     argscheck.checkArgs('fF', 'FGPushNotification.getInfo', arguments);
     exec(successCallback, errorCallback, "FGPushNotification", "getInfo", []);
 };
 var fastgoPushNotification = new FGPushNotification();

 module.exports = fastgoPushNotification;});


第三步开始进行配置操作了,强两步我们已经把所需要的插件都拷贝好了下面开始配置

1)找到res下面的xml目录下面有个config.xml配置文件,打开添加以下代码

<feature name="FGPushNotification">
         <param name="android-package" value="com.cmpsoft.mobile.plugin.pushnotification.PushNotification" />
     </feature> 2)在www文件夹下找到cordova_plugins.js,打开添加以下代码
 {
         "file": "plugins/com.cmpsoft.mobile.plugin.pushnotification/www/PushNotification.js",
         "id": "com.cmpsoft.mobile.plugin.pushnotification.FGPushNotification",
         "clobbers": [
             "fastgoPushNotification"
         ]
     }, module.exports.metadata = 
 // TOP OF METADATA
 {
     
     "com.cmpsoft.mobile.plugin.pushnotification": "1.0.0" }

第四部就可以直接开始调用了

找到自己的index.html,找到ondeviceready方法拷贝以下代码

需要先在百度云推送中注册服务端,获取apikey

fastgoPushNotification.init("你的API KEY");
     //推送返回appID
     document.addEventListener("cloudPushRegistered", function(info){
         console.log(info);
          
         }

     }, false);

-------info信息中保存的是和百度云绑定后返回的信息

好了以上操作已完成phonegap与百度云推送的集成,已经可以推送消息了

(假如你需要实现在通知栏收到的推送消息单击后单独跳转的话请继续往下看)

找到你的MainActivyty的那个目录在其目录下创建MyPushMessageReceiver类

package oa.mobile;

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

 import android.content.BroadcastReceiver;
 import android.content.Context;
 import android.content.Intent;

 import com.baidu.android.common.logging.Log;
 import com.baidu.android.pushservice.PushConstants;

 public class MyPushMessageReceiver extends BroadcastReceiver {
     /** TAG to Log */
     public static final String TAG = MyPushMessageReceiver.class.getSimpleName();

     /**
      * @param context
      *            Context
      * @param intent
      *            接收的 intent
      */
     @Override
     public void onReceive(final Context context, Intent intent) {
         Log.d(TAG, ">>> Receive intent: \r\n" + intent);
         if (intent.getAction().equals(
             PushConstants.ACTION_RECEIVER_NOTIFICATION_CLICK)) {
 //            Log.d(TAG, "intent=" + intent.toUri(0));
             String title = intent.getStringExtra(PushConstants.EXTRA_NOTIFICATION_TITLE);
             String content = intent.getStringExtra(PushConstants.EXTRA_NOTIFICATION_CONTENT);
 //            String customString = intent.getStringExtra()
 //            webView.loadUrl("http://www.baidu.com");
             String customString = intent.getStringExtra(PushConstants.EXTRA_EXTRA);
             JSONObject customJson = null;  
             try {  
                 customJson = new JSONObject(customString);  
                 String myvalue = null; 
                 myvalue = customJson.getString("messageId"); 
                 String messageId = myvalue;
                 OAApplication.messageId=messageId;
                 //webView.loadUrl("javascript:MPDL.util.Func.fetch_Notice_single("+messageId+")");
                 Intent intentView = new Intent();  
                 intentView.setClass(context.getApplicationContext(), OA.class);
                 intentView.setAction(Intent.ACTION_MAIN);
                 intentView.addCategory(Intent.CATEGORY_LAUNCHER);  
                 intentView.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK| Intent.FLAG_ACTIVITY_RESET_TASK_IF_NEEDED);  
                 context.getApplicationContext().startActivity(intentView);  
             } catch (JSONException e) {  
                 // TODO Auto-generated catch block  
                 e.printStackTrace();  
             }  
              
 //             
             
         }
     }
 }

然后在AndroidManifest.xml里面添加代码

<?xml version='1.0' encoding='utf-8'?>
 <manifest android:hardwareAccelerated="true" android:versionCode="2" android:versionName="1.2.1" android:windowSoftInputMode="adjustPan" package="oa.mobile" xmlns:android="http://schemas.android.com/apk/res/android">
     <supports-screens android:anyDensity="true" android:largeScreens="true" android:normalScreens="true" android:resizeable="true" android:smallScreens="true" android:xlargeScreens="true" />
     <uses-permission android:name="android.permission.INTERNET" />
     <application android:debuggable="true" android:hardwareAccelerated="true" android:icon="@drawable/ic_launcher" android:label="@string/app_name">
         <activity android:configChanges="orientation|keyboardHidden|keyboard|screenSize|locale" android:label="@string/app_name" android:name="OA" android:theme="@android:style/Theme.Black.NoTitleBar" android:launchMode="singleTask">
             <intent-filter>
                 <action android:name="android.intent.action.MAIN" />
                 <category android:name="android.intent.category.LAUNCHER" />
             </intent-filter>
         </activity>
         <activity android:clearTaskOnLaunch="true" android:configChanges="orientation|keyboardHidden" android:exported="false" android:name="com.google.zxing.client.android.CaptureActivity" android:screenOrientation="portrait" android:theme="@android:style/Theme.NoTitleBar.Fullscreen" android:windowSoftInputMode="stateAlwaysHidden">
             <intent-filter>
                 <action android:name="com.phonegap.plugins.barcodescanner.SCAN" />
                 <category android:name="android.intent.category.DEFAULT" />
             </intent-filter>
         </activity>
         <activity android:label="@string/share_name" android:name="com.google.zxing.client.android.encode.EncodeActivity">
             <intent-filter>
                 <action android:name="com.phonegap.plugins.barcodescanner.ENCODE" />
                 <category android:name="android.intent.category.DEFAULT" />
             </intent-filter>
         </activity>
         <activity android:label="@string/share_name" android:name="com.google.zxing.client.android.HelpActivity">
             <intent-filter>
                 <action android:name="android.intent.action.VIEW" />
                 <category android:name="android.intent.category.DEFAULT" />
             </intent-filter>
         </activity>
         <!-- push应用定义消息receiver声明 -->
        <receiver android:name="oa.mobile.MyPushMessageReceiver">  在这里改成你目录下的该类
             <intent-filter>
                 <action android:name="com.baidu.android.pushservice.action.notification.CLICK" />
             </intent-filter>
         </receiver>
         <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:exported="true" android:name="com.baidu.android.pushservice.PushService" android:process=":bdservice_v1" />
         <meta-data android:name="api_key" android:value="M7hhVSAfmW4EooeNboUur5ZN"/>        
     </application>
     <uses-sdk android:minSdkVersion="8" android:targetSdkVersion="19" />
     <uses-permission android:name="android.permission.READ_PHONE_STATE" />
     <uses-permission android:name="android.permission.RECEIVE_BOOT_COMPLETED" />
     <uses-permission android:name="android.permission.WRITE_SETTINGS" />
     <uses-permission android:name="android.permission.DISABLE_KEYGUARD" />
     <uses-permission android:name="android.permission.ACCESS_WIFI_STATE" />
     <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
     <uses-permission android:name="android.permission.READ_CONTACTS" />
     <uses-permission android:name="android.permission.WRITE_CONTACTS" />
     <uses-permission android:name="android.permission.GET_ACCOUNTS" />
     <uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" />
     <uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
     <uses-permission android:name="android.permission.RECORD_AUDIO" />
     <uses-permission android:name="android.permission.MODIFY_AUDIO_SETTINGS" />
     <uses-permission android:name="android.permission.RECORD_VIDEO" />
     <uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
     <uses-permission android:name="android.permission.VIBRATE" />
     <uses-permission android:name="android.permission.CAMERA" />
     <uses-permission android:name="android.permission.FLASHLIGHT" />
    <uses-permission android:name="android.permission.MOUNT_UNMOUNT_FILESYSTEMS"/>
    <uses-permission android:name="android.permission.INSTALL_PACKAGES"/>
     <uses-feature android:name="android.hardware.camera" android:required="false" />
 </manifest>


以上修改完毕后,在你的MainActivity方法里注册onstart方法

@Override  
     protected void onStart() {  
         // TODO Auto-generated method stub 
         super.onStart(); 
         Intent intent = this.getIntent();
         if(intent==null){
             return;
         }else{
             if(!OAApplication.messageId.equals("")){
                 
                 final Thread t = new Thread() {
                     public void run() {
                         try {
                                 sleep(1000);
                                 String messageId = OAApplication.messageId;
                                 sendJavascript("MPDL.util.Func.fetch_Notice_single("+messageId+")");
                                 OAApplication.messageId = "";
                         } catch (Exception e) {
                             e.printStackTrace();
                         }
                     }
                 };
                 t.start();
             } 
         }
         
     }


以上配置完成后基本上可以使用了