# 監聽通知欄獲取支付寶到賬信息 監聽通知欄獲取支付寶到賬信息

監聽通知欄獲取支付寶到賬信息

[toc]

定義service

@SuppressLint("OverrideAbstract")
@RequiresApi(api = Build.VERSION_CODES.JELLY_BEAN_MR2)
public class PayReceiver extends NotificationListenerService {
    private static final String TAG = "lht";


    @Override
    public void onCreate() {
        super.onCreate();

    }

    @RequiresApi(api = Build.VERSION_CODES.KITKAT)
    @Override
    public void onNotificationPosted(StatusBarNotification sbn) {
//        Toast.makeText(this,"收到消息",Toast.LENGTH_SHORT).show();
        Notification notification = sbn.getNotification();
        if (notification == null) {
            return;
        }
        Bundle extras = notification.extras;
        if (extras != null) {
            //包名
            String pkg = sbn.getPackageName();
            // 獲取通知標題
            String title = extras.getString(Notification.EXTRA_TITLE, "");
            // 獲取通知內容
            String content = extras.getString(Notification.EXTRA_TEXT, "");
            Log.i(TAG, String.format("收到通知,包名:%s,標題:%s,內容:%s", pkg, title, content));
            //處理
            processOnReceive(pkg, title, content);
        }
    }
}

權限獲取


public class MainActivity extends AppCompatActivity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        if (!isNotificationListenerEnabled(this)){
            openNotificationListenSettings();
        }
        toggleNotificationListenerService();
//        startService(new Intent(this,PayReceiver.class));
    }

    //檢測通知監聽服務是否被授權
    public boolean isNotificationListenerEnabled(Context context) {
        Set<String> packageNames = NotificationManagerCompat.getEnabledListenerPackages(this);
        if (packageNames.contains(context.getPackageName())) {
            return true;
        }
        return false;
    }
    //打開通知監聽設置頁面
    public void openNotificationListenSettings() {
        try {
            Intent intent;
            if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.LOLLIPOP_MR1) {
                intent = new Intent(Settings.ACTION_NOTIFICATION_LISTENER_SETTINGS);
            } else {
                intent = new Intent("android.settings.ACTION_NOTIFICATION_LISTENER_SETTINGS");
            }
            startActivity(intent);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
    //把應用的NotificationListenerService實現類disable再enable,即可觸發系統rebind操作
    private void toggleNotificationListenerService() {
        PackageManager pm = getPackageManager();
        pm.setComponentEnabledSetting(
                new ComponentName(this, PayReceiver.class),
                PackageManager.COMPONENT_ENABLED_STATE_DISABLED, PackageManager.DONT_KILL_APP);

        pm.setComponentEnabledSetting(
                new ComponentName(this, PayReceiver.class),
                PackageManager.COMPONENT_ENABLED_STATE_ENABLED, PackageManager.DONT_KILL_APP);
    }

}
    <application

        android:name=".ReceiverApplication"
        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>
        <service
            android:name=".PayReceiver"
            android:permission="android.permission.BIND_NOTIFICATION_LISTENER_SERVICE">
            <intent-filter>
                <action android:name="android.service.notification.NotificationListenerService" />
            </intent-filter>
        </service>
    </application>

