天天看點

Android內建極光推送

1、先下載下傳極光SDK 

位址:https://docs.jiguang.cn/jpush/resources/

解壓後進入libs将jar複制到項目libs檔案夾下,main建立jniLibs檔案夾注意與java平級,将要依賴的so庫複制進去,也可同時放入libs下(注意jar右鍵Add As Library)

Android內建極光推送

也可以在Android項目中App下的build.gradle檔案中加入依賴(個人推薦這種方式)

Android內建極光推送

2、AndroidManifest清單檔案配置

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.helloworld.jpushdemo">

    <permission
        android:name="com.helloworld.jpushdemo.permission.JPUSH_MESSAGE"
        android:protectionLevel="signature" />

    <!-- 要求 -->
    <uses-permission android:name="android.permission.INTERNET"/>
    <uses-permission android:name="com.helloworld.jpushdemo.permission.JPUSH_MESSAGE" />
    <uses-permission android:name="android.permission.RECEIVE_USER_PRESENT" />
    <uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
    <uses-permission android:name="android.permission.WAKE_LOCK" />
    <uses-permission android:name="android.permission.VIBRATE" />
    <uses-permission android:name="android.permission.MOUNT_UNMOUNT_FILESYSTEMS" />
    <uses-permission android:name="android.permission.WRITE_SETTINGS" />
    <!-- 用于開啟 debug 版本的應用在6.0 系統上 層疊視窗權限 -->
    <uses-permission android:name="android.permission.SYSTEM_ALERT_WINDOW" />
    <uses-permission android:name="android.permission.CHANGE_NETWORK_STATE" />
    <uses-permission android:name="android.permission.REAL_GET_TASKS" />

    <application
        android:name=".MyAppaction"
        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/AppTheme">
        <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:authorities="com.helloworld.jpushdemo.DataProvider"
            android:name="cn.jpush.android.service.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.helloworld.jpushdemo"/>
            </intent-filter>
        </service>

        <!-- 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.helloworld.jpushdemo"/>
            </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:theme="@android:style/Theme.NoTitleBar"
            android:exported="false" >
            <intent-filter>
                <action android:name="cn.jpush.android.ui.PushActivity" />
                <category android:name="android.intent.category.DEFAULT" />
                <category android:name="com.helloworld.jpushdemo" />
            </intent-filter>
        </activity>

        <!-- Required SDK核心功能-->
        <receiver android:name="cn.jpush.android.service.AlarmReceiver" />

        <!-- Required since 3.0.7 -->
        <!-- 新的tag/alias接口結果傳回需要開發者配置一個自定的廣播 -->
        <!-- 該廣播需要繼承JPush提供的JPushMessageReceiver類, 并如下新增一個 Intent-Filter -->
        <receiver
            android:name=".MyJPushMessageReceiver"
            android:enabled="true" >
            <intent-filter>
                <action android:name="cn.jpush.android.intent.RECEIVE_MESSAGE" />
                <category android:name="com.helloworld.jpushdemo" />
            </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.helloworld.jpushdemo" />
            </intent-filter>
        </receiver>

        <!-- 設定 AppKey -->
        <meta-data android:name="JPUSH_APPKEY" android:value="b6fe630e2bce584839547ce0"/>

    </application>
</manifest>
           

提示:  

注意包名的更換,以及(AppKey)的替換

3、MyAppaction

package com.helloworld.jpushdemo;

import android.app.Application;
import cn.jpush.android.api.JPushInterface;

public class MyAppaction extends Application {

    @Override
    public void onCreate() {
        super.onCreate();
        //TODO: 設定開啟日志,釋出時請關閉日志
        JPushInterface.setDebugMode(false);
        //初始化極光推送
        JPushInterface.init(this);
    }
}
           

4、MyJPushMessageReceiver

package com.helloworld.jpushdemo;

import android.content.Context;
import android.util.Log;

import cn.jpush.android.api.JPushMessage;
import cn.jpush.android.service.JPushMessageReceiver;

/**
 * 狀态回調
 */

