Android 使用第三方SDK极光实现推送功能

编程入门 行业动态 更新时间:2024-10-14 00:26:21

Android 使用第三方SDK<a href=https://www.elefans.com/category/jswz/34/1767070.html style=极光实现推送功能"/>

Android 使用第三方SDK极光实现推送功能

前言

这是我第一次写博客,今天学习了使用第三方sdk实现推送,为防止下次使用时忘记,在此记录下来,文章参考了极光自带的集成指南与其他大佬的代码,侵权私删。

JIGUANG SDK 集成指南

jiguang_sdk.zip 集成压缩包内容

  • jiguang

    • JIGUANG SDK 组合包。
  • jiguang-demo

    • JIGUANG SDK 组合包集成 demo。
  • doc

    • 文档说明。

集成步骤

导入 JIGUANG SDK

通过 AS 将 SDK 作为 module 导入项目

导入步骤:AndroidStudio -> File -> New -> Import Module -> 选择 jiguang 导入

配置 JIGUANG SDK

settings.gradle 配置添加:

include  ':jiguang'

在 module 的 gradle 中 添加 SDK 依赖,以 jpush 为例

android {defaultConfig {applicationId "com.xxx.xxx" //JPush 上注册的包名.manifestPlaceholders = [JPUSH_PKGNAME : applicationId,JPUSH_APPKEY : "386f567a31662ab695ea6703", //极光开发平台上注册的包名对应的appkey.JPUSH_CHANNEL : "developer-default", //暂时填写默认值即可.//xiaomi_config_startXIAOMI_APPID  : "MI-小米的APPID",XIAOMI_APPKEY : "MI-小米的APPKEY",//xiaomi_config_end//oppo_config_startOPPO_APPKEY   : "OP-oppo的APPKEY",OPPO_APPID    : "OP-oppo的APPID",OPPO_APPSECRET: "OP-oppo的APPSECRET",//oppo_config_end//vivo_config_startVIVO_APPKEY   : "vivo的APPKEY",VIVO_APPID    : "vivo的APPID",//vivo_config_end]}
}dependencies {implementation project(':jiguang')
}

编译 jiguang-demo 运行

JIGUANG SDK 配置指南

在Application中初始化

package com.example.practice.app;import android.app.Application;
import android.content.Context;
import cn.jpush.android.api.JPushInterface;public class MyApp extends Application {public static Context context;@Overridepublic void onCreate() {super.onCreate();context = this;initJPush();}//初始化极光private void initJPush() {JPushInterface.setDebugMode(true);    // 设置开启日志,发布时请关闭日志JPushInterface.init(this);            // 初始化 JPush}}

服务配置

如果您使用的JCore是2.0.0及更高版本,需要额外在Androidmanifest中配置一个Service,以在更多手机平台上获得更稳定的支持,示例如下。(JCore1.x版本不需要)

在清单文件(Androidmanifest)下注册服务

<!-- Since JCore2.0.0 Required SDK核心功能--><!-- 可配置android:process参数将Service放在其他进程中;android:enabled属性不能是false -->
<!-- 这个是自定义Service,要继承极光JCommonService,可以在更多手机平台上使得推送通道保持的更稳定 --><service android:name=".jpush.pushService"android:enabled="true"android:exported="false"android:process=":pushcore"><intent-filter><action android:name="cn.jiguang.user.service.action" /></intent-filter></service>

java代码

package com.example.practice.jpush;import cn.jpush.android.service.JCommonService;public class pushService extends JCommonService {}

广播配置

从JPush3.0.7开始,需要配置继承JPushMessageReceiver的广播,原来如果配了MyReceiver现在可以弃用。示例如下。

在清单文件(Androidmanifest)下注册广播

   <receiverandroid:name=".jpush.PushMessageReceiver"android:enabled="true"android:exported="false" ><intent-filter><action android:name="cn.jpush.android.intent.RECEIVE_MESSAGE" /><category android:name="com.example.practice" /></intent-filter></receiver>

java代码

package com.example.practice.jpush;import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.util.Log;import org.json.JSONException;
import org.json.JSONObject;import cn.jpush.android.api.CmdMessage;
import cn.jpush.android.api.CustomMessage;
import cn.jpush.android.api.JPushInterface;
import cn.jpush.android.api.JPushMessage;
import cn.jpush.android.api.NotificationMessage;
import cn.jpush.android.service.JPushMessageReceiver;public class PushMessageReceiver extends JPushMessageReceiver {private static final String TAG = "PushMessageReceiver";@Overridepublic void onMessage(Context context, CustomMessage customMessage) {Log.e(TAG,"[onMessage] "+customMessage);processCustomMessage(context,customMessage);}@Overridepublic void onNotifyMessageOpened(Context context, NotificationMessage message) {Log.e(TAG,"[onNotifyMessageOpened] "+message);try{//打开自定义的ActivityIntent i = new Intent(context, TestJPushActivity.class);Bundle bundle = new Bundle();bundle.putString(JPushInterface.EXTRA_NOTIFICATION_TITLE,message.notificationTitle);bundle.putString(JPushInterface.EXTRA_ALERT,message.notificationContent);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);}catch (Throwable throwable){}}@Overridepublic void onMultiActionClicked(Context context, Intent intent) {Log.e(TAG, "[onMultiActionClicked] 用户点击了通知栏按钮");String nActionExtra = intent.getExtras().getString(JPushInterface.EXTRA_NOTIFICATION_ACTION_EXTRA);//开发者根据不同 Action 携带的 extra 字段来分配不同的动作。if(nActionExtra==null){Log.d(TAG,"ACTION_NOTIFICATION_CLICK_ACTION nActionExtra is null");return;}if (nActionExtra.equals("my_extra1")) {Log.e(TAG, "[onMultiActionClicked] 用户点击通知栏按钮一");} else if (nActionExtra.equals("my_extra2")) {Log.e(TAG, "[onMultiActionClicked] 用户点击通知栏按钮二");} else if (nActionExtra.equals("my_extra3")) {Log.e(TAG, "[onMultiActionClicked] 用户点击通知栏按钮三");} else {Log.e(TAG, "[onMultiActionClicked] 用户点击通知栏按钮未定义");}}@Overridepublic void onNotifyMessageArrived(Context context, NotificationMessage message) {Log.e(TAG,"[onNotifyMessageArrived] "+message);}@Overridepublic void onNotifyMessageDismiss(Context context, NotificationMessage message) {Log.e(TAG,"[onNotifyMessageDismiss] "+message);}@Overridepublic void onRegister(Context context, String registrationId) {Log.e(TAG,"[onRegister] "+registrationId);}@Overridepublic void onConnected(Context context, boolean isConnected) {Log.e(TAG,"[onConnected] "+isConnected);}@Overridepublic void onCommandResult(Context context, CmdMessage cmdMessage) {Log.e(TAG,"[onCommandResult] "+cmdMessage);}@Overridepublic void onTagOperatorResult(Context context, JPushMessage jPushMessage) {TagAliasOperatorHelper.getInstance().onTagOperatorResult(context,jPushMessage);super.onTagOperatorResult(context, jPushMessage);}@Overridepublic void onCheckTagOperatorResult(Context context,JPushMessage jPushMessage){TagAliasOperatorHelper.getInstance().onCheckTagOperatorResult(context,jPushMessage);super.onCheckTagOperatorResult(context, jPushMessage);}@Overridepublic void onAliasOperatorResult(Context context, JPushMessage jPushMessage) {TagAliasOperatorHelper.getInstance().onAliasOperatorResult(context,jPushMessage);super.onAliasOperatorResult(context, jPushMessage);}@Overridepublic void onMobileNumberOperatorResult(Context context, JPushMessage jPushMessage) {TagAliasOperatorHelper.getInstance().onMobileNumberOperatorResult(context,jPushMessage);super.onMobileNumberOperatorResult(context, jPushMessage);}//send msg to MainActivityprivate void processCustomMessage(Context context, CustomMessage customMessage) {if (TestJPushActivity.isForeground) {String message = customMessage.message;String extras = customMessage.extra;Intent msgIntent = new Intent(TestJPushActivity.MESSAGE_RECEIVED_ACTION);msgIntent.putExtra(TestJPushActivity.KEY_MESSAGE, message);if (!ExampleUtil.isEmpty(extras)) {try {JSONObject extraJson = new JSONObject(extras);if (extraJson.length() > 0) {msgIntent.putExtra(TestJPushActivity.KEY_EXTRAS, extras);}} catch (JSONException e) {}}LocalBroadcastManager.getInstance(context).sendBroadcast(msgIntent);}}@Overridepublic void onNotificationSettingsCheck(Context context, boolean isOn, int source) {super.onNotificationSettingsCheck(context, isOn, source);Log.e(TAG,"[onNotificationSettingsCheck] isOn:"+isOn+",source:"+source);}
}

推送的工具类

package com.example.practice.jpush;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.ConnectivityManager;
import android.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;public class ExampleUtil {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;}/*** 只能以 “+” 或者 数字开头;后面的内容只能包含 “-” 和 数字。* */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 = Patternpile(MOBILE_NUMBER_CHARS);Matcher m = p.matcher(s);return m.matches();}// 校验Tag Alias 只能是数字,英文字母和中文public static boolean isValidTagAndAlias(String s) {Pattern p = Patternpile("^[\u4E00-\u9FA50-9a-zA-Z_!@#$&*+=.|]+$");Matcher m = p.matcher(s);return m.matches();}// 取得AppKeypublic 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() != 24) {appKey = null;}}} catch (NameNotFoundException e) {}return appKey;}// 取得版本号public static String GetVersion(Context context) {try {PackageInfo manager = context.getPackageManager().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 telephonyManager = (TelephonyManager) context.getSystemService(Context.TELEPHONY_SERVICE);ret = telephonyManager.getDeviceId();} catch (Exception e) {Logger.e(ExampleUtil.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 = Patternpile("[\\x20-\\x7E]+");return p.matcher(string).matches();} catch (Throwable e){return true;}}public static String getDeviceId(Context context) {return JPushInterface.getUdid(context);}
}

处理tagalias相关的逻辑

package com.example.practice.jpush;import android.content.Context;
import android.os.Handler;
import android.os.Message;
import android.util.SparseArray;import java.util.Locale;
import java.util.Set;import cn.jpush.android.api.JPushInterface;
import cn.jpush.android.api.JPushMessage;/*** 处理tagalias相关的逻辑* */
public class TagAliasOperatorHelper {private static final String TAG = "JIGUANG-TagAliasHelper";public static int sequence = 1;/**增加*/public static final int ACTION_ADD = 1;/**覆盖*/public static final int ACTION_SET = 2;/**删除部分*/public static final int ACTION_DELETE = 3;/**删除所有*/public static final int ACTION_CLEAN = 4;/**查询*/public static final int ACTION_GET = 5;public static final int ACTION_CHECK = 6;public static final int DELAY_SEND_ACTION = 1;public static final int DELAY_SET_MOBILE_NUMBER_ACTION = 2;private Context context;private static TagAliasOperatorHelper mInstance;private TagAliasOperatorHelper(){}public static TagAliasOperatorHelper getInstance(){if(mInstance == null){synchronized (TagAliasOperatorHelper.class){if(mInstance == null){mInstance = new TagAliasOperatorHelper();}}}return mInstance;}public void init(Context context){if(context != null) {this.context = context.getApplicationContext();}}private SparseArray<Object> setActionCache = new SparseArray<Object>();public Object get(int sequence){return setActionCache.get(sequence);}public Object remove(int sequence){return setActionCache.get(sequence);}public void put(int sequence,Object tagAliasBean){setActionCache.put(sequence,tagAliasBean);}private Handler delaySendHandler = new Handler(){@Overridepublic void handleMessage(Message msg) {switch (msg.what){case DELAY_SEND_ACTION:if(msg.obj !=null && msg.obj instanceof  TagAliasBean){Logger.i(TAG,"on delay time");sequence++;TagAliasBean tagAliasBean = (TagAliasBean) msg.obj;setActionCache.put(sequence, tagAliasBean);if(context!=null) {handleAction(context, sequence, tagAliasBean);}else{Logger.e(TAG,"#unexcepted - context was null");}}else{Logger.w(TAG,"#unexcepted - msg obj was incorrect");}break;case DELAY_SET_MOBILE_NUMBER_ACTION:if(msg.obj !=null && msg.obj instanceof  String) {Logger.i(TAG, "retry set mobile number");sequence++;String mobileNumber = (String) msg.obj;setActionCache.put(sequence, mobileNumber);if(context !=null) {handleAction(context, sequence, mobileNumber);}else {Logger.e(TAG, "#unexcepted - context was null");}}else{Logger.w(TAG,"#unexcepted - msg obj was incorrect");}break;}}};public void handleAction(Context context,int sequence,String mobileNumber){put(sequence,mobileNumber);Logger.d(TAG,"sequence:"+sequence+",mobileNumber:"+mobileNumber);JPushInterface.setMobileNumber(context,sequence,mobileNumber);}/*** 处理设置tag* */public void handleAction(Context context,int sequence, TagAliasBean tagAliasBean){init(context);if(tagAliasBean == null){Logger.w(TAG,"tagAliasBean was null");return;}put(sequence,tagAliasBean);if(tagAliasBean.isAliasAction){switch (tagAliasBean.action){case ACTION_GET:JPushInterface.getAlias(context,sequence);break;case ACTION_DELETE:JPushInterface.deleteAlias(context,sequence);break;case ACTION_SET:JPushInterface.setAlias(context,sequence,tagAliasBean.alias);break;default:Logger.w(TAG,"unsupport alias action type");return;}}else {switch (tagAliasBean.action) {case ACTION_ADD:JPushInterface.addTags(context, sequence, tagAliasBean.tags);break;case ACTION_SET:JPushInterface.setTags(context, sequence, tagAliasBean.tags);break;case ACTION_DELETE:JPushInterface.deleteTags(context, sequence, tagAliasBean.tags);break;case ACTION_CHECK://一次只能check一个tagString tag = (String)tagAliasBean.tags.toArray()[0];JPushInterface.checkTagBindState(context,sequence,tag);break;case ACTION_GET:JPushInterface.getAllTags(context, sequence);break;case ACTION_CLEAN:JPushInterface.cleanTags(context, sequence);break;default:Logger.w(TAG,"unsupport tag action type");return;}}}private boolean RetryActionIfNeeded(int errorCode,TagAliasBean tagAliasBean){if(!ExampleUtil.isConnected(context)){Logger.w(TAG,"no network");return false;}//返回的错误码为6002 超时,6014 服务器繁忙,都建议延迟重试if(errorCode == 6002 || errorCode == 6014){Logger.d(TAG,"need retry");if(tagAliasBean!=null){Message message = new Message();message.what = DELAY_SEND_ACTION;message.obj = tagAliasBean;delaySendHandler.sendMessageDelayed(message,1000*60);String logs =getRetryStr(tagAliasBean.isAliasAction, tagAliasBean.action,errorCode);ExampleUtil.showToast(logs, context);return true;}}return false;}private boolean RetrySetMObileNumberActionIfNeeded(int errorCode,String mobileNumber){if(!ExampleUtil.isConnected(context)){Logger.w(TAG,"no network");return false;}//返回的错误码为6002 超时,6024 服务器内部错误,建议稍后重试if(errorCode == 6002 || errorCode == 6024){Logger.d(TAG,"need retry");Message message = new Message();message.what = DELAY_SET_MOBILE_NUMBER_ACTION;message.obj = mobileNumber;delaySendHandler.sendMessageDelayed(message,1000*60);String str = "Failed to set mobile number due to %s. Try again after 60s.";str = String.format(Locale.ENGLISH,str,(errorCode == 6002 ? "timeout" : "server internal error”"));ExampleUtil.showToast(str, context);return true;}return false;}private String getRetryStr(boolean isAliasAction,int actionType,int errorCode){String str = "Failed to %s %s due to %s. Try again after 60s.";str = String.format(Locale.ENGLISH,str,getActionStr(actionType),(isAliasAction? "alias" : " tags") ,(errorCode == 6002 ? "timeout" : "server too busy"));return str;}private String getActionStr(int actionType){switch (actionType){case ACTION_ADD:return "add";case ACTION_SET:return "set";case ACTION_DELETE:return "delete";case ACTION_GET:return "get";case ACTION_CLEAN:return "clean";case ACTION_CHECK:return "check";}return "unkonw operation";}public void onTagOperatorResult(Context context, JPushMessage jPushMessage) {int sequence = jPushMessage.getSequence();Logger.i(TAG,"action - onTagOperatorResult, sequence:"+sequence+",tags:"+jPushMessage.getTags());Logger.i(TAG,"tags size:"+jPushMessage.getTags().size());init(context);//根据sequence从之前操作缓存中获取缓存记录TagAliasBean tagAliasBean = (TagAliasBean)setActionCache.get(sequence);if(tagAliasBean == null){ExampleUtil.showToast("获取缓存记录失败", context);return;}if(jPushMessage.getErrorCode() == 0){Logger.i(TAG,"action - modify tag Success,sequence:"+sequence);setActionCache.remove(sequence);String logs = getActionStr(tagAliasBean.action)+" tags success";Logger.i(TAG,logs);ExampleUtil.showToast(logs, context);}else{String logs = "Failed to " + getActionStr(tagAliasBean.action)+" tags";if(jPushMessage.getErrorCode() == 6018){//tag数量超过限制,需要先清除一部分再addlogs += ", tags is exceed limit need to clean";}logs += ", errorCode:" + jPushMessage.getErrorCode();Logger.e(TAG, logs);if(!RetryActionIfNeeded(jPushMessage.getErrorCode(),tagAliasBean)) {ExampleUtil.showToast(logs, context);}}}public void onCheckTagOperatorResult(Context context, JPushMessage jPushMessage){int sequence = jPushMessage.getSequence();Logger.i(TAG,"action - onCheckTagOperatorResult, sequence:"+sequence+",checktag:"+jPushMessage.getCheckTag());init(context);//根据sequence从之前操作缓存中获取缓存记录TagAliasBean tagAliasBean = (TagAliasBean)setActionCache.get(sequence);if(tagAliasBean == null){ExampleUtil.showToast("获取缓存记录失败", context);return;}if(jPushMessage.getErrorCode() == 0){Logger.i(TAG,"tagBean:"+tagAliasBean);setActionCache.remove(sequence);String logs = getActionStr(tagAliasBean.action)+" tag "+jPushMessage.getCheckTag() + " bind state success,state:"+jPushMessage.getTagCheckStateResult();Logger.i(TAG,logs);ExampleUtil.showToast(logs, context);}else{String logs = "Failed to " + getActionStr(tagAliasBean.action)+" tags, errorCode:" + jPushMessage.getErrorCode();Logger.e(TAG, logs);if(!RetryActionIfNeeded(jPushMessage.getErrorCode(),tagAliasBean)) {ExampleUtil.showToast(logs, context);}}}public void onAliasOperatorResult(Context context, JPushMessage jPushMessage) {int sequence = jPushMessage.getSequence();Logger.i(TAG,"action - onAliasOperatorResult, sequence:"+sequence+",alias:"+jPushMessage.getAlias());init(context);//根据sequence从之前操作缓存中获取缓存记录TagAliasBean tagAliasBean = (TagAliasBean)setActionCache.get(sequence);if(tagAliasBean == null){ExampleUtil.showToast("获取缓存记录失败", context);return;}if(jPushMessage.getErrorCode() == 0){Logger.i(TAG,"action - modify alias Success,sequence:"+sequence);setActionCache.remove(sequence);String logs = getActionStr(tagAliasBean.action)+" alias success";Logger.i(TAG,logs);ExampleUtil.showToast(logs, context);}else{String logs = "Failed to " + getActionStr(tagAliasBean.action)+" alias, errorCode:" + jPushMessage.getErrorCode();Logger.e(TAG, logs);if(!RetryActionIfNeeded(jPushMessage.getErrorCode(),tagAliasBean)) {ExampleUtil.showToast(logs, context);}}}//设置手机号码回调public void onMobileNumberOperatorResult(Context context, JPushMessage jPushMessage) {int sequence = jPushMessage.getSequence();Logger.i(TAG,"action - onMobileNumberOperatorResult, sequence:"+sequence+",mobileNumber:"+jPushMessage.getMobileNumber());init(context);if(jPushMessage.getErrorCode() == 0){Logger.i(TAG,"action - set mobile number Success,sequence:"+sequence);setActionCache.remove(sequence);}else{String logs = "Failed to set mobile number, errorCode:" + jPushMessage.getErrorCode();Logger.e(TAG, logs);if(!RetrySetMObileNumberActionIfNeeded(jPushMessage.getErrorCode(),jPushMessage.getMobileNumber())){ExampleUtil.showToast(logs, context);}}}public static class TagAliasBean{int action;Set<String> tags;String alias;boolean isAliasAction;@Overridepublic String toString() {return "TagAliasBean{" +"action=" + action +", tags=" + tags +", alias='" + alias + '\'' +", isAliasAction=" + isAliasAction +'}';}}
}

本地广播管理器

package com.example.practice.jpush;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.ConnectivityManager;
import android.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;public class ExampleUtil {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;}/*** 只能以 “+” 或者 数字开头;后面的内容只能包含 “-” 和 数字。* */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 = Patternpile(MOBILE_NUMBER_CHARS);Matcher m = p.matcher(s);return m.matches();}// 校验Tag Alias 只能是数字,英文字母和中文public static boolean isValidTagAndAlias(String s) {Pattern p = Patternpile("^[\u4E00-\u9FA50-9a-zA-Z_!@#$&*+=.|]+$");Matcher m = p.matcher(s);return m.matches();}// 取得AppKeypublic 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() != 24) {appKey = null;}}} catch (NameNotFoundException e) {}return appKey;}// 取得版本号public static String GetVersion(Context context) {try {PackageInfo manager = context.getPackageManager().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 telephonyManager = (TelephonyManager) context.getSystemService(Context.TELEPHONY_SERVICE);ret = telephonyManager.getDeviceId();} catch (Exception e) {Logger.e(ExampleUtil.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 = Patternpile("[\\x20-\\x7E]+");return p.matcher(string).matches();} catch (Throwable e){return true;}}public static String getDeviceId(Context context) {return JPushInterface.getUdid(context);}
}

log工具类

package com.example.practice.jpush;import android.util.Log;/*** Created by efan on 2017/4/13.*/public class Logger {//设为false关闭日志private static final boolean LOG_ENABLE = true;public static void i(String tag, String msg){if (LOG_ENABLE){Log.i(tag, msg);}}public static void v(String tag, String msg){if (LOG_ENABLE){Log.v(tag, msg);}}public static void d(String tag, String msg){if (LOG_ENABLE){Log.d(tag, msg);}}public static void w(String tag, String msg){if (LOG_ENABLE){Log.w(tag, msg);}}public static void e(String tag, String msg){if (LOG_ENABLE){Log.e(tag, msg);}}}

更多推荐

Android 使用第三方SDK极光实现推送功能

本文发布于:2024-02-08 21:12:45,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1675105.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:极光   第三方   功能   Android   SDK

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!