數據整理

    /**
     * 解析內容字符串,提取金額
     *
     * @param content
     * @return
     */
    private static String parseMoney(String content) {
        Pattern pattern = Pattern.compile("付款(([1-9]\\d*)|0)(\\.(\\d){0,2})?元");
        Matcher matcher = pattern.matcher(content);
        if (matcher.find()) {
            String tmp = matcher.group();
            Pattern patternnum = Pattern.compile("(([1-9]\\d*)|0)(\\.(\\d){0,2})?");
            Matcher matchernum = patternnum.matcher(tmp);
            if (matchernum.find())
                return matchernum.group();
        }
        return null;
    }

    /**
     * 驗證消息的合法性,防止非官方消息被處理
     *
     * @param title
     * @param content
     * @param gateway
     * @return
     */
    private static boolean checkMsgValid(String title, String content, String gateway) {
        if ("wxpay".equals(gateway)) {
            //微信支付的消息格式
            //1條:標題:微信支付,內容:微信支付收款0.01元(朋友到店)
            //多條:標題:微信支付,內容:[4條]微信支付: 微信支付收款1.01元(朋友到店)
            Pattern pattern = Pattern.compile("^((\\[\\+?\\d+條])?微信支付:|微信支付收款)");
            Matcher matcher = pattern.matcher(content);
            return "微信支付".equals(title) && matcher.find();
        } else if ("alipay".equals(gateway)) {
            //支付寶的消息格式,標題:支付寶通知,內容:支付寶成功收款1.00元。
            return "收錢碼".equals(title);
        }
        return false;
    }

    /**
     * 提取字符串中的數字
     * @param strInput
     * @return
     */
    public static String getNum(String strInput) {
        //匹配指定範圍內的數字
        String regEx = "[^0-9]";
        //Pattern是一個正則表達式經編譯後的表現模式
        Pattern p = Pattern.compile(regEx);
        // 一個Matcher對象是一個狀態機器,它依據Pattern對象做爲匹配模式對字符串展開匹配檢查。
        Matcher m = p.matcher(strInput);
        //將輸入的字符串中非數字部分用空格取代並存入一個字符串
        String string = m.replaceAll(" ").trim();
        //以空格爲分割符在講數字存入一個字符串數組中
        String[] strArr = string.split(" ");
        StringBuffer stringBuffer = new StringBuffer();
        //遍歷數組轉換數據類型輸出
        for (String s : strArr) {
            stringBuffer.append(s);
            System.out.println(Integer.parseInt(s));
        }
        String num = stringBuffer.toString();
        System.out.println("num is " + num);
        return num;
    }

完整代碼

package com.ly.paycallback;

import android.annotation.SuppressLint;
import android.app.Notification;
import android.os.Build;
import android.os.Bundle;
import android.service.notification.NotificationListenerService;
import android.service.notification.StatusBarNotification;
import android.text.TextUtils;
import android.util.Log;
import android.widget.Toast;

import androidx.annotation.RequiresApi;

import java.util.regex.Matcher;
import java.util.regex.Pattern;

@SuppressLint("OverrideAbstract")
@RequiresApi(api = Build.VERSION_CODES.JELLY_BEAN_MR2)
public class PayReceiver extends NotificationListenerService {
    private static final String TAG = "lht";


    @Override
    public void onCreate() {
        super.onCreate();

    }

    @RequiresApi(api = Build.VERSION_CODES.KITKAT)
    @Override
    public void onNotificationPosted(StatusBarNotification sbn) {
//        Toast.makeText(this,"收到消息",Toast.LENGTH_SHORT).show();
        Notification notification = sbn.getNotification();
        if (notification == null) {
            return;
        }
        Bundle extras = notification.extras;
        if (extras != null) {
            //包名
            String pkg = sbn.getPackageName();
            // 獲取通知標題
            String title = extras.getString(Notification.EXTRA_TITLE, "");
            // 獲取通知內容
            String content = extras.getString(Notification.EXTRA_TEXT, "");
            Log.i(TAG, String.format("收到通知,包名:%s,標題:%s,內容:%s", pkg, title, content));
            //處理
            processOnReceive(pkg, title, content);
        }
    }

