美文网首页
# 监听通知栏获取支付宝到账信息

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

作者: 间歇性丶神经病患者 | 来源:发表于2020-09-27 00:31 被阅读0次

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

    [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();
        }
    }
    

    相关文章

      网友评论

          本文标题:# 监听通知栏获取支付宝到账信息

          本文链接:https://www.haomeiwen.com/subject/smqkuktx.html