1. 程式人生 > >JPush 鐳射推送 接收通知和自定義訊息

JPush 鐳射推送 接收通知和自定義訊息

一.在極光推送官網註冊賬號並建立專案(包名填寫自己專案的包名,並記錄 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;
<