一.在極光推送官網註冊賬號並創建項目(包名填寫自己項目的包名,並記錄 AppKey)
二.
1.根據官網提示,下載sdk包並放入工程(將下載的sdk解壓,複製libs裏面的文件到項目的libs目錄下)
build.gradle裏面增加
android { sourceSets { main { jniLibs.srcDirs = ['libs'] } } }
2.AndroidManifest.xml裏面配置權限(相應位置填寫自己的包名:)
<category android:name="com.example.jgpush"
<!-- Required --> <permission android:name="com.example.jgpush.permission.JPUSH_MESSAGE" android:protectionLevel="signature" />
<!-- Required 一些系統要求的權限,如訪問網絡等 --> <uses-permission android:name="com.example.jgpush.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.WAKE_LOCK" /> <uses-permission android:name="android.permission.READ_PHONE_STATE" /> <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" /> <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.MOUNT_UNMOUNT_FILESYSTEMS" /> <uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" /> <uses-permission android:name="android.permission.ACCESS_WIFI_STATE" /> <!-- Optional for location --> <uses-permission android:name="android.permission.SYSTEM_ALERT_WINDOW" /> <!-- 用於開啓 debug 版本的應用在6.0 系統上 層疊窗口權限 --> <uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" /> <uses-permission android:name="android.permission.CHANGE_WIFI_STATE" /> <uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" /> <uses-permission android:name="android.permission.ACCESS_LOCATION_EXTRA_COMMANDS" /> <uses-permission android:name="android.permission.CHANGE_NETWORK_STATE" /> <uses-permission android:name="android.permission.GET_TASKS" /> <application 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"> <activity android:name=".MainActivity"> <intent-filter> <action android:name="android.intent.action.MAIN" /> <category android:name="android.intent.category.LAUNCHER" /> </intent-filter> </activity> <!-- 核心功能 --> <!-- Required SDK 核心功能 --> <!-- 可配置android:process參數將PushService放在其他進程中 --> <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> <!-- since 3.0.9 Required SDK 核心功能 --> <provider android:name="cn.jpush.android.service.DataProvider" android:authorities="com.example.jgpush.DataProvider" android:exported="true" /> <!-- since 1.8.0 option 可選項。用於同一設備中不同應用的JPush服務相互拉起的功能。 --> <!-- 若不啓用該功能可刪除該組件,將不拉起其他應用也不能被其他應用拉起 --> <service android:name="cn.jpush.android.service.DaemonService" android:enabled="true" android:exported="true"> <intent-filter> <action android:name="cn.jpush.android.intent.DaemonService" /> <category android:name="com.example.jgpush" /> </intent-filter> </service> <!-- since 3.1.0 Required SDK 核心功能 --> <provider android:name="cn.jpush.android.service.DownloadProvider" android:authorities="com.example.jgpush.DownloadProvider" android:exported="true" /> <!-- 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" /> <category android:name="com.example.jgpush" /> </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核心功能 --> <activity android:name="cn.jpush.android.ui.PushActivity" android:configChanges="orientation|keyboardHidden" android:exported="false" android:theme="@android:style/Theme.NoTitleBar"> <intent-filter> <action android:name="cn.jpush.android.ui.PushActivity" /> <category android:name="android.intent.category.DEFAULT" /> <category android:name="com.example.jgpush" /> </intent-filter> </activity> <!-- SDK核心功能 --> <activity android:name="cn.jpush.android.ui.PopWinActivity" android:configChanges="orientation|keyboardHidden" android:exported="false" android:theme="@style/MyDialogStyle"> <intent-filter> <category android:name="android.intent.category.DEFAULT" /> <category android:name="com.example.jgpush" /> </intent-filter> </activity> <!-- Required SDK核心功能 --> <service android:name="cn.jpush.android.service.DownloadService" android:enabled="true" android:exported="false"></service> <!-- Required SDK核心功能 --> <receiver android:name="cn.jpush.android.service.AlarmReceiver" /> <!-- Required since 3.0.7 --> <!-- 新的tag/alias接口結果返回需要開發者配置一個自定的廣播 --> <!-- 該廣播需要繼承JPush提供的JPushMessageReceiver類, 並如下新增一個 Intent-Filter --> <!-- <receiver --> <!-- android:name="com.example.jgpush.MyReceiver" --> <!-- android:enabled="false" > --> <!-- <intent-filter> --> <!-- <action android:name="cn.jpush.android.intent.RECEIVE_MESSAGE" /> --> <!-- <category android:name="com.example.jgpush" /> --> <!-- </intent-filter> --> <!-- </receiver> --> <!-- User defined. 用戶自定義的廣播接收器 --> <receiver android:name=".MyReceiver" android:enabled="true"> <intent-filter> <!-- Required 用戶註冊SDK的intent --> <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 用戶打開自定義通知欄的intent --> <action android:name="cn.jpush.android.intent.NOTIFICATION_OPENED" /> <!-- 接收網絡變化 連接/斷開 since 1.6.3 --> <action android:name="cn.jpush.android.intent.CONNECTION" /> <category android:name="com.example.jgpush" /> </intent-filter> </receiver> <!-- Required. For publish channel feature --> <!-- JPUSH_CHANNEL 是爲了方便開發者統計APK分發渠道。 --> <!-- 例如: --> <!-- 發到 Google Play 的APK可以設置爲 google-play; --> <!-- 發到其他市場的 APK 可以設置爲 xxx-market。 --> <meta-data android:name="JPUSH_CHANNEL" android:value="developer-default" /> <!-- Required. AppKey copied from Portal --> <meta-data android:name="JPUSH_APPKEY" android:value="自己創建應用是的AppKey" /> <activity android:name=".TestActivity"></activity> </application>
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)); Iterator<String> it = 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<BroadcastReceiver, ArrayList<IntentFilter>> mReceivers = new HashMap<BroadcastReceiver, ArrayList<IntentFilter>>(); private final HashMap<String, ArrayList<ReceiverRecord>> mActions = new HashMap<String, ArrayList<ReceiverRecord>> (); private final ArrayList<BroadcastRecord> mPendingBroadcasts = new ArrayList<BroadcastRecord>(); 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<ReceiverRecord> receivers; BroadcastRecord(Intent _intent, ArrayList<ReceiverRecord> _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, Set<String> set) { // Log.e(TAG,"--i:"+i+",s:"+s); // } // }); //設置標籤tag Set<String> tagSet = new HashSet<>(); tagSet.add("abc"); tagSet.add("123"); JPushInterface.setTags(this, tagSet, new TagAliasCallback() { @Override public void gotResult(int i, String s, Set<String> 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(); }
}