Android开发中从账号注册到推行消息一步一步实现极光推送

2023-12-21 05:10

本文主要是介绍Android开发中从账号注册到推行消息一步一步实现极光推送,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!

极光推送使用流程:

     1.去极光推送开发者服务网站注册账号

          https://www.jiguang.cn/accounts/register/form

          173417_eOiX_2879560.png

     2.注册完毕,登陆后创建应用

          173505_aFU7_2879560.png

     3.创建完毕获取应用信息

173518_pI4y_2879560.png

          

     4.创建工程,本次创建以Android Studio为例子

          应用名称为极光开发者平台的应用名称

           173537_fT5p_2879560.png

           173549_d529_2879560.png       

 

     5.创建完毕生成的空的工程,集成极光SDK,本例运用自动集成

1.jcenter自动集成步骤:

     使用jcenter自动集成的开发者,不需要在项目中添加jar和so,jcenter会自动完成依赖;

     在AndroidManifest.xml中不需要添加任何JPush SDK相关的配置,jcenter会自动导入。

     1.确认android studio的Project根目录的主gradle中配置了jcenter支持。(新建Preject默认配置支持)

    

buildscript {
    repositories {
        jcenter()
    }
    dependencies {
        classpath 'com.android.tools.build:gradle:2.2.2'

        // NOTE: Do not place your application dependencies here; they belong
        // in the individual module build.gradle files
    }
}

allprojects {
    repositories {
        jcenter()
    }
}

     

               Module build.gradle配置:

               AndroidManifest替换变量,在defaultConfig中添加

ndk {
    //选择要添加的对应cpu类型的.so库
    abiFilters 'armeabi', 'armeabi-v7a', 'armeabi-v8a'
    //'x86', 'x86_64', 'mips', 'mips64'
}
manifestPlaceholders = [
        JPUSH_PKGNAME : applicationId,
        JPUSH_APPKEY : 'a4d4161ac7d2908449605577', //JPush上注册的包名对应的appkey(https://www.jiguang.cn/push)
        JPUSH_CHANNEL : 'developer-default'//默认值
]

               

               添加依赖

compile 'cn.jiguang.sdk:jpush:3.0.5'//JPush版本
compile 'cn.jiguang.sdk:jcore:1.1.2'//JCore版本

          工程根目录文件gradle.properties中添加如下内容      

android.useDeprecatedNdk=true

 

     6.配置AndroidManifest.xml

添加权限

<!-- Required -->
<permission
    android:name="com.example.lucian.jpushdemo.permission.JPUSH_MESSAGE"
    android:protectionLevel="signature" />
<!-- Required  一些系统要求的权限,如访问网络等-->
<uses-permission android:name="com.example.lucian.jpushdemo.permission.JPUSH_MESSAGE" />
<uses-permission android:name="android.permission.RECEIVE_USER_PRESENT" />
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />

 

在Application中添加广播接收器

<!-- User defined.  For test only  用户自定义的广播接收器-->

<receiver
    android:name="com.example.lucian.jpushdemo.MyReceiver"
    android:exported="false"
    android:enabled="true">
    <intent-filter>
        <action android:name="cn.jpush.android.intent.REGISTRATION" /> <!--Required  用户注册SDK的intent-->
        <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.CONNECTION" /><!-- 接收网络变化 连接/断开 since 1.6.3 -->
        <category android:name="com.example.lucian.jpushdemo" />
    </intent-filter>
</receiver>

     7.创建信息接收器MyReceiver,该信息接收器为Manifiest中注册定义的MyReceiver

package com.example.lucian.jpushdemo;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.support.v4.content.LocalBroadcastManager;
import android.text.TextUtils;
import android.util.Log;

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

import java.util.Iterator;

import cn.jpush.android.api.JPushInterface;

/**
 * 自定义接收器
 * 
 * 如果不定义这个 Receiver,则:
 * 1) 默认用户会打开主界面
 * 2) 接收不到自定义消息
 */
