一.在极光推送官网注册账号并创建项目(包名填写自己项目的包名,并记录 AppKey)
二.
1.根据官网提示,下载sdk包并放入工程(将下载的sdk解压,复制libs里面的文件到项目的libs目录下)
build.gradle里面增加
android { sourceSets { main { jniLibs.srcDirs = ['libs'] } } }
2.AndroidManifest.xml里面配置权限(相应位置填写自己的包名:)
android:name="com.example.jgpush"
android:name="com.example.jgpush.permission.JPUSH_MESSAGE" android:protectionLevel="signature" />
android:name="com.example.jgpush.permission.JPUSH_MESSAGE" /> android:name="android.permission.RECEIVE_USER_PRESENT" /> android:name="android.permission.INTERNET" /> android:name="android.permission.WAKE_LOCK" /> android:name="android.permission.READ_PHONE_STATE" /> android:name="android.permission.WRITE_EXTERNAL_STORAGE" /> android:name="android.permission.READ_EXTERNAL_STORAGE" /> android:name="android.permission.WRITE_SETTINGS" /> android:name="android.permission.VIBRATE" /> android:name="android.permission.MOUNT_UNMOUNT_FILESYSTEMS" /> android:name="android.permission.ACCESS_NETWORK_STATE" /> android:name="android.permission.ACCESS_WIFI_STATE" /> android:name="android.permission.SYSTEM_ALERT_WINDOW" /> android:name="android.permission.ACCESS_COARSE_LOCATION" /> android:name="android.permission.CHANGE_WIFI_STATE" /> android:name="android.permission.ACCESS_FINE_LOCATION" /> android:name="android.permission.ACCESS_LOCATION_EXTRA_COMMANDS" /> android:name="android.permission.CHANGE_NETWORK_STATE" /> android:name="android.permission.GET_TASKS" /> android:name=".App" android:allowBackup="true" android:icon="@mipmap/ic_launcher" android:label="@string/app_name" android:roundIcon="@mipmap/ic_launcher_round" android:supportsRtl="true" android:theme="@style/Theme.AppCompat.Light.NoActionBar"> android:name=".MainActivity"> android:name="android.intent.action.MAIN" /> android:name="android.intent.category.LAUNCHER" /> android:name="cn.jpush.android.service.PushService" android:enabled="true" android:exported="false"> android:name="cn.jpush.android.intent.REGISTER" /> android:name="cn.jpush.android.intent.REPORT" /> android:name="cn.jpush.android.intent.PushService" /> android:name="cn.jpush.android.intent.PUSH_TIME" /> android:name="cn.jpush.android.service.DataProvider" android:authorities="com.example.jgpush.DataProvider" android:exported="true" /> android:name="cn.jpush.android.service.DaemonService" android:enabled="true" android:exported="true"> android:name="cn.jpush.android.intent.DaemonService" /> android:name="com.example.jgpush" /> android:name="cn.jpush.android.service.DownloadProvider" android:authorities="com.example.jgpush.DownloadProvider" android:exported="true" /> android:name="cn.jpush.android.service.PushReceiver" android:enabled="true"> android:priority="1000"> android:name="cn.jpush.android.intent.NOTIFICATION_RECEIVED_PROXY" /> android:name="com.example.jgpush" /> android:name="android.intent.action.USER_PRESENT" /> android:name="android.net.conn.CONNECTIVITY_CHANGE" /> android:name="android.intent.action.PACKAGE_ADDED" /> android:name="android.intent.action.PACKAGE_REMOVED" /> android:scheme="package" /> android:name="cn.jpush.android.ui.PushActivity" android:configChanges="orientation|keyboardHidden" android:exported="false" android:theme="@android:style/Theme.NoTitleBar"> android:name="cn.jpush.android.ui.PushActivity" /> android:name="android.intent.category.DEFAULT" /> android:name="com.example.jgpush" /> android:name="cn.jpush.android.ui.PopWinActivity" android:configChanges="orientation|keyboardHidden" android:exported="false" android:theme="@style/MyDialogStyle"> android:name="android.intent.category.DEFAULT" /> android:name="com.example.jgpush" /> android:name="cn.jpush.android.service.DownloadService" android:enabled="true" android:exported="false"> android:name="cn.jpush.android.service.AlarmReceiver" /> android:name=".MyReceiver" android:enabled="true"> android:name="cn.jpush.android.intent.REGISTRATION" /> android:name="cn.jpush.android.intent.MESSAGE_RECEIVED" /> android:name="cn.jpush.android.intent.NOTIFICATION_RECEIVED" /> android:name="cn.jpush.android.intent.NOTIFICATION_OPENED" /> android:name="cn.jpush.android.intent.CONNECTION" /> android:name="com.example.jgpush" /> android:name="JPUSH_CHANNEL" android:value="developer-default" /> android:name="JPUSH_APPKEY" android:value="自己创建应用是的AppKey" /> android:name=".TestActivity">
3.在此类初始化
package com.example.jgpush; import android.app.Application; import android.util.Log; import java.util.Set; import cn.jpush.android.api.JPushInterface; import cn.jpush.android.api.TagAliasCallback; /** * Created by issuser on 2018/3/19. */ public class App extends Application { public static final String TAG = "TEST_JPUSH"; @Override public void onCreate() { Log.e(TAG,"-----onCreate"); super.onCreate(); JPushInterface.setDebugMode(true); // 设置开启日志,发布时请关闭日志 JPushInterface.init(this); //初始化 } }
4.自定义Receiver(不自定义receiver时,在极光推送官网发送通知手机也可以收到),对通知做处理
package com.example.jgpush; import android.content.BroadcastReceiver; import android.content.Context; import android.content.Intent; import android.os.Bundle; import android.util.Log; import org.json.JSONObject; import java.util.Iterator; import cn.jpush.android.api.JPushInterface; /** * 如果不自定义Receiver,则 * 1)默认用户打开主界面 * 2)接收不到自定义消息(通知了没有显示) */ /** * Created by issuser on 2018/3/19. */ public class MyReceiver extends BroadcastReceiver { public static final String TAG = "MyReceiver"; @Override public void onReceive(Context context, Intent intent) { Bundle bundle = intent.getExtras(); Log.e(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.e(TAG, "--[MyReceiver] 接收Registration Id :" + regId); //send the Registration Id to your server... } else if (JPushInterface.ACTION_MESSAGE_RECEIVED.equals(intent.getAction())) { Log.e(TAG, "--[MyReceiver] 接收到推送下来的自定义消息:" + bundle.getString(JPushInterface.EXTRA_MESSAGE)); processCustomMessage(context, bundle); }else if (JPushInterface.ACTION_NOTIFICATION_RECEIVED.equals(intent.getAction())){ Log.e(TAG,"----接收到推送下来的通知"); //todo int notificationId = bundle.getInt(JPushInterface.EXTRA_NOTIFICATION_ID); Log.e(TAG,"----接收到推送下来的通知ID:"+notificationId); }else if (JPushInterface.ACTION_NOTIFICATION_OPENED.equals(intent.getAction())){ Log.e(TAG,"----用户点击了通知"); //点击通知后,打开自定义页面 Intent intent1 = new Intent(context,TestActivity.class); intent1.putExtras(bundle); intent1.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TOP); context.startActivity(intent1); }else if (JPushInterface.ACTION_RICHPUSH_CALLBACK.equals(intent.getAction())) { Log.e(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()); } } //send message to mainActivity private void processCustomMessage(Context context, Bundle bundle) { //取出自定义消息内容(自定义消息手机上不显示通知) String message = bundle.getString(JPushInterface.EXTRA_MESSAGE); String extras = bundle.getString(JPushInterface.EXTRA_EXTRA); Log.e(TAG,"--message:"+message+"\nextras:"+extras); if (MainActivity.isForeground) { Intent intent = new Intent(MainActivity.MESSAGE_RECEIVED_ACTION); intent.putExtra(MainActivity.KEY_MESSAGE, message); if (!ExampleUtil.isEmpty(extras)) { try { JSONObject jsonObject = new JSONObject(extras); if (jsonObject.length() > 0) { intent.putExtra(MainActivity.KEY_EXTRAS, extras); } } catch (Exception e) { e.printStackTrace(); } } LocalBroadcastManager.getInstance(context).sendBroadcast(intent); } } //打印所有intent extras 数据 private String printBundle(Bundle bundle) { StringBuilder sb = new StringBuilder(); for (String key : bundle.keySet()) { if (key.equals(JPushInterface.EXTRA_NOTIFICATION_ID)) { Log.e(TAG, "----收到通知"); sb.append("\nkey:" + key + ",value:" + bundle.getInt(key)); } else if (key.equals(JPushInterface.EXTRA_CONNECTION_CHANGE)) { Log.e(TAG, "----网络发生变化"); sb.append("\nkey:" + key + ",value:" + bundle.getBoolean(key)); } else if (key.equals(JPushInterface.EXTRA_EXTRA)) { Log.e(TAG, "----This message has no Extra data"); try { JSONObject json = new JSONObject(bundle.getString(JPushInterface.EXTRA_EXTRA)); Iteratorit = json.keys(); while (it.hasNext()) { String myKey = it.next(); sb.append("\nkey:" + key + ",value:[" + myKey + "-" + json.optString(myKey) + "]"); } } catch (Exception e) { Log.e(TAG, "Get message extra JSON error!"); } } else { sb.append("\nkey:" + key + ",value:" + bundle.getString(key)); } } return sb.toString(); } }
5.两个工具类,官方demo里面的
package com.example.jgpush; import android.content.BroadcastReceiver; import android.content.Context; import android.content.Intent; import android.content.IntentFilter; import android.net.Uri; import android.os.Handler; import android.os.Message; import android.util.Log; import java.util.ArrayList; import java.util.HashMap; import java.util.Set; /** * Created by efan on 2017/4/14. */ public final class LocalBroadcastManager { private static final String TAG = "JIGUANG-Example"; private static final boolean DEBUG = false; private final Context mAppContext; private final HashMap, ArrayList > mReceivers = new HashMap , ArrayList >(); private final HashMap , ArrayList > mActions = new HashMap , ArrayList > (); private final ArrayList mPendingBroadcasts = new ArrayList (); static final int MSG_EXEC_PENDING_BROADCASTS = 1; private final Handler mHandler; private static final Object mLock = new Object(); private static LocalBroadcastManager mInstance; public static LocalBroadcastManager getInstance(Context context) { Object var1 = mLock; synchronized (mLock) { if (mInstance == null) { mInstance = new LocalBroadcastManager(context.getApplicationContext()); } return mInstance; } } private LocalBroadcastManager(Context context) { this.mAppContext = context; this.mHandler = new Handler(context.getMainLooper()) { public void handleMessage(Message msg) { switch (msg.what) { case 1: LocalBroadcastManager.this.executePendingBroadcasts(); break; default: super.handleMessage(msg); } } }; } public void registerReceiver(BroadcastReceiver receiver, IntentFilter filter) { HashMap var3 = this.mReceivers; synchronized (this.mReceivers) { ReceiverRecord entry = new ReceiverRecord(filter, receiver); ArrayList filters = (ArrayList) this.mReceivers.get(receiver); if (filters == null) { filters = new ArrayList(1); this.mReceivers.put(receiver, filters); } filters.add(filter); for (int i = 0; i < filter.countActions(); ++i) { String action = filter.getAction(i); ArrayList entries = (ArrayList) this.mActions.get(action); if (entries == null) { entries = new ArrayList(1); this.mActions.put(action, entries); } entries.add(entry); } } } public void unregisterReceiver(BroadcastReceiver receiver) { HashMap var2 = this.mReceivers; synchronized (this.mReceivers) { ArrayList filters = (ArrayList) this.mReceivers.remove(receiver); if (filters != null) { for (int i = 0; i < filters.size(); ++i) { IntentFilter filter = (IntentFilter) filters.get(i); for (int j = 0; j < filter.countActions(); ++j) { String action = filter.getAction(j); ArrayList receivers = (ArrayList) this.mActions.get(action); if (receivers != null) { for (int k = 0; k < receivers.size(); ++k) { if (((ReceiverRecord) receivers.get(k)).receiver == receiver) { receivers.remove(k); --k; } } if (receivers.size() <= 0) { this.mActions.remove(action); } } } } } } } public boolean sendBroadcast(Intent intent) { HashMap var2 = this.mReceivers; synchronized (this.mReceivers) { String action = intent.getAction(); String type = intent.resolveTypeIfNeeded(this.mAppContext.getContentResolver()); Uri data = intent.getData(); String scheme = intent.getScheme(); Set categories = intent.getCategories(); boolean debug = (intent.getFlags() & 8) != 0; if (debug) { Log.v("LocalBroadcastManager", "Resolving type " + type + " scheme " + scheme + " of intent " + intent); } ArrayList entries = (ArrayList) this.mActions.get(intent.getAction()); if (entries != null) { if (debug) { Log.v("LocalBroadcastManager", "Action list: " + entries); } ArrayList receivers = null; int i; for (i = 0; i < entries.size(); ++i) { ReceiverRecord receiver = (ReceiverRecord) entries.get(i); if (debug) { Log.v("LocalBroadcastManager", "Matching against filter " + receiver.filter); } if (receiver.broadcasting) { if (debug) { Log.v("LocalBroadcastManager", " Filter\'s target already added"); } } else { int match = receiver.filter.match(action, type, scheme, data, categories, "LocalBroadcastManager"); if (match >= 0) { if (debug) { Log.v("LocalBroadcastManager", " Filter matched! match=0x" + Integer.toHexString(match)); } if (receivers == null) { receivers = new ArrayList(); } receivers.add(receiver); receiver.broadcasting = true; } else if (debug) { String reason; switch (match) { case -4: reason = "category"; break; case -3: reason = "action"; break; case -2: reason = "data"; break; case -1: reason = "type"; break; default: reason = "unknown reason"; } Log.v("LocalBroadcastManager", " Filter did not match: " + reason); } } } if (receivers != null) { for (i = 0; i < receivers.size(); ++i) { ((ReceiverRecord) receivers.get(i)).broadcasting = false; } this.mPendingBroadcasts.add(new BroadcastRecord(intent, receivers)); if (!this.mHandler.hasMessages(1)) { this.mHandler.sendEmptyMessage(1); } return true; } } return false; } } public void sendBroadcastSync(Intent intent) { if (this.sendBroadcast(intent)) { this.executePendingBroadcasts(); } } private void executePendingBroadcasts() { while (true) { BroadcastRecord[] brs = null; HashMap i = this.mReceivers; synchronized (this.mReceivers) { int br = this.mPendingBroadcasts.size(); if (br <= 0) { return; } brs = new BroadcastRecord[br]; this.mPendingBroadcasts.toArray(brs); this.mPendingBroadcasts.clear(); } for (int var6 = 0; var6 < brs.length; ++var6) { BroadcastRecord var7 = brs[var6]; for (int j = 0; j < var7.receivers.size(); ++j) { ((ReceiverRecord) var7.receivers.get(j)).receiver.onReceive(this.mAppContext, var7.intent); } } } } private static class BroadcastRecord { final Intent intent; final ArrayList receivers; BroadcastRecord(Intent _intent, ArrayList _receivers) { this.intent = _intent; this.receivers = _receivers; } } private static class ReceiverRecord { final IntentFilter filter; final BroadcastReceiver receiver; boolean broadcasting; ReceiverRecord(IntentFilter _filter, BroadcastReceiver _receiver) { this.filter = _filter; this.receiver = _receiver; } public String toString() { StringBuilder builder = new StringBuilder(128); builder.append("Receiver{"); builder.append(this.receiver); builder.append(" filter="); builder.append(this.filter); builder.append("}"); return builder.toString(); } } }
package com.example.jgpush; import android.annotation.SuppressLint; 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.util.Log; import android.widget.Toast; import java.util.logging.Logger; 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 = Pattern.compile(MOBILE_NUMBER_CHARS); Matcher m = p.matcher(s); return m.matches(); } // 校验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(); } // 取得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() != 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() { @Override public 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()); } @SuppressLint("MissingPermission") 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) { Log.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 = Pattern.compile("[\\x20-\\x7E]+"); return p.matcher(string).matches(); } catch (Throwable e){ return true; } } public static String getDeviceId(Context context) { return JPushInterface.getUdid(context); } }
此时可以收取通知和自定义消息------------------------------------------------end
三.MainActivity
设置别名和标签的方法(发送通知时可以选择,即有这个标签或别名的人才会收到通知)
package com.example.jgpush; import android.content.Intent; import android.support.v7.app.AppCompatActivity; import android.os.Bundle; import android.util.Log; import java.util.HashSet; import java.util.Set; import cn.jpush.android.api.JPushInterface; import cn.jpush.android.api.TagAliasCallback; public class MainActivity extends AppCompatActivity { public static final String TAG = "MainActivity"; public static boolean isForeground = false; public static final String MESSAGE_RECEIVED_ACTION = "com.example.jgpush.MESSAGE_RECEIVED_ACTION"; public static final String KEY_TITLE = "title"; public static final String KEY_MESSAGE = "message"; public static final String KEY_EXTRAS = "extras"; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); // Log.e(TAG,"---"+s.length()); //设置别名 // JPushInterface.setAlias(this, "adc", new TagAliasCallback() { // @Override // public void gotResult(int i, String s, Setset) { // Log.e(TAG,"--i:"+i+",s:"+s); // } // }); //设置标签tag SettagSet = new HashSet<>(); tagSet.add("abc"); tagSet.add("123"); JPushInterface.setTags(this, tagSet, new TagAliasCallback() { @Override public void gotResult(int i, String s, Set set) { Log.e(TAG,"--设置标签returnCode:"+i+",s:"+s); } }); } //可以在主页对自定义消息做处理
MessageReceiver mMessageReceiver; public void registerMessageReceiver() { mMessageReceiver = new MessageReceiver(); IntentFilter filter = new IntentFilter(); filter.setPriority(IntentFilter.SYSTEM_HIGH_PRIORITY); filter.addAction(MESSAGE_RECEIVED_ACTION); LocalBroadcastManager.getInstance(this).registerReceiver(mMessageReceiver, filter); } public class MessageReceiver extends BroadcastReceiver { @Override public void onReceive(Context context, Intent intent) { try { if (MESSAGE_RECEIVED_ACTION.equals(intent.getAction())) { String messge = intent.getStringExtra(KEY_MESSAGE); String extras = intent.getStringExtra(KEY_EXTRAS); StringBuilder showMsg = new StringBuilder(); Log.e(TAG,"[MainActivity]---message:"+messge);//自定义消息内容 if (!ExampleUtil.isEmpty(extras)) { } } } catch (Exception e){ } } } @Override protected void onResume() { isForeground = true; super.onResume(); } @Override protected void onPause() { isForeground = false; super.onPause(); } @Override protected void onDestroy() { LocalBroadcastManager.getInstance(this).unregisterReceiver(mMessageReceiver); super.onDestroy(); }