public class MyJPushMessageReceiver extends JPushMessageReceiver {

    private static final String TAG = "MyJPushMessageReceiver";

    /**
     * tag增删查改的操作會在此方法中回調結果
     */
    @Override
    public void onTagOperatorResult(Context context, JPushMessage jPushMessage) {
        super.onTagOperatorResult(context, jPushMessage);
        //下面2個回調類似
        Log.e(TAG, "onTagOperatorResult查詢得到的别名: " + jPushMessage.getAlias());
        Log.e(TAG, "onTagOperatorResult查詢得到的标簽: " + jPushMessage.getTags());
        Log.e(TAG, "onTagOperatorResult錯誤碼0為成功: " + jPushMessage.getErrorCode());
        Log.e(TAG, "onTagOperatorResult傳入的标示: " + jPushMessage.getSequence());
    }

    /**
     * 查詢某個tag與目前使用者的綁定狀态的操作會在此方法中回調結果
     */
    @Override
    public void onCheckTagOperatorResult(Context context, JPushMessage jPushMessage) {
        super.onCheckTagOperatorResult(context, jPushMessage);
        Log.e(TAG, "onCheckTagOperatorResult錯誤碼0為成功: " + jPushMessage.getErrorCode());
    }

    /**
     * alias相關的操作會在此方法中回調結果
     */
    @Override
    public void onAliasOperatorResult(Context context, JPushMessage jPushMessage) {
        super.onAliasOperatorResult(context, jPushMessage);
        Log.e(TAG, "onAliasOperatorResult錯誤碼0為成功: " + jPushMessage.getErrorCode());
    }
}
           

5、MyReceiver

package com.helloworld.jpushdemo;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.util.Log;

import cn.jpush.android.api.JPushInterface;

/**
 * 自定義廣播接收器
 */
public class MyReceiver extends BroadcastReceiver {

    private static final String TAG = "MyReceiver";

    @Override
    public void onReceive(Context context, Intent intent) {
        Bundle bundle = intent.getExtras();
        if (JPushInterface.ACTION_REGISTRATION_ID.equals(intent.getAction())) {

            String regId = bundle.getString(JPushInterface.EXTRA_REGISTRATION_ID);
            Log.e(TAG, "JPush使用者注冊成功id: " + regId);
        } else if (JPushInterface.ACTION_MESSAGE_RECEIVED.equals(intent.getAction())) {

            Log.e(TAG, "接受到推送下來的自定義消息id: " + bundle.getString(JPushInterface.EXTRA_MESSAGE));
        } else if (JPushInterface.ACTION_NOTIFICATION_RECEIVED.equals(intent.getAction())) {

            int notifactionId = bundle.getInt(JPushInterface.EXTRA_NOTIFICATION_ID);
            Log.e(TAG, "接受到推送下來的通知id: " + notifactionId);
        } else if (JPushInterface.ACTION_NOTIFICATION_OPENED.equals(intent.getAction())) {

//                Intent i = new Intent(context, TestActivity.class);
//                i.putExtras(bundle);
//                i.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
//                context.startActivity(i);
            Log.e(TAG, "使用者點選打開了通知跳轉的Activity: ");
        } else if (JPushInterface.ACTION_RICHPUSH_CALLBACK.equals(intent.getAction())) {

            Log.e(TAG, "onReceive: " + bundle.getString(JPushInterface.EXTRA_EXTRA));
        } else if (JPushInterface.ACTION_CONNECTION_CHANGE.equals(intent.getAction())) {
            boolean connected = intent.getBooleanExtra(JPushInterface.EXTRA_CONNECTION_CHANGE, false);

            Log.e(TAG, "onReceive: " + intent.getAction() + " 連接配接狀态變化 " + connected);
        } else {
            Log.e(TAG, "onReceive:  未處理的意圖- " + intent.getAction());
        }
    }
}
           

6、NotificationsUtils

package com.helloworld.jpushdemo;

import android.annotation.SuppressLint;
import android.app.AppOpsManager;
import android.content.Context;
import android.content.pm.ApplicationInfo;