public class MyReceiver extends BroadcastReceiver {
   private static final String TAG = "JPush";

   @Override
   public void onReceive(Context context, Intent intent) {
      try {
         Bundle bundle = intent.getExtras();
         Log.d(TAG, "[MyReceiver] onReceive - " + intent.getAction() + ", extras: " + printBundle(bundle));

         if (JPushInterface.ACTION_REGISTRATION_ID.equals(intent.getAction())) {
            String regId = bundle.getString(JPushInterface.EXTRA_REGISTRATION_ID);
            Log.d(TAG, "[MyReceiver] 接收Registration Id : " + regId);
            //send the Registration Id to your server...

         } else if (JPushInterface.ACTION_MESSAGE_RECEIVED.equals(intent.getAction())) {
            Log.d(TAG, "[MyReceiver] 接收到推送下来的自定义消息: " + bundle.getString(JPushInterface.EXTRA_MESSAGE));
            processCustomMessage(context, bundle);
         } else if (JPushInterface.ACTION_NOTIFICATION_RECEIVED.equals(intent.getAction())) {
            Log.d(TAG, "[MyReceiver] 接收到推送下来的通知");
            int notifactionId = bundle.getInt(JPushInterface.EXTRA_NOTIFICATION_ID);
            Log.d(TAG, "[MyReceiver] 接收到推送下来的通知的ID: " + notifactionId);
            processNotification(context, bundle);
         } else if (JPushInterface.ACTION_NOTIFICATION_OPENED.equals(intent.getAction())) {
            Log.d(TAG, "[MyReceiver] 用户点击打开了通知");
            processNotificationTitle(context, bundle);
         } else if (JPushInterface.ACTION_RICHPUSH_CALLBACK.equals(intent.getAction())) {
            Log.d(TAG, "[MyReceiver] 用户收到到RICH PUSH CALLBACK: " + bundle.getString(JPushInterface.EXTRA_EXTRA));
            //在这里根据 JPushInterface.EXTRA_EXTRA 的内容处理代码,比如打开新的Activity, 打开一个网页等..

         } else if(JPushInterface.ACTION_CONNECTION_CHANGE.equals(intent.getAction())) {
            boolean connected = intent.getBooleanExtra(JPushInterface.EXTRA_CONNECTION_CHANGE, false);
            Log.w(TAG, "[MyReceiver]" + intent.getAction() +" connected state change to "+connected);
         } else {
            Log.d(TAG, "[MyReceiver] Unhandled intent - " + intent.getAction());
         }
      } catch (Exception e){

      }

   }

   // 打印所有的 intent extra 数据
   private static String printBundle(Bundle bundle) {
      StringBuilder sb = new StringBuilder();
      for (String key : bundle.keySet()) {
         if (key.equals(JPushInterface.EXTRA_NOTIFICATION_ID)) {
            sb.append("\nkey:" + key + ", value:" + bundle.getInt(key));
         }else if(key.equals(JPushInterface.EXTRA_CONNECTION_CHANGE)){
            sb.append("\nkey:" + key + ", value:" + bundle.getBoolean(key));
         } else if (key.equals(JPushInterface.EXTRA_EXTRA)) {
            if (TextUtils.isEmpty(bundle.getString(JPushInterface.EXTRA_EXTRA))) {
               Log.i(TAG, "This message has no Extra data");
               continue;
            }

            try {
               JSONObject json = new JSONObject(bundle.getString(JPushInterface.EXTRA_EXTRA));
               Iterator<String> it =  json.keys();

               while (it.hasNext()) {
                  String myKey = it.next().toString();
                  sb.append("\nkey:" + key + ", value: [" +
                        myKey + " - " +json.optString(myKey) + "]");
               }
            } catch (JSONException e) {
               Log.e(TAG, "Get message extra JSON error!");
            }

         } else {
            sb.append("\nkey:" + key + ", value:" + bundle.getString(key));
         }
      }
      return sb.toString();
   }

