Android极光推送实际开发流程

说明:在web端操作数据,手机端需要获得通知,提示用户打开系统。

思路:将web端的操作数据推送给手机,这里使用极光推送API来实现。(Android版)

准备1:android开发eclipse工具、环境、设备等

准备2:注册极光推送账号、创建应用名称,获取AppKey

准备3:下载Android example调测推送实例

https://www.jpush.cn/common/apps

Android极光推送实际开发流程

web端,触发代码(APPkey 请用实际申请的值)

可参考下列地址

http://docs.jpush.cn/pages/viewpage.action?pageId=3309727

package com.proem.test;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.net.URL;
import java.net.URLConnection;
import java.security.MessageDigest;
import java.util.Random;

import com.proem.util.StringUtil;

public class Tuisong {

	private static String ApiKey = "您的ApiKey ";
	private static String APIMasterSecret = "APIMasterSecret";

	public static void TestPost(String RegistrationID) throws IOException {  
        
        URL url = new URL("http://api.jpush.cn:8800/v2/push");  
        URLConnection connection = url.openConnection();  
        connection.setDoOutput(true);  
        OutputStreamWriter out = new OutputStreamWriter(connection.getOutputStream(), "UTF-8");  
        
        String put = PushAndroid(RegistrationID);
        out.write(put); // 向页面传递数据。post的关键所在!  
        out.flush();  
        out.close();  
        // 一旦发送成功,用以下方法就可以得到服务器的回应:  
        String sCurrentLine;  
        String sTotalString;  
        sCurrentLine = "";  
        sTotalString = "";  
        InputStream l_urlStream;  
        l_urlStream = connection.getInputStream();  
        // 传说中的三层包装阿!  
        BufferedReader l_reader = new BufferedReader(new InputStreamReader(  
                l_urlStream));  
        while ((sCurrentLine = l_reader.readLine()) != null) {  
            sTotalString += sCurrentLine + "\r\n";  
        }  
        System.out.println(sTotalString);  
          
    }  
  
    public static void main(String[] args) throws IOException {  
//        TestPost("58");  
    }  
	
	
	/// <summary>
    /// Android极光推送
    /// </summary>
    /// <param name="RegistrationID">设备号</param>
    // RegistrationID 手机端注册上来的 ID(用户id)只发送指定用户
    public static String PushAndroid(String RegistrationID)
    {
    	String postData="";
        try
        {
            Random ran = new Random();
            int sendno = ran.nextInt(2100000000);//随机生成的一个编号
            String app_key = ApiKey;
            String masterSecret = APIMasterSecret;
            int receiver_type = 3;//接收者类型。2、指定的 tag。3、指定的 alias。4、广播:对 app_key 下的所有用户推送消息。5、根据 RegistrationID 进行推送。当前只是 Android SDK r1.6.0 版本支持
            String receiver_value = RegistrationID;
            int msg_type = 1;//1、通知2、自定义消息(只有 Android 支持)
            String msg_content = "{\"n_builder_id\":\"00\",\"n_title\":\"" + "来自11的通知消息" + "\",\"n_content\":\"" + "您有新的信息请查收!" + "\"}";//消息内容
            String platform = "android";//目标用户终端手机的平台类型,如: android, ios 多个请使用逗号分隔。
            String verification_code = GetMD5Str(String.valueOf(sendno), String.valueOf(receiver_type), receiver_value,masterSecret);//验证串,用于校验发送的合法性。MD5
            postData = "sendno=" + sendno;
            postData += ("&app_key=" + app_key);
            postData += ("&masterSecret=" + masterSecret);
            postData += ("&receiver_type=" + receiver_type);
            postData += ("&receiver_value=" + receiver_value);
            postData += ("&msg_type=" + msg_type);
            postData += ("&msg_content=" + msg_content);
            postData += ("&platform=" + platform);
            postData += ("&verification_code=" + verification_code);
            //byte[] data = encoding.GetBytes(postData);
            byte[] data = postData.getBytes("UTF-8");
//            String resCode = GetPostRequest(data);//调用极光的接口获取返回值
//            JpushMsg msg = Newtonsoft.Json.JsonConvert.DeserializeObject<JpushMsg>(resCode);//定义一个JpushMsg类,包含返回值信息,将返回的json格式字符串转成JpushMsg对象
        }
        catch (Exception ex)
        {
            
        }
        return postData;
    }
    
    
    