    /**
     * 消息來時處理
     *
     * @param pkg
     * @param title
     * @param content
     */
    private void processOnReceive(String pkg, String title, String content) {
//        Toast.makeText(this,"收到消息",Toast.LENGTH_SHORT).show();
//        if (!AppConstants.LISTEN_RUNNING) {
//            return;
//        }
        if ("com.eg.android.AlipayGphone".equals(pkg)) {
            //支付寶
            if (checkMsgValid(title, content, "alipay") && !TextUtils.isEmpty(parseMoney(content))) {
                Toast.makeText(this,content,Toast.LENGTH_SHORT).show();
                Toast.makeText(this,getNum(content),Toast.LENGTH_SHORT).show();

//                TreeMap<String, String> paramMap = new TreeMap<>();
//                paramMap.put("title", title);
//                paramMap.put("content", content);
//                paramMap.put("identifier", AppConstants.CLIENT_IDENTIFIER);
//                paramMap.put("orderid", CommonUtils.randomCharSeq());
//                paramMap.put("gateway", "alipay");
//                String sign = CommonUtils.calcSign(paramMap, AppConstants.SIGN_KEY);
//                if (StringUtils.isBlank(sign)) {
//                    Log.e(TAG, "簽名錯誤");
//                    return;
//                }
//                HttpTask task = new HttpTask();
//                task.setOnAsyncResponse(this);
//                String json = new Gson().toJson(paramMap);
//                task.execute(AppConstants.POST_URL, "sign=" + sign, json);

            }
        } else if ("com.tencent.mm".equals(pkg)) {
            //微信
            if (checkMsgValid(title, content, "wxpay") && !TextUtils.isEmpty(parseMoney(content))) {
                Toast.makeText(this,content,Toast.LENGTH_SHORT).show();
//                TreeMap<String, String> paramMap = new TreeMap<>();
//                paramMap.put("title", title);
//                paramMap.put("content", content);
//                paramMap.put("identifier", AppConstants.CLIENT_IDENTIFIER);
//                paramMap.put("orderid", CommonUtils.randomCharSeq());
//                paramMap.put("gateway", "wxpay");
//                String sign = CommonUtils.calcSign(paramMap, AppConstants.SIGN_KEY);
//                if (StringUtils.isBlank(sign)) {
//                    Log.e(TAG, "簽名錯誤");
//                    return;
//                }
//                HttpTask task = new HttpTask();
//                task.setOnAsyncResponse(this);
//                String json = new Gson().toJson(paramMap);
//                task.execute(AppConstants.POST_URL, "sign=" + sign, json);
            }
        }
    }

    /**
     * 解析內容字符串,提取金額
     *
     * @param content
     * @return
     */
    private static String parseMoney(String content) {
        Pattern pattern = Pattern.compile("付款(([1-9]\\d*)|0)(\\.(\\d){0,2})?元");
        Matcher matcher = pattern.matcher(content);
        if (matcher.find()) {
            String tmp = matcher.group();
            Pattern patternnum = Pattern.compile("(([1-9]\\d*)|0)(\\.(\\d){0,2})?");
            Matcher matchernum = patternnum.matcher(tmp);
            if (matchernum.find())
                return matchernum.group();
        }
        return null;
    }

    /**
     * 驗證消息的合法性,防止非官方消息被處理
     *
     * @param title
     * @param content
     * @param gateway
     * @return
     */
    private static boolean checkMsgValid(String title, String content, String gateway) {
        if ("wxpay".equals(gateway)) {
            //微信支付的消息格式
            //1條:標題:微信支付,內容:微信支付收款0.01元(朋友到店)
            //多條:標題:微信支付,內容:[4條]微信支付: 微信支付收款1.01元(朋友到店)
            Pattern pattern = Pattern.compile("^((\\[\\+?\\d+條])?微信支付:|微信支付收款)");
            Matcher matcher = pattern.matcher(content);
            return "微信支付".equals(title) && matcher.find();
        } else if ("alipay".equals(gateway)) {
            //支付寶的消息格式,標題:支付寶通知,內容:支付寶成功收款1.00元。
            return "收錢碼".equals(title);
        }
        return false;
    }

    /**
     * 提取字符串中的數字
     * @param strInput
     * @return
     */
    public static String getNum(String strInput) {
        //匹配指定範圍內的數字
        String regEx = "[^0-9]";
        //Pattern是一個正則表達式經編譯後的表現模式
        Pattern p = Pattern.compile(regEx);
        // 一個Matcher對象是一個狀態機器,它依據Pattern對象做爲匹配模式對字符串展開匹配檢查。
        Matcher m = p.matcher(strInput);
        //將輸入的字符串中非數字部分用空格取代並存入一個字符串
        String string = m.replaceAll(" ").trim();
        //以空格爲分割符在講數字存入一個字符串數組中
        String[] strArr = string.split(" ");
        StringBuffer stringBuffer = new StringBuffer();
        //遍歷數組轉換數據類型輸出
        for (String s : strArr) {
            stringBuffer.append(s);
            System.out.println(Integer.parseInt(s));
        }
        String num = stringBuffer.toString();
        System.out.println("num is " + num);
        return num;
    }
    private static String getMoney(String str) {
        Pattern pattern = Pattern.compile("[0-9|-|+|.]");  // 因爲金額中有小數點,有可能是增加的錢,也可能是減少的錢
        Matcher matcher = pattern.matcher(str);
        StringBuilder sb = new StringBuilder();
        while(matcher.find()) {
            sb.append(matcher.find());
        }
        return sb.toString();
    }
}
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章