   //send msg to MainActivity
   private void processCustomMessage(Context context, Bundle bundle) {
      if (JPushActivity.isForeground) {
         String message = bundle.getString(JPushInterface.EXTRA_MESSAGE);
         String extras = bundle.getString(JPushInterface.EXTRA_EXTRA);
         Intent msgIntent = new Intent(JPushActivity.MESSAGE_RECEIVED_ACTION);
         msgIntent.putExtra(JPushActivity.KEY_MESSAGE, message);
         if (!extras.isEmpty()) {
            try {
               JSONObject extraJson = new JSONObject(extras);
               if (extraJson.length() > 0) {
                  msgIntent.putExtra(JPushActivity.KEY_EXTRAS, extras);
               }
            } catch (JSONException e) {

            }

         }
         LocalBroadcastManager.getInstance(context).sendBroadcast(msgIntent);
      }

   }
   //send msg to MainActivity
   private void processNotification(Context context, Bundle bundle) {
      if (JPushActivity.isForeground) {
         String extras = bundle.getString(JPushInterface.EXTRA_EXTRA);
         String notification = bundle.getString(JPushInterface.EXTRA_ALERT);
         Intent msgIntent = new Intent(JPushActivity.MESSAGE_RECEIVED_ACTION);
         msgIntent.putExtra(JPushActivity.KEY_MESSAGE, notification);
         if (!extras.isEmpty()) {
            try {
               JSONObject extraJson = new JSONObject(extras);
               if (extraJson.length() > 0) {
                  msgIntent.putExtra(JPushActivity.KEY_EXTRAS, extras);
               }
            } catch (JSONException e) {

            }
         }
         LocalBroadcastManager.getInstance(context).sendBroadcast(msgIntent);
      }

   }

   private void processNotificationTitle(Context context, Bundle bundle) {
      if (JPushActivity.isForeground) {
         //进入下一个Activity前的处理
         Intent i = new Intent(context, TestActivity.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);

         //下一个Activity的处理
         /*Intent intent = getIntent();
         if (null != intent) {
            Bundle bundle = getIntent().getExtras();
            String title = bundle.getString(JPushInterface.EXTRA_NOTIFICATION_TITLE);
            String content = bundle.getString(JPushInterface.EXTRA_ALERT);
         }*/
      }
   }

}

 

     8.创建JPushActivity

package com.example.lucian.jpushdemo;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.os.Handler;
import android.support.v4.content.LocalBroadcastManager;
import android.text.TextUtils;
import android.util.Log;
import android.widget.Toast;

import java.util.LinkedHashSet;
import java.util.Set;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import cn.jpush.android.api.JPushInterface;
import cn.jpush.android.api.TagAliasCallback;

/**
 * Created by qulus on 2017/6/29 0029.
 */

public class JPushActivity {

    private static final String TAG = "JPushActivity" ;
    private static Context mContext ;
    public static boolean isForeground = true;//接收到信息是否传递给Activity
    private String receiveResult ;

    public JPushActivity() {}

    public JPushActivity(Context context) {
        this.mContext = context ;
    }

    private MessageReceiver mMessageReceiver;
    public static final String MESSAGE_RECEIVED_ACTION = "com.example.jpushdemo.MESSAGE_RECEIVED_ACTION";
    public static final String KEY_TITLE = "title";
    public static final String KEY_MESSAGE = "message";
    public static final String KEY_EXTRAS = "extras";
    /**
     *注册信息接收
     */
    public void registerMessageReceiver() {
        mMessageReceiver = new MessageReceiver() ;
        IntentFilter filter = new IntentFilter() ;
        filter.setPriority(IntentFilter.SYSTEM_HIGH_PRIORITY);
        filter.addAction(MESSAGE_RECEIVED_ACTION);
        LocalBroadcastManager.getInstance(mContext).registerReceiver(mMessageReceiver,filter);
    }
    /**
     *设置接收到信息是否向下传递给Activity
     */
    public void setIsForeground(boolean isForeground) {
        this.isForeground = isForeground ;
    }
    /**
     *停止Push信息
     */
    public void stopPush() {
        JPushInterface.stopPush(mContext);
    }
    /**
     *重启Push
     */
    public void resumePush() {
        JPushInterface.resumePush(mContext);
    }