  /// <summary>
    /// MD5字符串
    /// </summary>
    /// <param name="paras">参数数组</param>
    /// <returns>MD5字符串</returns>
    public static String GetMD5Str(String sendno, String receiver_type, String receiver_value, String masterSecret)
    {
        String str = "";
        str = sendno+receiver_type+receiver_value+masterSecret;
        String md5Str = encode(str);
        return md5Str;
    }
    
    
    /**
	 * MD5密码加密
	 * 
	 * @param input
	 *            输入的字符串
	 * @return String
	 */
	public static String encode(String input) {
		if (!StringUtil.validate(input))
			return input;
		char hexDigits[] = { '0', '1', '2', '3', '4', '5', '6', '7', '8', '9',
				'a', 'b', 'c', 'd', 'e', 'f' };
		try {
			byte[] strTemp = input.getBytes();
			MessageDigest mdTemp = MessageDigest.getInstance("MD5");
			mdTemp.update(strTemp);
			byte[] md = mdTemp.digest();
			int j = md.length;
			char str[] = new char[j * 2];
			int k = 0;
			for (int i = 0; i < j; i++) {
				byte byte0 = md[i];
				str[k++] = hexDigits[byte0 >>> 4 & 0xf];
				str[k++] = hexDigits[byte0 & 0xf];
			}
			return new String(str);
		} catch (Exception e) {
			return null;
		}
	}
}

代码说明:

上述代码ApiKey需自己申请

APIMasterSecret API 主密码(//极光推送portal 上分配的 appKey 的验证串(masterSecret))

receiver_type=3携带唯一标识参数

receiver_value 用户id,在手机平台上,登录的用户Id

Android端代码:

将实例中的代码移动到android工程中

(1)初始化极光推送类库

JPushInterface.setDebugMode(true);
JPushInterface.init(this);

(2)登录方法中,登录成功注册一个通知用户id

JPushInterface.setAlias(this, user.getServiceStationId(), new TagAliasCallback() {
   @Override
   public void gotResult(int arg0, String alias, Set<String> arg2) {
    Log.e("info",alias+"-----------");
   }
  });

(3)MyReceiver.java跳转直接打开页面

else if (JPushInterface.ACTION_NOTIFICATION_OPENED.equals(intent.getAction())) {
            Log.d(TAG, "[MyReceiver] 用户点击打开了通知");
           
         //打开自定义的Activity
//         Intent i = new Intent(context, TestActivity.class);
            Intent i = new Intent(context, LoginActivity.class);

         i.putExtras(bundle);
         //i.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
         i.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TOP );
         context.startActivity(i);
        }

(4)AndroidManifest.xml android集成极光推送配置

<!-- 极光推动 主要实现区域  Begin -->
 <!-- Required -->
 <permission android:name="com.aerte.base.permission.JPUSH_MESSAGE" android:protectionLevel="signature" />
 <!-- Required -->
 <uses-permission android:name="com.aerte.base.permission.JPUSH_MESSAGE" />
 <uses-permission android:name="android.permission.RECEIVE_USER_PRESENT" />
 <uses-permission android:name="android.permission.WAKE_LOCK" />
 <uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />
 <uses-permission android:name="android.permission.WRITE_SETTINGS" />
 <uses-permission android:name="android.permission.VIBRATE" />
 <uses-permission android:name="android.permission.SYSTEM_ALERT_WINDOW"/> 
 <!-- 极光推动 主要实现区域  End -->

=============================================================================

中间部分省略

《activity》******************《/activity》

<service android:name="com.baidu.location.f" android:enabled="true" android:process=":remote">
  </service>

中间部分省略

=============================================================================