import java.lang.reflect.Field;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;

/**
 * 判斷通知欄是否開啟
 */

public class NotificationsUtils {

    private static final String CHECK_OP_NO_THROW = "checkOpNoThrow";
    private static final String OP_POST_NOTIFICATION = "OP_POST_NOTIFICATION";

    @SuppressLint("NewApi")
    public static boolean isNotificationEnabled(Context context) {
        AppOpsManager mAppOps = (AppOpsManager) context.getSystemService(Context.APP_OPS_SERVICE);
        ApplicationInfo appInfo = context.getApplicationInfo();
        String pkg = context.getApplicationContext().getPackageName();
        int uid = appInfo.uid;
        Class appOpsClass = null;
        try {
            appOpsClass = Class.forName(AppOpsManager.class.getName());
            Method checkOpNoThrowMethod = appOpsClass.getMethod(CHECK_OP_NO_THROW, Integer.TYPE, Integer.TYPE, String.class);
            Field opPostNotificationValue = appOpsClass.getDeclaredField(OP_POST_NOTIFICATION);
            int value = (Integer) opPostNotificationValue.get(Integer.class);
            return ((Integer) checkOpNoThrowMethod.invoke(mAppOps, value, uid, pkg) == AppOpsManager.MODE_ALLOWED);
        } catch (ClassNotFoundException e) {
            e.printStackTrace();
        } catch (NoSuchMethodException e) {
            e.printStackTrace();
        } catch (NoSuchFieldException e) {
            e.printStackTrace();
        } catch (InvocationTargetException e) {
            e.printStackTrace();
        } catch (IllegalAccessException e) {
            e.printStackTrace();
        }
        return false;
    }
}
           

7、MainActivity

package com.helloworld.jpushdemo;

import android.content.Intent;
import android.provider.Settings;
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.JPushMessage;

/**
 * 文檔:https://docs.jiguang.cn/jpush/client/Android/android_api/
 */
public class MainActivity extends AppCompatActivity {

    private static final String TAG = "MainActivity";

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        if (NotificationsUtils.isNotificationEnabled(this)) {
            Log.e(TAG, "onCreate: 通知權限 已開啟");
            setBasicSetup(1);
            setBasicSetup(4);
        } else {
            Log.e(TAG, "onCreate: 通知權限 未開啟");
            //提示使用者去設定,跳轉到應用資訊界面
            Intent intent = new Intent(Settings.ACTION_SETTINGS);
            startActivity(intent);
        }
    }

    /**
     * 1-2-3-4
     * 增、删、改、查
     */
    public void setBasicSetup(int type) {
        if (type == 1) {
            //設定别名(新的調用會覆寫之前的設定)
            JPushInterface.setAlias(this, 0, "0x123");
            //設定标簽(同上)
            JPushInterface.setTags(this, 0, setUserTags());
        } else if (type == 2) {
            //删除别名
            JPushInterface.deleteAlias(this, 0);
            //删除指定标簽
            JPushInterface.deleteTags(this, 0, setUserTags());
            //删除所有标簽
            JPushInterface.cleanTags(this, 0);
        } else if (type == 3) {
            //增加tag使用者量(一般都是登入成功設定userid為目标,在别處新增加比較少見)
            JPushInterface.addTags(this, 0, setUserTags());
        } else if (type == 4) {
            //查詢所有标簽
            JPushInterface.getAllTags(this, 0);
            //查詢别名
            JPushInterface.getAlias(this, 0);
            //查詢指定tag與目前使用者綁定的狀态(MyJPushMessageReceiver擷取)
            JPushInterface.checkTagBindState(this, 0, "0x123");
            //擷取注冊id
            JPushInterface.getRegistrationID(this);
        }
    }

    /**
     * 标簽使用者
     */
    private static Set<String> setUserTags() {
        //添加3個标簽使用者(擷取登入userid較為常見)
        Set<String> tags = new HashSet<>();
        tags.add("0x123");
        tags.add("0x124");
        tags.add("0x125");
        return tags;
    }
}