    /**
     *初始化推送服务,不初始化,无法接收到信息
     */
    public void initJPush() {
        JPushInterface.setDebugMode(true);
        JPushInterface.init(mContext);
    }
    /**
     *取消注册接收服务
     */
    public void unregisterReceiver() {
        LocalBroadcastManager.getInstance(mContext).unregisterReceiver(mMessageReceiver);
    }
    /**
     *信息接收器,接收到信息后的处理
     */
    public class MessageReceiver extends BroadcastReceiver {
        @Override
        public void onReceive(Context context, Intent intent) {

            if (MESSAGE_RECEIVED_ACTION.equals(intent.getAction())) {
                String message = intent.getStringExtra(KEY_MESSAGE) ;
                String extras = intent.getStringExtra(KEY_EXTRAS) ;
                StringBuilder showMsg = new StringBuilder() ;
                showMsg.append(KEY_MESSAGE + " : " + message + "\n");
                if (!(null == extras)) {
                    showMsg.append(KEY_EXTRAS + " : " + extras + "\n");
                }
                Toast.makeText(mContext,showMsg.toString(),Toast.LENGTH_SHORT).show();
                receiveResult = showMsg.toString() ;
            }
        }
    }
    /**
     *获取接收到的信息
     */
    public String getReceiveResult() {
        return receiveResult ;
    }
    /**
     *为设备设置标签
     */
    public  static void setTag(String tag) {
        // 检查 tag 的有效性
        if (TextUtils.isEmpty(tag)) {
            return;
        }
        // ","隔开的多个 转换成 Set
        String[] sArray = tag.split(",");
        Set<String> tagSet = new LinkedHashSet<String>();
        for (String sTagItme : sArray) {
            if (!isValidTagAndAlias(sTagItme)) {
                Log.e(TAG, "error_tag_gs_empty");
                return;
            }
            tagSet.add(sTagItme);
        }
        // 调用JPush API设置Tag
        mHandler.sendMessage(mHandler.obtainMessage(MSG_SET_TAGS, tagSet));
    }
    /**
     *为设备设置别名
     */
    public void setAlias(String alias) {
        // 检查 alias 的有效性
        if (TextUtils.isEmpty(alias)) {
            return;
        }
        if (!isValidTagAndAlias(alias)) {
            Log.e(TAG, "error_alias_empty");
            return;
        }

        //调用JPush API设置Alias
        mHandler.sendMessage(mHandler.obtainMessage(MSG_SET_ALIAS, alias));
    }


    // 校验Tag Alias 只能是数字,英文字母和中文
    public static boolean isValidTagAndAlias(String s) {
        Pattern p = Pattern.compile("^[\u4E00-\u9FA50-9a-zA-Z_!@#$&*+=.|]+$");
        Matcher m = p.matcher(s);
        return m.matches();
    }

