Androidstudio Offline pack MUI Integrated Jpush Aurora Push and manage push in Java backend

Source: Internet
Author: User
Tags jcenter

1.AndroidStudio offline packaged MUI

How to package offline please take a look at the essay "Androidstudio Offline Pack MUI"

2. Integrated Aurora push

Official Document: https://docs.jiguang.cn/jpush/client/Android/android_guide/

Recommended for Jcenter Auto-integration, manual integration is error-prone for beginners

Developers using Jcenter Auto-integration do not need to add jars and so,jcenter in the project to automatically complete dependencies, and in androidmanifest.xml you do not need to add any Jpush SDK-related configuration, Jcenter will automatically import.

  • If the developer needs to modify the component properties, you can define the component with the same name in the local androidmanifest and configure the desired properties, and then use Xmlns:tools to control the components on the Jcenter on the local component. Example:

    <manifest xmlns:android= "http://schemas.android.com/apk/res/android"    package= " Com.android.tests.flavorlib.app "    xmlns:tools=" Http://schemas.android.com/tools ">    <application        android:icon= "@drawable/icon"        android:name= "Com.example.jpushdemo.ExampleApplication"        android: Label= "@string/app_name" >        <service android:name= "Cn.jpush.android.service.PushService"            android: process= ": multiprocess"            tools:node= "replace" >            ...        </service> ...  </application>  ......</manifest>
  • Confirm that Jcenter support is configured in the main gradle of the Project root directory of Android studio. (supported by new project default configuration)

    Buildscript {    repositories {        jcenter ()    }    ...} Allprojets {    repositories {        jcenter ()    }}
  • Add dependent and androidmanifest substitution variables in the module's gradle.

    Android {    ...    defaultconfig {        ApplicationID "com.xxx.xxx"//jpush the name of the package registered.        ......        NDK {            //select the. So library for the corresponding CPU type to be added.            abifilters ' Armeabi ', ' armeabi-v7a ', ' arm64-v8a '            //can also add ' x86 ', ' x86_64 ', ' MIPS ', ' Mips64 '        }        Manifestplaceholders = [            Jpush_pkgname:applicationid,            jpush_appkey: "Your APPKEY",//jpush the name of the package that is registered on the appkey.< C12/>jpush_channel: "Developer-default",//temporarily fill in the default value        .        ......    }    ......} dependencies {    ...    Compile ' cn.jiguang.sdk:jpush:3.1.1 '  //Here is an example of the Jpush 3.1.1 version.    compile ' cn.jiguang.sdk:jcore:1.1.9 '  //Here is an example of the Jcore 1.1.9 version.    ......}
3.Android Project Add registration, get Aurora push related information Code 3.1. Add Jpushutil tool class in AS
Import Android.content.context;import Android.content.pm.applicationinfo;import android.content.pm.PackageInfo; Import Android.content.pm.packagemanager;import Android.content.pm.packagemanager.namenotfoundexception;import Android.net.connectivitymanager;import Android.net.networkinfo;import Android.os.bundle;import Android.os.Looper; Import Android.telephony.telephonymanager;import Android.text.textutils;import Android.widget.toast;import Java.util.regex.matcher;import Java.util.regex.pattern;import Cn.jpush.android.api.jpushinterface;import    Io.dcloud.common.adapter.util.logger;public class Jpushutil {public static final String prefs_name = "Jpush_example";    public static final String prefs_days = "Jpush_example_days";    public static final String prefs_start_time = "Prefs_start_time";    public static final String prefs_end_time = "Prefs_end_time";    public static final String Key_app_key = "Jpush_appkey";      public static Boolean isEmpty (String s) {if (null = = s)      return true;        if (s.length () = = 0) return true;        if (S.trim (). Length () = = 0) return true;    return false;     /** * can only start with a "+" or a number; The following content can only contain "-" and numbers.    * */private final static String Mobile_number_chars = "^[+0-9][-0-9]{1,}$";        public static Boolean Isvalidmobilenumber (String s) {if (Textutils.isempty (s)) return true;        Pattern p = pattern.compile (mobile_number_chars);        Matcher m = P.matcher (s);    return m.matches (); }//Verify that the tag Alias can only be numeric, English letter and Chinese public static Boolean Isvalidtagandalias (String s) {Pattern p = Pattern.compi Le ("^[\u4e00-\[email protected]#$&*+=.|")        +$");        Matcher m = P.matcher (s);    return m.matches ();        }//Get Appkey public static String Getappkey (context context) {Bundle metaData = null;        String AppKey = null; try {applicationinfo ai = Context.getpackagemanager (). Getapplicationinfo (context. Getpackagename (), packagemanager.get_meta_data);            if (null! = AI) metaData = ai.metadata;                if (null! = MetaData) {AppKey = metadata.getstring (Key_app_key);                if ((null = = AppKey) | | appkey.length ()! =) {AppKey = null;    }}} catch (Namenotfoundexception e) {} return AppKey; }//Get version number public static String GetVersion (context context) {try {PackageInfo manager = Context.getpackagemanage R (). Getpackageinfo (Context.getpackagename (), 0); return manager.versionname;}    catch (Namenotfoundexception e) {return "Unknown";}}  public static void Showtoast (final String toast, final context context) {New Thread (new Runnable () {@Overridepublic void Run () {looper.prepare (); Toast.maketext (context, toast, toast.length_short). Show (); Looper.loop ();}}).    Start (); } public static Boolean isconnected (context context) {Connectivitymanager conn = (Connectivitymanager) context.getsystemservice (Context.connectivity_service);        Networkinfo info = Conn.getactivenetworkinfo ();    return (info! = null && info.isconnected ()); } public static string Getimei (context context, string imei) {string ret = null;try {Telephonymanager telephony            Manager = (Telephonymanager) context.getsystemservice (Context.telephony_service); ret = Telephonymanager.getdeviceid ();} catch (Exception e) {LOGGER.E (JpushUtil.class.getSimpleName (), E.getmessage ());}        if (ISREADABLEASCII (ret)) {return ret;        } else {return IMEI;        }} private static Boolean Isreadableascii (Charsequence string) {if (Textutils.isempty (String)) return false;            try {Pattern p = pattern.compile ("[\\x20-\\x7e]+");        return P.matcher (String). Matches ();        } catch (Throwable e) {return true; }} public static String Getdeviceid (context context) {RETurn jpushinterface.getudid (context); }}

  

3.2. Add Jpushinitactivity Class
Import Android.os.bundle;import Cn.jpush.android.api.instrumentedactivity;import cn.jpush.android.api.jpushinterface;/** * Initialize Aurora push related information */public class Jpushinitactivity extends Instrumentedactivity { public static string app_key = "";//Application registered in Aurora push idpublic static string Master_secret  = "08123213666d973dkkik3bbe7fd6 *//The password obtained after the Aurora is pushed to the official website (please change your own registered value) public static String registration_id = "";//the user who installs the app id@overridepublic void registered in Aurora push OnCreate (Bundle savedinstancestate) {super.oncreate (savedinstancestate); init ();} public void init () {Jpushinterface.init (Getapplicationcontext ());//gets initialized after the environment App_key = Jpushutil.getappkey ( Getapplicationcontext ()); registration_id = Jpushinterface.getregistrationid (Getapplicationcontext ());} public static String Getjpushdata () {return "AppKey:" +app_key+ "; Mastersecret:" +master_secret+ "; Registrationid:" + registration_id;}}

  

3.3. Register Jpushinitactivity in Androidmanifest.xml
<!--used to initialize the registration data for Aurora Push, not to user-  -        <activity            android:name= ". Jpush. Jpushinitactivity "            android:theme=" @android: Style/theme.nodisplay ">        </activity>

  

3.4. Create activity in Mui.js and complete registration
Mui.plusready (function () {//call native Activityvar Intent = Plus.android.importClass ("android.content.Intent");// Gets the instance of the main activity object var main = plus.android.runtimeMainActivity ();//create Intentvar naviintent = new Intent (); var ComponentName = Plus.android.importClass ("Android.content.ComponentName");//create Aurora push register activity, Please replace the package name with your own package name Naviintent.setcomponent (componentname (Main, "com.xxx.xxx.xxx.JPushInitActivity")); Main.startactivity (naviintent); Call the Java method $ (". Login_btn"). Click (function () {//Introduce Java class file, package name please replace your own package name var Jpush  = Plus.android.importClass (" Com.xxx.xxx.xxx.JPushInitActivity ");//Call static method var jpushdata = Jpush.getjpushdata ();//Output return value alert (jpushdata);//todo Pass the Jpushdata and username and password to the Java backend at login
//......}) })

  

4.java Terminal Code 4.1 receive login information, bind Registrationid with user, please associate according to your own business
Verify success, Associate Jpushid with user try {string[] split = Jpushdata.split (";"); for (string str:split) {if ("Registrationid". Equals (Str.split (":") [0])) {String jpushid = Str.split (":") [1]; String sql = "UPDATE bo_pbs_org_ext_user SET j_push_id =?" WHERE Yhzh =? "; O Bject[] params = {Jpushid, Loginusermodel.getuser_account ()};d b.update (sql, params); catch (Exception e) {e.printstacktrace ();}

 

4.2 New Service Interface Jpushmessageservice
Public interface Jpushmessageservice {/** * sent to all users * @param content * @return */public string Sendpushall (string content) /** * sent to userid corresponding user * @param userid * @param content * @return */public string Senpushbyuserid (String userId, String con tent);}

  

4.3 New service Interface implementation class Jpushmessageserviceimpl
Import Java.util.arraylist;import java.util.hashmap;import Java.util.list;import Java.util.map;import Javax.annotation.resource;import Org.apache.commons.lang.stringutils;import Org.apache.log4j.logger;import Org.springframework.stereotype.service;import Com.pbs.mobile.business.service.jpushmessageservice;import Com.pbs.mobile.util.jpushutil;import Com.pbs.mobile.util.returnutil;import Com.pbs.workflow.service.databaseservice;import Com.pbs.workflow.service.userservice;import Cn.jiguang.common.clientconfig;import Cn.jiguang.common.resp.apiconnectionexception;import Cn.jiguang.common.resp.apirequestexception;import Cn.jpush.api.jpushclient;import Cn.jpush.api.push.PushResult; Import Cn.jpush.api.push.model.PushPayload; @Servicepublic class Jpushmessageserviceimpl implements Jpushmessageservice {@ResourceUserService userservice; @ResourceDataBaseService db;private final static String AppKey = "weqwewe1123123123123";//here please fill in the values you have registered, or send the value via MUI to the background private final static String Mastersecret = "213123123asdjfoi1293 ";//here please fill in the values you have registered, or pass the value/** * to the background via MUI to save the offline duration. seconds in the unit. Supports up to 10 days (864,000 seconds). 0 indicates that the message is not saved offline. That is, the user is issued immediately online, the current non-online users will not receive this message. * This parameter is not set to default, the default is to save 1 days of offline messages (86,400 seconds). */private static Long timeToLive = $ * 24;private static jpushclient jpushclient = null;private static final Logger Logger = Logger.getlogger (Jpushmessageserviceimpl.class); @Overridepublic string Sendpushall (string content) { ClientConfig config = clientconfig.getinstance (); Config.setmaxretrytimes (5); Config.setconnectiontimeout (10 * 1000); Config.setglobalpushsetting (False, timeToLive); jpushclient = new Jpushclient (Mastersecret, appKey, null, config); Boolean flag = false;try {pushpayload payload = jpushutil.buildpushobject_all_all_alert (content); Pushresult result = Jpushclient.sendpush (payload); if (null! = result) {Logger.info ("Get resul---" + result); flag = true;} } catch (Apiconnectionexception e) {logger.error ("Connection error. Should retry later. ", e);} catch (Apirequestexception e) {logger.error ("error response from JPush server. Should review and fix it. ", e); Logger.info (" HTTP Status: "+ e.getstatus ()), Logger.info (" Error Code: "+ e.geterrorcode ()); Logger.info (" Error Message: "+ e.geterrormessage ()); Logger.info (" Msg ID: "+ e.getmsgid ());} map<string, object> result = new hashmap<string, object> (), if (flag) {Result.put ("status", "OK"), Result.put ("code", "0"); Result.put ("msg", "Send Success");} else {result.put ("status", "fail"), Result.put ("Code", "1"), Result.put ("msg", "Send Failed");} return returnutil.getjsonstr (result);} @Overridepublic string Senpushbyuserid (String userId, String content) {Boolean flag = False;try {// Query the database for Aurora push registration information and whether or not to accept push (you can omit the decision to receive push based on your business)
Eu. J_PUSH_ID is the Registrationid that we manage with the user after login
String sql = "Select EU." J_push_id,eu. Accept_push from Pbs_org_user u joins bo_pbs_org_ext_user eu on u.user_account = EU. Yhzh and u.id =? "; O Bject[] params = {userId}; List<map<string, object>> records = db.querylist (sql, params); if (records! = null && records.size () & Gt 0) {Boolean acceptpush = Records.get (0). Get ("accept_push") = = null? True: (Boolean) records.get (0). Get ("Accept_push"); String Jpushid = records.get (0). Get ("j_push_id") = = null? "": (String) records.get (0). Get ("j_push_id"); if (Acceptpush && stringutils.isnotempty (Jpushid)) {jpushclient Jpushclient = new Jpushclient (Mastersecret, AppKey); list<string> regesterids = new arraylist<> (); Regesterids.add (Jpushid); try {pushpayload payload = Jpushutil.buildpushobject_all_all_regesterids (regesterids, content); Pushresult Pushresult = Jpushclient.sendpush (payload), if (null! = Pushresult) {logger.info ("Get result----" + Pushresult ); flag = True;}} catch (Apiconnectionexception e) {logger.erROR ("Connection error. Should retry later. ", e);} catch (Apirequestexception e) {logger.error ("error response from Jpush server. Should review and fix it. ", e); Logger.info (" HTTP Status: "+ e.getstatus ()), Logger.info (" Error Code: "+ e.geterrorcode ()); Logger.info (" Error Message: "+ e.geterrormessage ()); Logger.info (" Msg ID: "+ e.getmsgid ());}}} catch (Exception e) {e.printstacktrace ();} map<string, object> result = new hashmap<string, object> (), if (flag) {Result.put ("status", "OK"), Result.put ("code", "0"); Result.put ("msg", "Send Success");} else {result.put ("status", "fail"), Result.put ("Code", "1"), Result.put ("msg", "Send Failed");} return returnutil.getjsonstr (Result);}}

  

Androidstudio Offline pack MUI Integrated Jpush Aurora Push and manage push in Java backend

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.