# 监听通知栏获取支付宝到账信息

监听通知栏获取支付宝到账信息

[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();
    }
}
©著作权归作者所有,转载或内容合作请联系作者
  • 序言:七十年代末,一起剥皮案震惊了整个滨河市,随后出现的几起案子,更是在滨河造成了极大的恐慌,老刑警刘岩,带你破解...
    沈念sama阅读 217,277评论 6 503
  • 序言:滨河连续发生了三起死亡事件,死亡现场离奇诡异,居然都是意外死亡,警方通过查阅死者的电脑和手机,发现死者居然都...
    沈念sama阅读 92,689评论 3 393
  • 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
    开封第一讲书人阅读 163,624评论 0 353
  • 文/不坏的土叔 我叫张陵,是天一观的道长。 经常有香客问我,道长,这世上最难降的妖魔是什么? 我笑而不...
    开封第一讲书人阅读 58,356评论 1 293
  • 正文 为了忘掉前任,我火速办了婚礼,结果婚礼上,老公的妹妹穿的比我还像新娘。我一直安慰自己,他们只是感情好,可当我...
    茶点故事阅读 67,402评论 6 392
  • 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
    开封第一讲书人阅读 51,292评论 1 301
  • 那天,我揣着相机与录音,去河边找鬼。 笑死,一个胖子当着我的面吹牛,可吹牛的内容都是我干的。 我是一名探鬼主播,决...
    沈念sama阅读 40,135评论 3 418
  • 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
    开封第一讲书人阅读 38,992评论 0 275
  • 序言:老挝万荣一对情侣失踪,失踪者是张志新(化名)和其女友刘颖,没想到半个月后,有当地人在树林里发现了一具尸体,经...
    沈念sama阅读 45,429评论 1 314
  • 正文 独居荒郊野岭守林人离奇死亡,尸身上长有42处带血的脓包…… 初始之章·张勋 以下内容为张勋视角 年9月15日...
    茶点故事阅读 37,636评论 3 334
  • 正文 我和宋清朗相恋三年,在试婚纱的时候发现自己被绿了。 大学时的朋友给我发了我未婚夫和他白月光在一起吃饭的照片。...
    茶点故事阅读 39,785评论 1 348
  • 序言:一个原本活蹦乱跳的男人离奇死亡,死状恐怖,灵堂内的尸体忽然破棺而出,到底是诈尸还是另有隐情,我是刑警宁泽,带...
    沈念sama阅读 35,492评论 5 345
  • 正文 年R本政府宣布,位于F岛的核电站,受9级特大地震影响,放射性物质发生泄漏。R本人自食恶果不足惜,却给世界环境...
    茶点故事阅读 41,092评论 3 328
  • 文/蒙蒙 一、第九天 我趴在偏房一处隐蔽的房顶上张望。 院中可真热闹,春花似锦、人声如沸。这庄子的主人今日做“春日...
    开封第一讲书人阅读 31,723评论 0 22
  • 文/苍兰香墨 我抬头看了看天上的太阳。三九已至,却和暖如春,着一层夹袄步出监牢的瞬间,已是汗流浃背。 一阵脚步声响...
    开封第一讲书人阅读 32,858评论 1 269
  • 我被黑心中介骗来泰国打工, 没想到刚下飞机就差点儿被人妖公主榨干…… 1. 我叫王不留,地道东北人。 一个月前我还...
    沈念sama阅读 47,891评论 2 370
  • 正文 我出身青楼,却偏偏与公主长得像,于是被迫代替她去往敌国和亲。 传闻我的和亲对象是个残疾皇子,可洞房花烛夜当晚...
    茶点故事阅读 44,713评论 2 354

推荐阅读更多精彩内容