    private static final int MSG_SET_ALIAS = 1001;
    private static final int MSG_SET_TAGS = 1002;
    private final static Handler mHandler = new Handler() {
        @Override
        public void handleMessage(android.os.Message msg) {
            super.handleMessage(msg);
            switch (msg.what) {
                case MSG_SET_ALIAS:
                    Log.d(TAG, "Set alias in handler.");
                    JPushInterface.setAliasAndTags(mContext, (String) msg.obj, null, mAliasCallback);
                    break;

                case MSG_SET_TAGS:
                    Log.d(TAG, "Set tags in handler.");
                    JPushInterface.setAliasAndTags(mContext, null, (Set<String>) msg.obj, mTagsCallback);
                    break;

                default:
                    Log.i(TAG, "Unhandled msg - " + msg.what);
            }
        }
    };
    /**
     *设置别名的回调函数
     */
    private final static TagAliasCallback mAliasCallback = new TagAliasCallback() {

        @Override
        public void gotResult(int code, String alias, Set<String> tags) {
            String LogUtilss;
            switch (code) {
                case 0:
                    LogUtilss = "Set tag and alias success";
                    Log.i(TAG, LogUtilss);
                    break;

                case 6002:
                    LogUtilss = "Failed to set alias and tags due to timeout. Try again after 60s.";
                    Log.i(TAG, LogUtilss);
                    if (isConnected(mContext)) {
                        mHandler.sendMessageDelayed(mHandler.obtainMessage(MSG_SET_ALIAS, alias), 1000 * 60);
                    } else {
                        Log.i(TAG, "No network");
                    }
                    break;

                default:
                    LogUtilss = "Failed with errorCode = " + code;
                    Log.e(TAG, LogUtilss);
            }

        }

    };
    /**
     *设置标签回调函数
     */
    private final static TagAliasCallback mTagsCallback = new TagAliasCallback() {

        @Override
        public void gotResult(int code, String alias, Set<String> tags) {
            String LogUtilss;
            switch (code) {
                case 0:
                    LogUtilss = "Set tag and alias success";
                    Log.i(TAG, LogUtilss);
                    break;

                case 6002:
                    LogUtilss = "Failed to set alias and tags due to timeout. Try again after 60s.";
                    Log.i(TAG, LogUtilss);
                    if (isConnected(mContext)) {
                        mHandler.sendMessageDelayed(mHandler.obtainMessage(MSG_SET_TAGS, tags), 1000 * 60);
                    } else {
                        Log.i(TAG, "No network");
                    }
                    break;

                default:
                    LogUtilss = "Failed with errorCode = " + code;
                    Log.e(TAG, LogUtilss);
            }

        }

    };
    /**
     *检测设备是否联网
     */
    public static boolean isConnected(Context context) {
        ConnectivityManager conn = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
        NetworkInfo info = conn.getActiveNetworkInfo();
        return (info != null && info.isConnected());
    }


}

 

     9.在需要的地方初始化JPush和注册信息接收器

package com.example.lucian.jpushdemo;

import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;

public class MainActivity extends AppCompatActivity {
    private JPushActivity mJPush ;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        mJPush = new JPushActivity(this) ;
        mJPush.initJPush();//初始化极光推送
        mJPush.registerMessageReceiver();//注册信息接收器
        mJPush.setTag("admin1,admin2");//为设备设置标签
        mJPush.setAlias("automic");//为设备设置别名
    }
}

     

     10.通过极光推送开发者服务平台测试,是否能接收到信息,可根据设置的标签,别名,等形式发送,可发送通知和自定义消息

173613_tFeK_2879560.png

173618_h1ly_2879560.png

11.推送历史:

173623_PmiG_2879560.png

 

     

转载于:https://my.oschina.net/LucianQU/blog/1068989

这篇关于Android开发中从账号注册到推行消息一步一步实现极光推送的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!



http://www.chinasem.cn/article/518740

相关文章

C++对象布局及多态实现探索之内存布局(整理的很多链接)

本文通过观察对象的内存布局,跟踪函数调用的汇编代码。分析了C++对象内存的布局情况,虚函数的执行方式,以及虚继承,等等 文章链接:http://dev.yesky.com/254/2191254.shtml      论C/C++函数间动态内存的传递 (2005-07-30)   当你涉及到C/C++的核心编程的时候,你会无止境地与内存管理打交道。 文章链接:http://dev.yesky

通过SSH隧道实现通过远程服务器上外网