<!-- 极光推动 主要实现区域  Begin -->
  
  <!-- For test only 测试的主程序-->
        <!-- <activity
            android:name="com.example.jpushdemo.MainActivity"
            android:label="@string/app_name" >
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />
                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filters>
        </activity> -->
       <!-- For test only 测试高级功能 -->
       <activity android:name="com.example.jpushdemo.PushSetActivity" android:label="@string/app_name"></activity>
        <!-- For test only 测试设置 -->
       <activity android:name="com.example.jpushdemo.SettingActivity" android:label="@string/app_name"></activity>
        <!-- For test only 测试状态通知栏,需要打开的Activity -->
        <activity android:name="com.example.jpushdemo.TestActivity" >
            <intent-filter>
                <action android:name="jpush.testAction" />
                <category android:name="jpush.testCategory" />
            </intent-filter>
        </activity>
  
  
  
  <!-- Required SDK核心功能-->
        <activity
            android:name="cn.jpush.android.ui.PushActivity"
            android:theme="@android:style/Theme.Translucent.NoTitleBar"
            android:configChanges="orientation|keyboardHidden" >
            <intent-filter>
                <action android:name="cn.jpush.android.ui.PushActivity" />
                <category android:name="android.intent.category.DEFAULT" />
                <category android:name="com.11.11" />
            </intent-filter>
        </activity>
        <!-- Required  SDK核心功能-->
        <service
            android:name="cn.jpush.android.service.DownloadService"
            android:enabled="true"
            android:exported="false" >
        </service>
   
       
        <!-- Required SDK 核心功能-->
        <service
            android:name="cn.jpush.android.service.PushService"
            android:enabled="true"
            android:exported="false">
            <intent-filter>
                <action android:name="cn.jpush.android.intent.REGISTER" />
                <action android:name="cn.jpush.android.intent.REPORT" />
                <action android:name="cn.jpush.android.intent.PushService" />
                <action android:name="cn.jpush.android.intent.PUSH_TIME" />
               
            </intent-filter>
        </service>
       
        <!-- Required SDK核心功能-->
        <receiver
            android:name="cn.jpush.android.service.PushReceiver"
            android:enabled="true" >
             <intent-filter android:priority="1000">
                <action android:name="cn.jpush.android.intent.NOTIFICATION_RECEIVED_PROXY" />   <!--Required  显示通知栏 -->
                <category android:name="com.11.11" />
            </intent-filter>
            <intent-filter>
                <action android:name="android.intent.action.USER_PRESENT" />
                <action android:name="android.net.conn.CONNECTIVITY_CHANGE" />
            </intent-filter>
             <!-- Optional -->
            <intent-filter>
                <action android:name="android.intent.action.PACKAGE_ADDED" />
                <action android:name="android.intent.action.PACKAGE_REMOVED" />
                <data android:scheme="package" />
            </intent-filter>
  
        </receiver>
       
        <!-- Required SDK核心功能-->
        <receiver android:name="cn.jpush.android.service.AlarmReceiver" />
       
        <!-- User defined.  For test only  用户自定义的广播接收器-->
        <receiver
            android:name="com.example.jpushdemo.MyReceiver"
            android:enabled="true">
            <intent-filter>
                <action android:name="cn.jpush.android.intent.REGISTRATION" /> <!--Required  用户注册SDK的intent-->
                <action android:name="cn.jpush.android.intent.UNREGISTRATION" /> 
                <action android:name="cn.jpush.android.intent.MESSAGE_RECEIVED" /> <!--Required  用户接收SDK消息的intent-->
                <action android:name="cn.jpush.android.intent.NOTIFICATION_RECEIVED" /> <!--Required  用户接收SDK通知栏信息的intent-->
                <action android:name="cn.jpush.android.intent.NOTIFICATION_OPENED" /> <!--Required  用户打开自定义通知栏的intent-->
                <action android:name="cn.jpush.android.intent.ACTION_RICHPUSH_CALLBACK" /> <!--Optional 用户接受Rich Push Javascript 回调函数的intent-->
                <action android:name="cn.jpush.android.intent.CONNECTION" /><!-- 接收网络变化 连接/断开 since 1.6.3 -->
                <category android:name="com.11.11" />
            </intent-filter>
        </receiver>
 
       
        <!-- Required  . Enable it you can get statistics data with channel -->
        <meta-data android:name="JPUSH_CHANNEL" android:value="developer-default"/>
        <meta-data android:name="JPUSH_APPKEY" android:value="您的AppKey" /> <!--  </>值来自开发者平台取得的AppKey-->
  <!-- 极光推动 主要实现区域  End -->

 备注:com.11.11请替换成当前工程的路径,AndroidManifest.xml 中配置的activity都是实例中的

备注:流程大体如上,因在实际项目中故不提供源码

相关推荐