搭建隧道 autossh -M 0 -f -D 1080 -C -N user1@remotehost##验证隧道是否生效,查看1080端口是否启动netstat -tuln | grep 1080## 测试ssh 隧道是否生效curl -x socks5h://127.0.0.1:1080 -I http://www.github.com 将autossh 设置为服务,隧道开机启动

Eureka高可用注册中心registered-replicas没有分布式注册中心

自己在学习过程中发现,如果Eureka挂掉了,其他的Client就跑不起来了,那既然是商业项目,还是要处理好这个问题,所以决定用《Spring Cloud微服务实战》(PDF版在全栈技术交流群中自行获取)中说的“高可用注册中心”。 一开始我yml的配置是这样的 server:port: 8761eureka:instance:hostname: 127.0.0.1client:fetch-r

时序预测 | MATLAB实现LSTM时间序列未来多步预测-递归预测

时序预测 | MATLAB实现LSTM时间序列未来多步预测-递归预测 目录 时序预测 | MATLAB实现LSTM时间序列未来多步预测-递归预测基本介绍程序设计参考资料 基本介绍 MATLAB实现LSTM时间序列未来多步预测-递归预测。LSTM是一种含有LSTM区块(blocks)或其他的一种类神经网络,文献或其他资料中LSTM区块可能被描述成智能网络单元,因为

vue项目集成CanvasEditor实现Word在线编辑器

CanvasEditor实现Word在线编辑器 官网文档:https://hufe.club/canvas-editor-docs/guide/schema.html 源码地址:https://github.com/Hufe921/canvas-editor 前提声明: 由于CanvasEditor目前不支持vue、react 等框架开箱即用版,所以需要我们去Git下载源码,拿到其中两个主

Eclipse+ADT与Android Studio开发的区别

下文的EA指Eclipse+ADT,AS就是指Android Studio。 就编写界面布局来说AS可以边开发边预览(所见即所得,以及多个屏幕预览),这个优势比较大。AS运行时占的内存比EA的要小。AS创建项目时要创建gradle项目框架,so,创建项目时AS比较慢。android studio基于gradle构建项目,你无法同时集中管理和维护多个项目的源码,而eclipse ADT可以同时打开

android 免费短信验证功能

没有太复杂的使用的话,功能实现比较简单粗暴。 在www.mob.com网站中可以申请使用免费短信验证功能。 步骤: 1.注册登录。 2.选择“短信验证码SDK” 3.下载对应的sdk包,我这是选studio的。 4.从头像那进入后台并创建短信验证应用,获取到key跟secret 5.根据技术文档操作(initSDK方法写在setContentView上面) 6.关键:在有用到的Mo

android一键分享功能部分实现

为什么叫做部分实现呢,其实是我只实现一部分的分享。如新浪微博,那还有没去实现的是微信分享。还有一部分奇怪的问题:我QQ分享跟QQ空间的分享功能,我都没配置key那些都是原本集成就有的key也可以实现分享,谁清楚的麻烦详解下。 实现分享功能我们可以去www.mob.com这个网站集成。免费的,而且还有短信验证功能。等这分享研究完后就研究下短信验证功能。 开始实现步骤(新浪分享,以下是本人自己实现

Android我的二维码扫描功能发展史(完整)

最近在研究下二维码扫描功能,跟据从网上查阅的资料到自己勉强已实现扫描功能来一一介绍我的二维码扫描功能实现的发展历程: 首页通过网络搜索发现做android二维码扫描功能看去都是基于google的ZXing项目开发。 2、搜索怎么使用ZXing实现自己的二维码扫描:从网上下载ZXing-2.2.zip以及core-2.2-source.jar文件,分别解压两个文件。然后把.jar解压出来的整个c

android 带与不带logo的二维码生成

该代码基于ZXing项目,这个网上能下载得到。 定义的控件以及属性: public static final int SCAN_CODE = 1;private ImageView iv;private EditText et;private Button qr_btn,add_logo;private Bitmap logo,bitmap,bmp; //logo图标private st