() {
@Override
public void onChanged(@Nullable String[] testpostbean) {
PreferenceUtil preference=new PreferenceUtil(getBaseContext());
preference.setNumOfPush("add");
}
});
}
}
================================================
FILE: app/src/main/java/com/weihuagu/receiptnotice/NotificationCollectorMonitorService.java
================================================
package com.weihuagu.receiptnotice;;
import android.app.ActivityManager;
import android.app.Service;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.os.IBinder;
import android.os.Process;
import android.os.Build;
import android.util.Log;
import android.os.PowerManager.WakeLock;
import android.os.PowerManager;
import io.socket.client.IO;
import io.socket.client.Socket;
import java.lang.reflect.Field;
import java.util.HashMap;
import java.util.List;
import java.util.Date;
import java.util.ArrayList;
import java.util.Map;
import java.util.Random;
import java.lang.System;
import java.lang.Thread;
import java.io.PrintWriter;
import java.io.StringWriter;
import java.net.URISyntaxException;
import java.text.SimpleDateFormat;
import java.security.KeyManagementException;
import java.security.NoSuchAlgorithmException;
import javax.net.ssl.SSLSocketFactory;
import com.google.gson.Gson;
import com.weihuagu.receiptnotice.util.DeviceInfoUtil;
import com.weihuagu.receiptnotice.util.ExternalInfoUtil;
import com.weihuagu.receiptnotice.util.LogUtil;
import com.weihuagu.receiptnotice.util.PreferenceUtil;
import com.weihuagu.receiptnotice.util.SSLSocketFactoryCompat;
import io.socket.emitter.Emitter;
import java.util.Timer;
import java.util.TimerTask;
import okhttp3.OkHttpClient;
import okhttp3.TlsVersion;
import okhttp3.ConnectionSpec;
/**
* Created by xinghui on 9/20/16.
*
* calling this in your Application's onCreate
* startService(new Intent(this, NotificationCollectorMonitorService.class));
*
* BY THE WAY Don't Forget to Add the Service to the AndroidManifest.xml File.
*
*/
public class NotificationCollectorMonitorService extends Service {
/**
* {@link Log#isLoggable(String, int)}
*
* IllegalArgumentException is thrown if the tag.length() > 23.
*/
private static final String TAG = "NotifiCollectorMonitor";
private Timer timer=null;
private String echointerval=null;
private TimerTask echotimertask =null;
private WakeLock wl=null;
private void setWakelock() {
PreferenceUtil preference=new PreferenceUtil(getBaseContext());
if(preference.isWakelock())
obtainWakelock();
}
private void obtainWakelock() {
PowerManager pm = (PowerManager)getSystemService(
Context.POWER_SERVICE);
wl = pm.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK,
"receiptnotice:NotificationCollectorMonitorServicewakelock");
wl.acquire();
}
private void releaseWakelock() {
if(wl!=null)
wl.release();
else
return;
}
@Override
public void onCreate() {
super.onCreate();
ensureCollectorRunning();
startEchoTimer();
setWakelock();
}
@Override
public int onStartCommand(Intent intent, int flags, int startId) {
return START_STICKY;
}
private boolean echoServerBySocketio(String echourl,String echojson){
Socket mSocket= EchoSocket.getInstance(echourl);
mSocket.connect();
mSocket.emit("echo",echojson);
mSocket.on(Socket.EVENT_DISCONNECT, new Emitter.Listener() {
@Override
public void call(Object... args) {
LogUtil.infoLog("socket disconnected,try start echo in 5 secend");
try{
Thread.sleep(5000);
}catch(InterruptedException e){
e.printStackTrace();
}
echoServer();
}
});
return true;
}
private String getDefaultEchoInterval(){
if (Build.VERSION.SDK_INT >= 22 )
return "300";
else
return "100";
}
private void startEchoTimer(){
PreferenceUtil preference=new PreferenceUtil(getBaseContext());
String interval=preference.getEchoInterval();
this.echointerval=(!interval.equals("") ? interval:getDefaultEchoInterval());
this.echotimertask=returnEchoTimerTask();
this.timer=new Timer();
int intervalmilliseconds = Integer.parseInt(this.echointerval)*1000;
LogUtil.infoLog("now socketio timer milliseconds:"+intervalmilliseconds);
timer.schedule(echotimertask,5*1000,intervalmilliseconds);
}
private TimerTask returnEchoTimerTask(){
return new TimerTask() {
@Override
public void run() {
if(!isIntervalMatchPreference()){
restartEchoTimer();
return;
}
LogUtil.debugLog("once socketio timer task run");
boolean flag= echoServer();
if(!flag)
LogUtil.debugLog("socketio timer task not have a server");
}
};
}
private void restartEchoTimer(){
if (this.timer != null) {
this.timer.cancel();
this.timer = null;
}
if (echotimertask != null) {
echotimertask.cancel();
echotimertask = null;
}
LogUtil.debugLog("restart echo timer task");
startEchoTimer();
}
private boolean isIntervalMatchPreference(){
PreferenceUtil preference=new PreferenceUtil(getBaseContext());
String interval=preference.getEchoInterval();
if(interval.equals(""))
return true;
if(interval.equals(this.echointerval))
return true;
return false;
}
private boolean echoServer(){
PreferenceUtil preference=new PreferenceUtil(getBaseContext());
Gson gson = new Gson();
if(preference. isEcho()&&(preference.getEchoServer()!=null)){
Date date = new Date(System.currentTimeMillis());
SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
String time = format.format(date);
DeviceBean device = new DeviceBean();
String deviceid = preference.getDeviceid();
deviceid = (!deviceid.equals("") ? deviceid : DeviceInfoUtil.getUniquePsuedoID());
device.setDeviceid(deviceid);
device.setTime(time);
LogUtil.debugLog("start connect socketio");
//////////////
Map devicemap = DeviceBeanReflect(device);
if(devicemap==null)
return false;
if (preference.getEchoCustomOption().equals("") == false) {
Map custompostoption = ExternalInfoUtil.getCustomOption(preference.getEchoCustomOption());
if (custompostoption != null) {
LogUtil.debugLogWithJava("echo custom option map"+custompostoption.toString());
if(custompostoption.size()>0)
devicemap.putAll(custompostoption);
}
}
echoServerBySocketio(preference.getEchoServer(), gson.toJson(devicemap));
LogUtil.debugLog(gson.toJson(devicemap));
return true;
}
else
return false;
}
private void ensureCollectorRunning() {
ComponentName collectorComponent = new ComponentName(this, /*NotificationListenerService Inheritance*/ NLService.class);
Log.v(TAG, "ensureCollectorRunning collectorComponent: " + collectorComponent);
ActivityManager manager = (ActivityManager) getSystemService(Context.ACTIVITY_SERVICE);
boolean collectorRunning = false;
List runningServices = manager.getRunningServices(Integer.MAX_VALUE);
if (runningServices == null ) {
Log.w(TAG, "ensureCollectorRunning() runningServices is NULL");
return;
}
for (ActivityManager.RunningServiceInfo service : runningServices) {
if (service.service.equals(collectorComponent)) {
Log.w(TAG, "ensureCollectorRunning service - pid: " + service.pid + ", currentPID: " + Process.myPid() + ", clientPackage: " + service.clientPackage + ", clientCount: " + service.clientCount
+ ", clientLabel: " + ((service.clientLabel == 0) ? "0" : "(" + getResources().getString(service.clientLabel) + ")"));
if (service.pid == Process.myPid() /*&& service.clientCount > 0 && !TextUtils.isEmpty(service.clientPackage)*/) {
collectorRunning = true;
}
}
}
if (collectorRunning) {
Log.d(TAG, "ensureCollectorRunning: collector is running");
return;
}
Log.d(TAG, "ensureCollectorRunning: collector not running, reviving...");
toggleNotificationListenerService();
}
private void toggleNotificationListenerService() {
Log.d(TAG, "toggleNotificationListenerService() called");
ComponentName thisComponent = new ComponentName(this, /*getClass()*/ NLService.class);
PackageManager pm = getPackageManager();
pm.setComponentEnabledSetting(thisComponent, PackageManager.COMPONENT_ENABLED_STATE_DISABLED, PackageManager.DONT_KILL_APP);
pm.setComponentEnabledSetting(thisComponent, PackageManager.COMPONENT_ENABLED_STATE_ENABLED, PackageManager.DONT_KILL_APP);
}
@Override
public IBinder onBind(Intent intent) {
return null;
}
public class DeviceBean{
public String deviceid;
public String connectedtime;
public void setDeviceid(String deviceid){
this.deviceid=deviceid;
}
public void setTime(String time){
this.connectedtime=time;
}
}
public Map DeviceBeanReflect(DeviceBean e){
Class cls = e.getClass();
Field[] fields = cls.getDeclaredFields();
Map devicebeanmap = new HashMap();
for(int i=0; i= 22 ){
return IO.socket(socketserverurl);
}
else{
SSLSocketFactory factory = new SSLSocketFactoryCompat();
ConnectionSpec cs = new ConnectionSpec.Builder(ConnectionSpec.MODERN_TLS)
.tlsVersions(TlsVersion.TLS_1_2)
.build();
List specs = new ArrayList<>();
specs.add(cs);
specs.add(ConnectionSpec.COMPATIBLE_TLS);
specs.add(ConnectionSpec.CLEARTEXT);
OkHttpClient client = new OkHttpClient.Builder()
.sslSocketFactory(factory)
.connectionSpecs(specs)
.build();
IO.setDefaultOkHttpWebSocketFactory(client);
IO.setDefaultOkHttpCallFactory(client);
// set as an option
IO.Options opts = new IO.Options();
opts.callFactory = client;
opts.webSocketFactory = client;
return IO.socket(socketserverurl, opts);
}
}catch(URISyntaxException e) {
StringWriter sw = new StringWriter();
PrintWriter pw = new PrintWriter(sw);
e.printStackTrace(pw);
LogUtil.debugLog(sw.toString());
return null;
}catch (KeyManagementException e) {
e.printStackTrace();
return null;
} catch (NoSuchAlgorithmException e) {
e.printStackTrace();
return null;
}
}
}
}
================================================
FILE: app/src/main/java/com/weihuagu/receiptnotice/NotificationHandle.java
================================================
package com.weihuagu.receiptnotice;
import android.app.Notification;
import android.app.PendingIntent;
import android.os.Bundle;
import android.service.notification.StatusBarNotification;
import com.weihuagu.receiptnotice.action.ActionStatusBarNotification;
import com.weihuagu.receiptnotice.action.IDoPost;
import com.weihuagu.receiptnotice.util.LogUtil;
import com.weihuagu.receiptnotice.util.NotificationUtil;
import java.text.SimpleDateFormat;
import java.util.Date;
public abstract class NotificationHandle {
protected String pkgtype;
protected Notification notification;
protected Bundle extras;
protected String title;
protected String content;
protected String notitime;
protected IDoPost postpush;
protected ActionStatusBarNotification actionstatusbar;
public StatusBarNotification sbn;
public NotificationHandle(String rawpkgtype, Notification rawnotification, IDoPost rawpostpush){
pkgtype=rawpkgtype;
notification=rawnotification;
postpush=rawpostpush;
extras=notification.extras;
// 获取通知标题
title = extras.getString(Notification.EXTRA_TITLE, "");
// 获取通知内容
content = extras.getString(Notification.EXTRA_TEXT, "");
long when=notification.when;
Date date=new Date(when);
SimpleDateFormat format=new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
notitime=format.format(date);
}
public void setStatusBarNotification(StatusBarNotification sbn){
this.sbn=sbn;
}
public void setActionStatusbar(ActionStatusBarNotification actionstatusbar){
this.actionstatusbar=actionstatusbar;
}
public abstract void handleNotification();
protected void removeNotification(){
if(actionstatusbar==null|sbn==null)
return ;
actionstatusbar.removeNotification(sbn);
}
protected void printNotify(){
LogUtil.debugLog("-----------------");
LogUtil.debugLog("接受到app消息");
LogUtil.debugLog("包名是"+this.pkgtype);
NotificationUtil.printNotify(notification);
LogUtil.debugLog("**********************");
}
protected void openNotify(){
PendingIntent pendingIntent = notification.contentIntent;
try{
pendingIntent.send();
}catch(PendingIntent.CanceledException e){
}
}
}
================================================
FILE: app/src/main/java/com/weihuagu/receiptnotice/NotificationHandleFactory.java
================================================
package com.weihuagu.receiptnotice;
import android.app.Notification;
import android.provider.Telephony.Sms;
import com.weihuagu.receiptnotice.action.IDoPost;
import com.weihuagu.receiptnotice.pushclassification.pmentay.AlipayPmentayNotificationHandle;
import com.weihuagu.receiptnotice.pushclassification.pmentay.BanksProxy;
import com.weihuagu.receiptnotice.pushclassification.pmentay.CashbarPmentayNotificationHandle;
import com.weihuagu.receiptnotice.pushclassification.pmentay.IcbcelifePmentayNotificationHandle;
import com.weihuagu.receiptnotice.pushclassification.pmentay.MipushPmentayNotificationHandle;
import com.weihuagu.receiptnotice.pushclassification.pmentay.UnionpayPmentayNotificationHandle;
import com.weihuagu.receiptnotice.pushclassification.pmentay.WechatPmentayNotificationHandle;
import com.weihuagu.receiptnotice.pushclassification.pmentay.XposedmodulePmentayNotificationHandle;
public class NotificationHandleFactory{
public PmentayNotificationHandle getNotificationHandle(String pkg, Notification notification, IDoPost postpush){
//mipush
if("com.xiaomi.xmsf".equals(pkg)){
return new MipushPmentayNotificationHandle("com.xiaomi.xmsf",notification,postpush);
}
//支付宝
if("com.eg.android.AlipayGphone".equals(pkg)){
return new AlipayPmentayNotificationHandle("com.eg.android.AlipayGphone",notification,postpush);
}
//应用管理GCM代收
if("android".equals(pkg)){
return new XposedmodulePmentayNotificationHandle("github.tornaco.xposedmoduletest",notification,postpush);
}
//微信
if("com.tencent.mm".equals(pkg)){
return new WechatPmentayNotificationHandle("com.tencent.mm",notification,postpush);
}
//收钱吧
if("com.wosai.cashbar".equals(pkg)){
return new CashbarPmentayNotificationHandle("com.wosai.cashbar",notification,postpush);
}
//云闪付
if("com.unionpay".equals(pkg)){
return new UnionpayPmentayNotificationHandle("com.unionpay",notification,postpush);
}
//工银商户之家
if("com.icbc.biz.elife".equals(pkg)){
return new IcbcelifePmentayNotificationHandle("com.icbc.biz.elife",notification,postpush);
}
//接到短信
if(getMessageAppPkg().equals(pkg)){
return new BanksProxy(getMessageAppPkg(),notification,postpush);
}
return null;
}
private String getMessageAppPkg(){
return Sms.getDefaultSmsPackage(MainApplication.getAppContext());
}
}
================================================
FILE: app/src/main/java/com/weihuagu/receiptnotice/OnlyWriteToDateBase.java
================================================
package com.weihuagu.receiptnotice;
import java.util.Map;
import com.weihuagu.receiptnotice.util.DataBaseHolder;
import com.google.gson.Gson;
public class OnlyWriteToDateBase {
DataBaseHolder database = DataBaseHolder.getInstance();
public void onePostWriteToDateBase(String postjson){
Gson gson=new Gson();
Map postmap=gson.fromJson(postjson,Map.class);
String type=postmap.get("type");
String time=postmap.get("time");
String title=postmap.get("title");
String money=postmap.get("money");
String content=postmap.get("content");
checkHavePlatName(type);
}
public boolean checkHavePlatName(String plattype){
database.sqliteDatabase.query("plat",new String[]{"name"},plattype,null,null,null,null);
return false;
}
}
================================================
FILE: app/src/main/java/com/weihuagu/receiptnotice/PmentayNotificationHandle.java
================================================
package com.weihuagu.receiptnotice;
import android.app.Notification;
import android.service.notification.StatusBarNotification;
import com.weihuagu.receiptnotice.action.ActionStatusBarNotification;
import com.weihuagu.receiptnotice.action.IDoPost;
import com.weihuagu.receiptnotice.util.LogUtil;
import com.weihuagu.receiptnotice.util.NotificationUtil;
import java.util.ArrayList;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public abstract class PmentayNotificationHandle extends NotificationHandle{
protected ActionStatusBarNotification actionstatusbar;
public StatusBarNotification sbn;
public PmentayNotificationHandle(String pkgtype, Notification notification, IDoPost postpush){
super(pkgtype, notification, postpush);
}
public void setStatusBarNotification(StatusBarNotification sbn){
this.sbn=sbn;
}
public void setActionStatusbar(ActionStatusBarNotification actionstatusbar){
this.actionstatusbar=actionstatusbar;
}
protected String extractMoney(String content){
Pattern pattern = Pattern.compile("(收款|收款¥|向你付款|向您付款|入账|到帐)(([1-9]{1}\\d*)|([0]{1}))(\\.(\\d){0,2})?元");
Matcher matcher = pattern.matcher(content);
List list = new ArrayList<>();
while(matcher.find()){
list.add(matcher.group());
}
if(list.size()>0){
String tmp=list.get(list.size()-1);
System.out.println(tmp);
Pattern patternnum = Pattern.compile("(([1-9]{1}\\d*)|([0]{1}))(\\.(\\d){0,2})?");
Matcher matchernum = patternnum.matcher(tmp);
if(matchernum.find())
return matchernum.group();
return null;
}else
return null;
}
protected boolean predictIsPost(String content){
Pattern pattern = Pattern.compile("(收到|收款|向你付款|向您付款|入账)(([1-9]{1}\\d*)|([0]{1}))(\\.(\\d){0,2})?元");
Matcher matcher = pattern.matcher(content);
if(matcher.find())
return true;
else
return false;
}
protected void removeNotification(){
if(actionstatusbar==null|sbn==null)
return ;
if(predictIsPost(content))
actionstatusbar.removeNotification(sbn);
}
protected void printNotify(){
LogUtil.debugLog("-----------------");
LogUtil.debugLog("接受到支付类app消息");
LogUtil.debugLog("包名是"+this.pkgtype);
NotificationUtil.printNotify(this.notification);
LogUtil.debugLog("**********************");
}
}
================================================
FILE: app/src/main/java/com/weihuagu/receiptnotice/ReceiptnoticeAccessibilityService.java
================================================
package com.weihuagu.receiptnotice;
import android.accessibilityservice.AccessibilityService;
import android.accessibilityservice.GestureDescription;
import android.app.KeyguardManager;
import android.content.Context;
import android.graphics.Path;
import android.os.Build;
import android.os.PowerManager;
import android.util.DisplayMetrics;
import android.util.Log;
import android.view.WindowManager;
import android.view.accessibility.AccessibilityEvent;
import android.view.accessibility.AccessibilityNodeInfo;
import android.view.accessibility.AccessibilityWindowInfo;
import androidx.annotation.Nullable;
import androidx.lifecycle.Observer;
import com.jeremyliao.liveeventbus.LiveEventBus;
import com.weihuagu.receiptnotice.filteringmiddleware.AlipayTransferBean;
import com.weihuagu.receiptnotice.util.LogUtil;
import com.weihuagu.receiptnotice.util.message.MessageConsumer;
import com.weihuagu.receiptnotice.util.message.MessageSendBus;
import java.util.LinkedList;
import java.util.List;
import java.util.Queue;
public class ReceiptnoticeAccessibilityService extends AccessibilityService implements MessageConsumer {
PowerManager pm=null;
String TAG="onAccessibilityEvent";
private PowerManager.WakeLock mWakeLock = null;
private KeyguardManager mKeyguardManager;
private KeyguardManager.KeyguardLock kl;
private String lastpoststr = "";
private String lastnotistr = "";
private Queue poststrqueue = new LinkedList();
private void setLastPostStr(String str){
lastpoststr=str;
}
private void setLastNotiStr(String str){
lastnotistr=str;
}
@Override
public void onServiceConnected(){
debugLogWithDeveloper("accessibility service connected");
subMessage();
pm = (PowerManager) getSystemService(Context.POWER_SERVICE);
mKeyguardManager = (KeyguardManager) getSystemService(Context.KEYGUARD_SERVICE);
kl = mKeyguardManager.newKeyguardLock("myapp:kllock");
}
@Override
public void onAccessibilityEvent(AccessibilityEvent event) {
debugLogWithDeveloper( event.toString());
final int eventType = event.getEventType();
//根据事件回调类型进行处理
switch (eventType) {
//当通知栏发生改变时
case AccessibilityEvent.TYPE_NOTIFICATION_STATE_CHANGED:
break;
//当窗口的状态发生改变时
case AccessibilityEvent.TYPE_WINDOW_STATE_CHANGED:
String className = event.getClassName().toString();
getAlipayTransferInfo(className);
break;
}
}
@Override
public void onInterrupt() {
debugLogWithDeveloper( "oninterrupt");
}
private void mockSwipe(){
if(Build.VERSION.SDK_INT >= 24) {
//获取屏幕中心点坐标
WindowManager wm = (WindowManager) MainApplication.getAppContext()
.getSystemService(Context.WINDOW_SERVICE);
DisplayMetrics dm = new DisplayMetrics();
wm.getDefaultDisplay().getMetrics(dm);
int width = dm.widthPixels;
int height = dm.heightPixels;
int cx = width/2;
int cy = height / 2;
final Path path = new Path();
path.moveTo(cx, cy); //滑动的起始位置,例如屏幕的中心点X、Y
path.lineTo(cx, 0); //需要滑动的位置,如从中心点滑到屏幕的顶部
GestureDescription.Builder builder = new GestureDescription.Builder();
GestureDescription gestureDescription = builder.addStroke(
new GestureDescription.StrokeDescription(path, 100, 400)
).build(); //移动到中心点,100ms后开始滑动,滑动的时间持续400ms,可以调整
dispatchGesture(gestureDescription, new GestureResultCallback() {
@Override
//如果滑动成功,会回调如下函数,可以在下面记录是否滑动成功,滑动成功或失败都要关闭该路径笔画
public void onCompleted(GestureDescription gestureDescription) {
super.onCompleted(gestureDescription);
Log.d(TAG, "swipe success.");
path.close();
}
@Override
public void onCancelled(GestureDescription gestureDescription) {
super.onCancelled(gestureDescription);
Log.d(TAG, " swipe fail.");
path.close();
}
},null);
}
}
public void subMessage(){
LiveEventBus
.get("action_request_return", String.class)
.observeForever( new Observer() {
@Override
public void onChanged(@Nullable String s) {
LogUtil.debugLog("收到订阅消息:action_request_return " + s);
if(s.equals("return")){
performGlobalAction(GLOBAL_ACTION_BACK);
}
}
});
LiveEventBus
.get("action_request_home", String.class)
.observeForever( new Observer() {
@Override
public void onChanged(@Nullable String s) {
LogUtil.debugLog("收到订阅消息:action_request_home " + s);
if(s.equals("home")){
performGlobalAction(GLOBAL_ACTION_HOME);
}
}
});
LiveEventBus
.get("message_noti_alipay_transfer_arrive", String.class)
.observeForever( new Observer() {
@Override
public void onChanged(@Nullable String s) {
LogUtil.debugLog("收到订阅消息:message_noti_alipay_transfer_arrive " + s);
wakeAndUnlock(true);
setLastNotiStr(s);
}
});
LiveEventBus
.get("update_laststr", String.class)
.observeForever( new Observer() {
@Override
public void onChanged(@Nullable String s) {
LogUtil.debugLog("收到订阅消息:update_laststr " + s);
poststrqueue.offer(s);
setLastPostStr(s);
}
});
}
public void getAlipayTransferInfo(String classname){
String transnumid="com.alipay.mobile.chatapp:id/biz_desc";
String transremarkid="com.alipay.mobile.chatapp:id/biz_title";
debugLogWithDeveloper( ":窗口状态改变,类名为"+classname);
if(classname.equals("com.alipay.mobile.chatapp.ui.PersonalChatMsgActivity_")){
mockSwipe();
AccessibilityNodeInfo nodepersonalchat=null;
AccessibilityWindowInfo windowInfopersonalchat=null;
if(pm.isScreenOn()) {
nodepersonalchat= getRootInActiveWindow();
}else {
if(Build.VERSION.SDK_INT >= 21) {
windowInfopersonalchat = getWindows().get(1);
nodepersonalchat=windowInfopersonalchat.getRoot();
}
}
if (nodepersonalchat== null) {
return;
}
// 找到领取红包的点击事件
try {
List list = nodepersonalchat.findAccessibilityNodeInfosByViewId(transnumid);
AccessibilityNodeInfo thelastnode= list.get(list.size() - 1);
String transnum = thelastnode.getText().toString();
List remarklist=thelastnode.getParent().findAccessibilityNodeInfosByViewId(transremarkid);
String transremark=remarklist.get(remarklist.size()-1).getText().toString();
debugLogWithDeveloper(":金额为" + transnum);
debugLogWithDeveloper(":备注为" + transremark);
AlipayTransferBean transferbean=new AlipayTransferBean();
transferbean.setNum(transnum);
transferbean.setRemark(transremark);
if(!poststrqueue.poll().equals(lastnotistr))
MessageSendBus.postMessageWithget_alipay_transfer_money(transferbean);
}catch (ArrayIndexOutOfBoundsException e){
}
}
}
public void debugLogWithDeveloper(String info){
Log.d(TAG,info);
}
/**
* 唤醒屏幕和解锁
* @param unLock 是否点亮屏幕
*/
private void wakeAndUnlock(boolean unLock)
{
if(unLock)
{
//若为黑屏状态则唤醒屏幕
if(!pm.isScreenOn()) {
//获取电源管理器对象,ACQUIRE_CAUSES_WAKEUP这个参数能从黑屏唤醒屏幕
mWakeLock = pm.newWakeLock(PowerManager.SCREEN_BRIGHT_WAKE_LOCK | PowerManager.ACQUIRE_CAUSES_WAKEUP, "myapp:bright");
//点亮屏幕
mWakeLock.acquire();
kl.disableKeyguard();
Log.i("QHB", "亮屏");
}
}
else
{
//若之前唤醒过屏幕则释放使屏幕不保持常亮
if(mWakeLock != null) {
mWakeLock.release();
mWakeLock = null;
Log.i("QHB", "锁屏");
}
}
}
}
================================================
FILE: app/src/main/java/com/weihuagu/receiptnotice/TestBeanWithPostFullInformationMap.java
================================================
package com.weihuagu.receiptnotice;
import java.util.Map;
public class TestBeanWithPostFullInformationMap {
private String posturl;
private Map infomap;
private String pkg;
public String getPosturl() {
return posturl;
}
public void setPosturl(String posturl) {
this.posturl = posturl;
}
public Map getInfomap() {
return infomap;
}
public void setInfomap(Map infomap) {
this.infomap = infomap;
}
public String getPkg() {
return pkg;
}
public void setPkg(String pkg) {
this.pkg = pkg;
}
}
================================================
FILE: app/src/main/java/com/weihuagu/receiptnotice/action/ActionStatusBarNotification.java
================================================
package com.weihuagu.receiptnotice.action;
import android.service.notification.StatusBarNotification;
public interface ActionStatusBarNotification{
public void removeNotification(StatusBarNotification sbn);
}
================================================
FILE: app/src/main/java/com/weihuagu/receiptnotice/action/AsyncResponse.java
================================================
package com.weihuagu.receiptnotice.action;
import java.util.List;
import java.util.Map;
public interface AsyncResponse {
public void onDataReceivedSuccess(String[] returnstr);
public void onDataReceivedFailed(String[] returnstr,Map postedmap);
}
================================================
FILE: app/src/main/java/com/weihuagu/receiptnotice/action/HandlePost.java
================================================
package com.weihuagu.receiptnotice.action;
import android.content.SharedPreferences;
import com.weihuagu.receiptnotice.MainApplication;
import com.weihuagu.receiptnotice.OnlyWriteToDateBase;
import com.weihuagu.receiptnotice.filteringmiddleware.PostMapFilter;
import com.weihuagu.receiptnotice.util.LogUtil;
import com.weihuagu.receiptnotice.util.PreferenceUtil;
import com.weihuagu.receiptnotice.util.RandomUtil;
import com.weihuagu.receiptnotice.util.message.MessageSendBus;
import java.util.Map;
public class HandlePost implements IDoPost, AsyncResponse {
protected String posturl=null;
public HandlePost() {
getPostUrl();
}
protected String getPostUrl(){
PreferenceUtil preference=new PreferenceUtil(MainApplication.getAppContext());
posturl=preference.getPostUrl();
return posturl;
}
@Override
public void doPost(Map params) {
if(this.posturl==null|params==null)
return;
LogUtil.debugLog("开始准备进行post");
if(params.get("repeatnum")!=null){
doPostTask(params,null);
return;
}
PreferenceUtil preference=new PreferenceUtil(MainApplication.getAppContext());
PostMapFilter mapfilter=new PostMapFilter(preference,params,this.posturl);
Map recordmap=mapfilter.getLogMap();
Map postmap=mapfilter.getPostMap();
doPostTask(postmap,recordmap);
}
protected void doPostTask(Map postmap,Map recordmap){
PostTask mtask = new PostTask();
String tasknum= RandomUtil.getRandomTaskNum();
mtask.setRandomTaskNum(tasknum);
mtask.setOnAsyncResponse(this);
if(recordmap!=null)
LogUtil.postRecordLog(tasknum,recordmap.toString());
else
LogUtil.postRecordLog(tasknum,postmap.toString());
mtask.execute(postmap);
}
@Override
public void onDataReceivedSuccess(String[] returnstr) {
LogUtil.debugLog("Post Receive-returned post string");
LogUtil.debugLog(returnstr[2]);
LogUtil.postResultLog(returnstr[0],returnstr[1],returnstr[2]);
MessageSendBus.postMessageWithFinishedonePost(returnstr);
new OnlyWriteToDateBase().onePostWriteToDateBase(returnstr[2]);
}
@Override
public void onDataReceivedFailed(String[] returnstr, Map postedmap) {
// TODO Auto-generated method stub
LogUtil.debugLog("Post Receive-post error");
LogUtil.postResultLog(returnstr[0],returnstr[1],returnstr[2]);
PreferenceUtil preference=new PreferenceUtil(MainApplication.getAppContext());
if(preference.isPostRepeat()){
String repeatlimit=preference.getPostRepeatNum();
int limitnum=Integer.parseInt(repeatlimit);
String repeatnumstr=postedmap.get("repeatnum");
int repeatnum=Integer.parseInt(repeatnumstr);
if(repeatnum<=limitnum)
doPost(postedmap);
}
}
}
================================================
FILE: app/src/main/java/com/weihuagu/receiptnotice/action/IDoPost.java
================================================
package com.weihuagu.receiptnotice.action;
import java.util.Map;
public interface IDoPost{
public void doPost(Map params);
}
================================================
FILE: app/src/main/java/com/weihuagu/receiptnotice/action/PostTask.java
================================================
package com.weihuagu.receiptnotice.action;
import android.os.AsyncTask;
import java.util.Map;
import java.util.HashMap;
import java.io.IOException;
import okhttp3.MediaType;
import okhttp3.OkHttpClient;
import java.util.Iterator;
import android.util.Log;
import com.weihuagu.receiptnotice.util.NetUtil;
import com.weihuagu.receiptnotice.util.UrlUtil;
public class PostTask extends AsyncTask, Void, String[]> {
public AsyncResponse asyncResponse;
public static final MediaType JSON = MediaType.get("application/json; charset=utf-8");
public String TAG="NLService";
public String randomtasknum;
public Map recordpostmap;
private NetUtil netutil=new NetUtil();
public void setRandomTaskNum(String num){
this.randomtasknum=num;
}
OkHttpClient client = new OkHttpClient();
//fuck 竟然不导包找不到个好的map转json的
public String map2Json(Map map){
String mapjson="";
Iterator> entries = map.entrySet().iterator();
while (entries.hasNext()) {
Map.Entry entry = entries.next();
mapjson=mapjson+'"'+entry.getKey()+'"' + ":"+'"'+entry.getValue()+'"'+",";
}
int strlength=(int)mapjson.length();
mapjson=mapjson.substring(0,(strlength-1));
mapjson="{"+mapjson+"}";
return mapjson;
}
public void setOnAsyncResponse(AsyncResponse asyncResponse)
{
this.asyncResponse = asyncResponse;
}
@Override
protected String[] doInBackground(Map ... key) {
recordpostmap=key[0];
Map postmap=new HashMap();
postmap.putAll(key[0]);
if(postmap==null)
return null;
String url = postmap.get("url");
if(url==null)
return null;
String[] resultstr=new String[3];
resultstr[0]=this.randomtasknum;
postmap.remove("url");
String protocol= UrlUtil.httpOrHttps(url);
String postjson=map2Json(postmap);
if("http".equals(protocol)){
try{
Log.d(TAG,"post task url:"+url);
Log.d(TAG,"post task postjson:"+postjson);
String returnstr=netutil.httppost(url,postjson);
resultstr[1]="true";
resultstr[2]=returnstr;
return resultstr;
}catch(IOException e){}
}
if("https".equals(protocol)){
try{
Log.d(TAG,"post task url:"+url);
Log.d(TAG,"post task postjson:"+postjson);
String returnstr=netutil.httpspost(url,postjson);
resultstr[1]="true";
resultstr[2]=returnstr;
return resultstr;
}catch(IOException e){}
}
return null;
}
@Override
protected void onPostExecute(String[] resultstr) {
super.onPostExecute(resultstr);
if (resultstr != null)
{
asyncResponse.onDataReceivedSuccess(resultstr);//将结果传给回调接口中的函数
}
else {
String [] errstr=new String[3];
errstr[0]=this.randomtasknum;
errstr[1]="false";
errstr[2]="";
if(recordpostmap.get("repeatnum")!=null){
String repeatnumstr=recordpostmap.get("repeatnum");
int num=Integer.parseInt(repeatnumstr)+1;
recordpostmap.put("repeatnum",String.valueOf(num));
//key 存在
}
else
recordpostmap.put("repeatnum","1");
asyncResponse.onDataReceivedFailed(errstr,recordpostmap);
}
}
}
================================================
FILE: app/src/main/java/com/weihuagu/receiptnotice/audiorecognize/AudioHub.java
================================================
package com.weihuagu.receiptnotice.audiorecognize;
import java.io.File;
import java.io.IOException;
import java.util.Collection;
import java.util.HashSet;
import android.media.AudioFormat;
import android.media.AudioRecord;
import android.media.MediaRecorder.AudioSource;
public class AudioHub {
private boolean isRecord = false;
private final static int sampleRate = 8000;
private static int channelConfig = AudioFormat.CHANNEL_IN_STEREO;
private int bufferSize = 0;
private int bufferSizeInBytes =AudioRecord.getMinBufferSize(sampleRate,
channelConfig, AudioFormat.ENCODING_PCM_16BIT);
private final AudioRecord recorder;
public AudioHub() throws IOException{
bufferSize=bufferSizeInBytes;
recorder = new AudioRecord(
AudioSource.VOICE_RECOGNITION, sampleRate,
AudioFormat.CHANNEL_IN_MONO,
AudioFormat.ENCODING_PCM_16BIT, bufferSizeInBytes);
if (recorder.getState() == AudioRecord.STATE_UNINITIALIZED) {
recorder.release();
throw new IOException(
"Failed to initialize recorder. Microphone might be already in use.");
}
}
private void startRecord() {
recorder.startRecording();
// 让录制状态为true
isRecord = true;
// 开启音频文件写入线程
new Thread(new AudioRecordThread()).start();
}
private void stopRecord() {
close();
}
private void close() {
if (recorder != null) {
System.out.println("stopRecord");
isRecord = false;
recorder.stop();
recorder.release();//释放资源
}
}
private void getRecordData(){
short[] buffer = new short[bufferSize];
recorder.read(buffer, 0, buffer.length); // Skip the first buffer, usually zeroes
}
class AudioRecordThread implements Runnable {
@Override
public void run() {
getRecordData();//往文件中写入裸数据
}
}
}
================================================
FILE: app/src/main/java/com/weihuagu/receiptnotice/audiorecognize/RecordService.java
================================================
package com.weihuagu.receiptnotice.audiorecognize;
import android.app.Service;
import android.content.Intent;
import android.os.IBinder;;import androidx.annotation.Nullable;
public class RecordService extends Service {
@Nullable
@Override
public IBinder onBind(Intent intent) {
return null;
}
@Override
public void onCreate() {
super.onCreate();
try {
AudioHub hub=new AudioHub();
}catch (Exception e){
}
}
}
================================================
FILE: app/src/main/java/com/weihuagu/receiptnotice/filteringmiddleware/AlipayTransferBean.java
================================================
package com.weihuagu.receiptnotice.filteringmiddleware;
public class AlipayTransferBean {
public String getNum() {
return num;
}
public void setNum(String num) {
this.num = num;
}
public String getRemark() {
return remark;
}
public void setRemark(String remark) {
this.remark = remark;
}
private String num;
private String remark;
}
================================================
FILE: app/src/main/java/com/weihuagu/receiptnotice/filteringmiddleware/PostMapFilter.java
================================================
package com.weihuagu.receiptnotice.filteringmiddleware;
import com.weihuagu.receiptnotice.util.DeviceInfoUtil;
import com.weihuagu.receiptnotice.util.ExternalInfoUtil;
import com.weihuagu.receiptnotice.util.LogUtil;
import com.weihuagu.receiptnotice.util.PreferenceUtil;
import com.weihuagu.receiptnotice.util.encrypt.EncryptFactory;
import com.weihuagu.receiptnotice.util.encrypt.Encrypter;
import com.weihuagu.receiptnotice.util.encrypt.MD5;
import java.util.HashMap;
import java.util.Map;
public class PostMapFilter {
private Map unmodifiedmap;
private PreferenceUtil preference;
private String posturl;
public PostMapFilter(PreferenceUtil preference, Map unmodifiedmap, String posturl) {
this.preference = preference;
this.unmodifiedmap = unmodifiedmap;
this.posturl = posturl;
}
public String getDeviceid() {
String deviceid = preference.getDeviceid();
if (deviceid.equals(""))
deviceid = DeviceInfoUtil.getUniquePsuedoID();
else if (preference.isAppendDeviceiduuid())
deviceid = deviceid + '-' + DeviceInfoUtil.getUniquePsuedoID();
else
deviceid = deviceid;
return deviceid;
}
public Map getPostMap() {
Map postmap = new HashMap();
postmap.putAll(getLogMap());
postmap.put("sign",new MD5().getSignMd5(postmap.get("type"),postmap.get("money")));
if (preference.isEncrypt()) {
String encrypt_type = preference.getEncryptMethod();
if (encrypt_type != null) {
String key = preference.getPasswd();
EncryptFactory encryptfactory = new EncryptFactory(key);
LogUtil.debugLog("加密方法" + encrypt_type);
LogUtil.debugLog("加密秘钥" + key);
Encrypter encrypter = encryptfactory.getEncrypter(encrypt_type);
if (encrypter != null && key != null) {
postmap = encrypter.transferMapValue(postmap);
postmap.put("url", this.posturl);
if (preference.isSkipEncryptDeviceid())
postmap.put("deviceid", getDeviceid());
}
}
} else
postmap.put("encrypt", "0");
return postmap;
}
public Map getLogMap() {
Map recordmap = new HashMap();
recordmap.putAll(this.unmodifiedmap);
recordmap.put("url", this.posturl);
recordmap.put("deviceid", getDeviceid());
if (preference.getCustomOption().equals("") == false) {
Map custompostoption = ExternalInfoUtil.getCustomPostOption(preference.getCustomOption());
if (custompostoption != null)
recordmap.putAll(custompostoption);
}
return recordmap;
}
}
================================================
FILE: app/src/main/java/com/weihuagu/receiptnotice/pushclassification/pmentay/AlipayPmentayNotificationHandle.java
================================================
package com.weihuagu.receiptnotice.pushclassification.pmentay;
import android.app.Notification;
import androidx.annotation.Nullable;
import androidx.lifecycle.Observer;
import com.jeremyliao.liveeventbus.LiveEventBus;
import com.weihuagu.receiptnotice.filteringmiddleware.AlipayTransferBean;
import com.weihuagu.receiptnotice.util.AuthorityUtil;
import com.weihuagu.receiptnotice.action.IDoPost;
import com.weihuagu.receiptnotice.util.LogUtil;
import com.weihuagu.receiptnotice.MainApplication;
import com.weihuagu.receiptnotice.util.message.MessageConsumer;
import com.weihuagu.receiptnotice.util.message.MessageSendBus;
import com.weihuagu.receiptnotice.PmentayNotificationHandle;
import java.util.Map;
import java.util.HashMap;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class AlipayPmentayNotificationHandle extends PmentayNotificationHandle implements MessageConsumer {
Map tmppostmap=new HashMap();
public AlipayPmentayNotificationHandle(String pkgtype, Notification notification, IDoPost postpush){
super(pkgtype,notification,postpush);
}
public void handleNotification(){
if(title.contains("支付宝") | title.contains("收钱码") | title.contains("收款通知")){
//不可将转账判断延后放,以防止通过昵称虚构金额
if(content.contains("向你转了1笔钱")){
transfercodePush();
return ;
}
if(content.contains("成功收款") | content.contains("向你付款")){
collectioncodePush(true);
return ;
}
}
if(isInfoHideInTitle()){
collectioncodePush(false);
return ;
}
}
private void transfercodePush(){
Map postmap=new HashMap();
postmap.put("type","alipay-transfer");
postmap.put("time",notitime);
postmap.put("title","转账");
postmap.put("money","-0.00");
postmap.put("content",content);
postmap.put("transferor",whoTransferred(content));
//use acceesbility service to get info
if (AuthorityUtil.isAccessibilitySettingsOn(MainApplication.getAppContext())) {
tmppostmap.putAll(postmap);
subMessage();
//open notify
MessageSendBus.postMessageWithReceiptAlipayTransfer(tmppostmap.get("time")+tmppostmap.get("content"));
this.openNotify();
return ;
}
postpush.doPost(postmap);
return ;
}
private void collectioncodePush(boolean isinfoincontent){
Map postmap=new HashMap();
postmap.put("type","alipay");
postmap.put("time",notitime);
postmap.put("title","支付宝支付");
if(isinfoincontent){
postmap.put("money",extractMoney(content));
postmap.put("content",content);
}else
{
postmap.put("money",extractMoney(title));
postmap.put("content",title);
}
postpush.doPost(postmap);
return ;
}
private boolean isInfoHideInTitle(){
if(title.contains("成功收款")&&content.contains("立即查看"))
return true;
return false;
}
private String whoTransferred(String content){
Pattern pattern = Pattern.compile("(.*)(已成功向你转了)");
Matcher matcher = pattern.matcher(content);
if(matcher.find()){
String tmp=matcher.group(1);
return tmp;
}
else
return "";
}
public void subMessage() {
LiveEventBus
.get("get_alipay_transfer_money", AlipayTransferBean.class)
.observeForever( new Observer() {
@Override
public void onChanged(@Nullable AlipayTransferBean transfer) {
if(tmppostmap.size()==0)
return;
LogUtil.debugLog("收到订阅消息:get_alipay_transfer_money " + "money"+transfer.getNum()+"备注"+transfer.getRemark());
MessageSendBus.postActionRequestWithReturn();
MessageSendBus.postActionRequestWithHome();
tmppostmap.put("money",transfer.getNum());
tmppostmap.put("remark",transfer.getRemark());
MessageSendBus.postMessageWithUpdateTheLastPostString(tmppostmap.get("time")+tmppostmap.get("content"));
postpush.doPost(tmppostmap);
tmppostmap=new HashMap();
return;
}
});
}
}
================================================
FILE: app/src/main/java/com/weihuagu/receiptnotice/pushclassification/pmentay/BankDistinguisher.java
================================================
package com.weihuagu.receiptnotice.pushclassification.pmentay;
import com.weihuagu.receiptnotice.util.ExternalInfoUtil;
import java.util.Map;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import java.util.Stack;
import java.util.Calendar;
import java.text.SimpleDateFormat;
import java.text.ParseException;
import java.util.Date;
public class BankDistinguisher{
public BankDistinguisher(){
}
public String distinguishByNum(String num){
Map map= ExternalInfoUtil.getBanksMessageNum();
String whatsback=map.get(num);
if(whatsback!=null)
return whatsback;
else
return "";
}
public String distinguishByMessageContent(String content){
if(content.contains("银行")&&ExternalInfoUtil.containsBankmessageFeature(content))
{
Stack alternativebank = new Stack();
Map map=ExternalInfoUtil.getAllBanksNameMap();
for (String key : map.keySet()) {
if(content.contains(key))
alternativebank.push(key);
}
if(alternativebank.isEmpty())
return "";
else
return map.get(alternativebank.peek());
}
else
return null;
}
public String extractMoney(String content){
Pattern pattern = Pattern.compile("(收入|存入|转入|入账)(\\(.*\\))?(\\d{1,3}(,\\d{2,3})*(\\.\\d{0,2})?)元?");
Matcher matcher = pattern.matcher(content);
if(matcher.find()){
String tmp=matcher.group();
Pattern patternnum = Pattern.compile("((\\d{1,3}(,\\d{2,3})*(\\.\\d{0,2})?))");
Matcher matchernum = patternnum.matcher(tmp);
if(matchernum.find())
return matchernum.group();
return null;
}else
return null;
}
public String extractCardNum(String content){
String pattern = "(尾号\\d{4}的?(卡|账号|账户))";
Pattern r = Pattern.compile(pattern);
Matcher m = r.matcher(content);
if(m.find())
return m.group();
else
return "";
}
public String extractTime(String content,String time){
Pattern pattern = Pattern.compile("([0-9]|0[0-9]|1[0-9]|2[0-3]):([0-5][0-9])");
Matcher matcher = pattern.matcher(content);
if(matcher.find()){
try {
SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd hh:mm");
Date date = df.parse(time);
Calendar calendar = Calendar.getInstance();
calendar.setTime(date);
calendar.set(Calendar.HOUR_OF_DAY,Integer.parseInt(matcher.group(1)));
calendar.set(Calendar.MINUTE,Integer.parseInt(matcher.group(2)));
return df.format(calendar.getTime());
} catch (ParseException e) {
return time;
}
}else
return time;
}
}
================================================
FILE: app/src/main/java/com/weihuagu/receiptnotice/pushclassification/pmentay/BanksProxy.java
================================================
package com.weihuagu.receiptnotice.pushclassification.pmentay;
import android.app.Notification;
import com.weihuagu.receiptnotice.action.IDoPost;
import com.weihuagu.receiptnotice.PmentayNotificationHandle;
import java.util.Map;
import java.util.HashMap;
public class BanksProxy extends PmentayNotificationHandle {
private BankDistinguisher onedistinguisher=new BankDistinguisher();
public BanksProxy(String pkgtype, Notification notification, IDoPost postpush){
super(pkgtype,notification,postpush);
}
private String getBankType(){
return onedistinguisher.distinguishByMessageContent(content);
}
public void handleNotification(){
String banktype=getBankType();
if(banktype==null)
return;
String type=null;
if(banktype=="")
type="message-bank";
else
type="message-bank-"+banktype;
Map postmap=new HashMap();
postmap.put("type",type);
postmap.put("time",onedistinguisher.extractTime(content,notitime));
postmap.put("title","短信银行卡入账");
postmap.put("phonenum",title);
postmap.put("money",onedistinguisher.extractMoney(content));
postmap.put("cardnum",onedistinguisher.extractCardNum(content));
postmap.put("content",content);
postpush.doPost(postmap);
return ;
}
}
================================================
FILE: app/src/main/java/com/weihuagu/receiptnotice/pushclassification/pmentay/CashbarPmentayNotificationHandle.java
================================================
package com.weihuagu.receiptnotice.pushclassification.pmentay;
import android.app.Notification;
import com.weihuagu.receiptnotice.action.IDoPost;
import com.weihuagu.receiptnotice.PmentayNotificationHandle;
import java.util.Map;
import java.util.HashMap;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class CashbarPmentayNotificationHandle extends PmentayNotificationHandle {
public CashbarPmentayNotificationHandle(String pkgtype, Notification notification, IDoPost postpush){
super(pkgtype,notification,postpush);
}
public void handleNotification(){
if(title.contains("收钱吧")){
if(content.contains("成功收款") | content.contains("向你付款")){
Map postmap=new HashMap();
postmap.put("type",getCashbarType(content));
postmap.put("time",notitime);
postmap.put("title","支付宝支付");
postmap.put("money",extractMoney(content));
postmap.put("content",content);
postpush.doPost(postmap);
return ;
}
}
}
private String getCashbarType(String content){
Pattern pattern = Pattern.compile("(来自)(微信|支付宝|.*)");
Matcher matcher = pattern.matcher(content);
if(matcher.find()){
String tmp=matcher.group(2);
return "cashbar-"+transType(tmp);
}else
return "";
}
private String transType(String chinesetype){
if(chinesetype.equals("微信"))
return "wechat";
if(chinesetype.equals("支付宝"))
return "alipay";
else return chinesetype;
}
}
================================================
FILE: app/src/main/java/com/weihuagu/receiptnotice/pushclassification/pmentay/IcbcelifePmentayNotificationHandle.java
================================================
package com.weihuagu.receiptnotice.pushclassification.pmentay;
import android.app.Notification;
import com.weihuagu.receiptnotice.action.IDoPost;
import com.weihuagu.receiptnotice.PmentayNotificationHandle;
import java.util.Map;
import java.util.HashMap;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class IcbcelifePmentayNotificationHandle extends PmentayNotificationHandle {
public IcbcelifePmentayNotificationHandle(String pkgtype, Notification notification, IDoPost postpush){
super(pkgtype,notification,postpush);
}
public void handleNotification(){
if(title.contains("工银商户")){
if(content.contains("已收到")&&content.contains("元")){
Map postmap=new HashMap();
postmap.put("type","icbcelife");
postmap.put("time",notitime);
postmap.put("title","工银商户之家");
postmap.put("money",extractMoney(content));
postmap.put("content",content);
postpush.doPost(postmap);
return ;
}
}
}
@Override
protected String extractMoney(String content){
Pattern pattern = Pattern.compile("(收到|收款|向你付款)(([1-9]{1}\\d*)|([0]{1}))(\\.(\\d){0,2})?元");
Matcher matcher = pattern.matcher(content);
if(matcher.find()){
String tmp=matcher.group();
Pattern patternnum = Pattern.compile("(([1-9]{1}\\d*)|([0]{1}))(\\.(\\d){0,2})?");
Matcher matchernum = patternnum.matcher(tmp);
if(matchernum.find())
return matchernum.group();
return null;
}else
return null;
}
}
================================================
FILE: app/src/main/java/com/weihuagu/receiptnotice/pushclassification/pmentay/MipushPmentayNotificationHandle.java
================================================
package com.weihuagu.receiptnotice.pushclassification.pmentay;
import android.app.Notification;
import com.weihuagu.receiptnotice.action.IDoPost;
import com.weihuagu.receiptnotice.PmentayNotificationHandle;
import java.util.Map;
import java.util.HashMap;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class MipushPmentayNotificationHandle extends PmentayNotificationHandle {
public MipushPmentayNotificationHandle(String pkgtype, Notification notification, IDoPost postpush){
super(pkgtype,notification,postpush);
}
public void handleNotification(){
if(title.contains("支付宝")){
if(content.contains("成功收款")){
Map postmap=new HashMap();
postmap.put("type","alipay");
postmap.put("time",notitime);
postmap.put("title","支付宝支付");
postmap.put("money",extractMoney(content));
postmap.put("content",content);
postpush.doPost(postmap);
return ;
}
if(content.contains("向你转了1笔钱")){
Map postmap=new HashMap();
postmap.put("type","alipay-transfer");
postmap.put("time",notitime);
postmap.put("title","转账");
postmap.put("money","-0.00");
postmap.put("content",content);
postmap.put("transferor",whoTransferred(content));
postpush.doPost(postmap);
return ;
}
}
if(title.contains("动账通知")){
if(content.contains("入账")&&content.contains("尾号为")){
Map postmap=new HashMap();
postmap.put("type","unionpay");
postmap.put("time",notitime);
postmap.put("title","云闪付扫码收款");
postmap.put("money",extractMoney(content));
postmap.put("content",content);
//postmap.put("payer",getPayer(content));
postpush.doPost(postmap);
return ;
}
}
}
private String getPayer(String content){
Pattern pattern = Pattern.compile("(.*)(通过扫码向您付款)");
Matcher matcher = pattern.matcher(content);
if(matcher.find()){
String tmp=matcher.group(2);
return tmp;
}else
return "";
}
private String whoTransferred(String content){
Pattern pattern = Pattern.compile("(.*)(已成功向你转了)");
Matcher matcher = pattern.matcher(content);
if(matcher.find()){
String tmp=matcher.group(1);
return tmp;
}
else
return "";
}
}
================================================
FILE: app/src/main/java/com/weihuagu/receiptnotice/pushclassification/pmentay/UnionpayPmentayNotificationHandle.java
================================================
package com.weihuagu.receiptnotice.pushclassification.pmentay;
import android.app.Notification;
import com.weihuagu.receiptnotice.action.IDoPost;
import com.weihuagu.receiptnotice.PmentayNotificationHandle;
import java.util.Map;
import java.util.HashMap;
public class UnionpayPmentayNotificationHandle extends PmentayNotificationHandle {
public UnionpayPmentayNotificationHandle(String pkgtype, Notification notification, IDoPost postpush){
super(pkgtype,notification,postpush);
}
public void handleNotification(){
if(title.contains("消息推送")&&content.contains("云闪付收款")){
Map postmap=new HashMap();
postmap.put("type","unionpay");
postmap.put("time",notitime);
postmap.put("title",title);
postmap.put("money",extractMoney(content));
postmap.put("content",content);
postpush.doPost(postmap);
return ;
}
}
}
================================================
FILE: app/src/main/java/com/weihuagu/receiptnotice/pushclassification/pmentay/WechatPmentayNotificationHandle.java
================================================
package com.weihuagu.receiptnotice.pushclassification.pmentay;
import android.app.Notification;
import com.weihuagu.receiptnotice.action.IDoPost;
import com.weihuagu.receiptnotice.PmentayNotificationHandle;
import java.util.Map;
import java.util.HashMap;
public class WechatPmentayNotificationHandle extends PmentayNotificationHandle {
public WechatPmentayNotificationHandle(String pkgtype, Notification notification, IDoPost postpush){
super(pkgtype,notification,postpush);
}
public void handleNotification(){
if(title.contains("微信支付")|title.contains("微信收款")){
if(content.contains("收款")){
Map postmap = new HashMap();
postmap.put("type", "wechat");
postmap.put("time", notitime);
postmap.put("title", title);
postmap.put("money", extractMoney(content));
postmap.put("content", content);
postpush.doPost(postmap);
return;
}
if(content.contains("二维码赞赏")){
Map postmap = new HashMap();
postmap.put("type", "wechat-sponsor");
postmap.put("time", notitime);
postmap.put("title", title);
postmap.put("money", extractMoney(content));
postmap.put("content", content);
postpush.doPost(postmap);
return;
}
}
}
}
================================================
FILE: app/src/main/java/com/weihuagu/receiptnotice/pushclassification/pmentay/XposedmodulePmentayNotificationHandle.java
================================================
package com.weihuagu.receiptnotice.pushclassification.pmentay;
import android.app.Notification;
import com.weihuagu.receiptnotice.action.IDoPost;
import com.weihuagu.receiptnotice.PmentayNotificationHandle;
import java.util.Map;
import java.util.HashMap;
public class XposedmodulePmentayNotificationHandle extends PmentayNotificationHandle {
public XposedmodulePmentayNotificationHandle(String pkgtype, Notification notification, IDoPost postpush){
super(pkgtype,notification,postpush);
}
public void handleNotification(){
if(content.contains("微信支付")&&content.contains("收款")){
Map postmap=new HashMap();
postmap.put("type","wechat");
postmap.put("time",notitime);
postmap.put("title","微信支付");
postmap.put("money",extractMoney(content));
postmap.put("content",content);
postpush.doPost(postmap);
return ;
}
}
}
================================================
FILE: app/src/main/java/com/weihuagu/receiptnotice/util/AuthorityUtil.java
================================================
package com.weihuagu.receiptnotice.util;
import android.content.Context;
import android.provider.Settings;
import android.text.TextUtils;
public class AuthorityUtil {
public static boolean isAccessibilitySettingsOn(Context mContext) {
int accessibilityEnabled = 0;
final String service = "com.weihuagu.receiptnotice/com.weihuagu.receiptnotice.ReceiptnoticeAccessibilityService";
boolean accessibilityFound = false;
try {
accessibilityEnabled = Settings.Secure.getInt(
mContext.getApplicationContext().getContentResolver(),
android.provider.Settings.Secure.ACCESSIBILITY_ENABLED);
} catch (Settings.SettingNotFoundException e) {
}
TextUtils.SimpleStringSplitter mStringColonSplitter = new TextUtils.SimpleStringSplitter(':');
if (accessibilityEnabled == 1) {
LogUtil.debugLog("***ACCESSIBILIY IS ENABLED*** -----------------");
String settingValue = Settings.Secure.getString(
mContext.getApplicationContext().getContentResolver(),
Settings.Secure.ENABLED_ACCESSIBILITY_SERVICES);
if (settingValue != null) {
TextUtils.SimpleStringSplitter splitter = mStringColonSplitter;
splitter.setString(settingValue);
while (splitter.hasNext()) {
String accessabilityService = splitter.next();
LogUtil.debugLog("绑定的accessabilityService :: " + accessabilityService);
if (accessabilityService.equalsIgnoreCase(service)) {
return true;
}
}
}
} else {
LogUtil.debugLog("***ACCESSIBILIY IS DISABLED***");
}
return accessibilityFound;
}
}
================================================
FILE: app/src/main/java/com/weihuagu/receiptnotice/util/ByteUtil.java
================================================
/*
*下面两个自己字节的函数源自GcsSloop
*GitHub: https://github.com/GcsSloop
*/
package com.weihuagu.receiptnotice.util;
public class ByteUtil {
/**
* 二进位组转十六进制字符串
*
* @param buf 二进位组
* @return 十六进制字符串
*/
public static String parseByte2HexStr(byte buf[]) {
StringBuilder sb = new StringBuilder();
for (byte b : buf) {
String hex = Integer.toHexString(b & 0xFF);
if (hex.length() == 1) {
hex = '0' + hex;
}
sb.append(hex.toUpperCase());
}
return sb.toString();
}
/**
* 十六进制字符串转二进位组
*
* @param hexStr 十六进制字符串
* @return 二进位组
*/
public static byte[] parseHexStr2Byte(String hexStr) {
if (hexStr.length() < 1) return null;
byte[] result = new byte[hexStr.length() / 2];
for (int i = 0; i < hexStr.length() / 2; i++) {
int high = Integer.parseInt(hexStr.substring(i * 2, i * 2 + 1), 16);
int low = Integer.parseInt(hexStr.substring(i * 2 + 1, i * 2 + 2), 16);
result[i] = (byte) (high * 16 + low);
}
return result;
}
}
================================================
FILE: app/src/main/java/com/weihuagu/receiptnotice/util/Constants.java
================================================
/*
* Created By WeihuaGu (email:weihuagu_work@163.com)
* Copyright (c) 2017
* All right reserved.
*/
package com.weihuagu.receiptnotice.util;
public class Constants {
/**
* Actions.
*/
public static final String ACTION_BROWSER_CONTEXT_MENU = "ACTION_BROWSER_OPEN";
/**
* Extras.
*/
public static final String EXTRA_ID = "EXTRA_ID";
public static final String EXTRA_ACTION_ID = "EXTRA_ACTION_ID";
public static final String EXTRA_NEW_TAB = "EXTRA_NEW_TAB";
public static final String EXTRA_LABEL = "EXTRA_LABEL";
public static final String EXTRA_URL = "EXTRA_URL";
public static final String EXTRA_FOLDER_ID = "EXTRA_FOLDER_ID";
public static final String EXTRA_HIT_TEST_RESULT = "EXTRA_HIT_TEST_RESULT";
public static final String EXTRA_INCOGNITO = "EXTRA_INCOGNITO";
/**
* Specials urls.
*/
public static final String URL_ABOUT_BLANK = "about:blank";
public static final String URL_ABOUT_START = "about:start";
public static final String URL_ABOUT_TUTORIAL = "about:tutorial";
/**
* User agents
*/
public static final String USER_AGENT_ANDROID = "";
public static final String USER_AGENT_DESKTOP = "Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/534.24 (KHTML, like Gecko) Chrome/11.0.696.34 Safari/534.24";
/**
* Preferences.
*/
public static final String PREFERENCE_HOME_PAGE = "PREFERENCE_HOME_PAGE";
public static final String PREFERENCE_SEARCH_URL = "PREFERENCE_SEARCH_URL";
public static final String PREFERENCE_START_PAGE_LIMIT = "PREFERENCE_START_PAGE_LIMIT";
public static final String PREFERENCE_BUBBLE_POSITION = "PREFERENCE_BUBBLE_POSITION";
public static final String PREFERENCE_TOOLBARS_AUTOHIDE_DURATION = "PREFERENCE_TOOLBARS_AUTOHIDE_DURATION";
public static final String PREFERENCES_SWITCH_TABS_METHOD = "PREFERENCES_SWITCH_TABS_METHOD";
public static final String PREFERENCE_ENABLE_JAVASCRIPT = "PREFERENCE_ENABLE_JAVASCRIPT";
public static final String PREFERENCE_ENABLE_IMAGES = "PREFERENCE_ENABLE_IMAGES";
public static final String PREFERENCE_USE_WIDE_VIEWPORT = "PREFERENCE_USE_WIDE_VIEWPORT";
public static final String PREFERENCE_LOAD_WITH_OVERVIEW = "PREFERENCE_LOAD_WITH_OVERVIEW";
public static final String PREFERENCE_USER_AGENT = "PREFERENCE_USER_AGENT";
public static final String PREFERENCE_PLUGINS = "PREFERENCE_PLUGINS";
public static final String PREFERENCE_ACCEPT_COOKIES = "PREFERENCE_ACCEPT_COOKIES";
public static final String PREFERENCE_ENABLE_GEOLOCATION = "PREFERENCE_ENABLE_GEOLOCATION";
public static final String PREFERENCE_REMEMBER_FORM_DATA = "PREFERENCE_REMEMBER_FORM_DATA";
public static final String PREFERENCE_REMEMBER_PASSWORDS = "PREFERENCE_REMEMBER_PASSWORDS";
public static final String PREFERENCE_HISTORY_SIZE = "PREFERENCE_HISTORY_SIZE";
public static final String PREFERENCE_CLEAR_CACHE = "PREFERENCE_CLEAR_CACHE";
public static final String PREFERENCE_WEBSITES_SETTINGS = "PREFERENCE_WEBSITES_SETTINGS";
public static final String PREFERENCE_SSL_EXCEPTIONS = "PREFERENCE_SSL_EXCEPTIONS";
public static final String PREFERENCE_CLEAR_HISTORY = "PREFERENCE_CLEAR_HISTORY";
public static final String PREFERENCE_CLEAR_COOKIES = "PREFERENCE_CLEAR_COOKIES";
public static final String PREFERENCE_CLEAR_GEOLOCATION = "PREFERENCE_CLEAR_GEOLOCATION";
public static final String PREFERENCE_CLEAR_FORM_DATA = "PREFERENCE_CLEAR_FORM_DATA";
public static final String PREFERENCE_CLEAR_PASSWORDS = "PREFERENCE_CLEAR_PASSWORDS";
public static final String PREFERENCE_INCOGNITO_BY_DEFAULT = "PREFERENCE_INCOGNITO_BY_DEFAULT";
public static final String PREFERENCE_TEXT_SCALING = "PREFERENCE_TEXT_SCALING";
public static final String PREFERENCE_MINIMUM_FONT_SIZE = "PREFERENCE_MINIMUM_FONT_SIZE";
public static final String PREFERENCE_INVERTED_DISPLAY = "PREFERENCE_INVERTED_DISPLAY";
public static final String PREFERENCE_INVERTED_DISPLAY_CONTRAST = "PREFERENCE_INVERTED_DISPLAY_CONTRAST";
public static final String PREFERENCE_BOOKMARKS_SORT_MODE = "PREFERENCE_BOOKMARKS_SORT_MODE";
public static final String PREFERENCE_FULL_SCREEN = "PREFERENCE_FULL_SCREEN";
public static final String PREFERENCE_RESTORE_TABS = "PREFERENCE_RESTORE_TABS";
public static final String PREFERENCE_UI_TYPE = "PREFERENCE_UI_TYPE";
public static final String PREFERENCE_CLOSE_PANEL_ON_NEW_TAB = "PREFERENCE_CLOSE_PANEL_ON_NEW_TAB";
public static final String PREFERENCE_JS_LOG_ON_LOGCAT = "PREFERENCE_JS_LOG_ON_LOGCAT";
/**
* Technical preferences.
*/
public static final String TECHNICAL_PREFERENCE_LAST_HISTORY_TRUNCATION = "TECHNICAL_PREFERENCE_LAST_HISTORY_TRUNCATION";
public static final String TECHNICAL_PREFERENCE_FIRST_RUN = "TECHNICAL_PREFERENCE_FIRST_RUN";
public static final String TECHNICAL_PREFERENCE_LAST_RUN_VERSION_CODE = "TECHNICAL_PREFERENCE_LAST_RUN_VERSION_CODE";
public static final String TECHNICAL_PREFERENCE_ADDON_ENABLED = "TECHNICAL_PREFERENCE_ADDON_ENABLED_";
public static final String TECHNICAL_PREFERENCE_SAVED_TABS = "TECHNICAL_PREFERENCE_SAVED_TABS";
public static final String TECHNICAL_PREFERENCE_HOMEPAGE_URL_UPDATE_NEEDED = "TECHNICAL_PREFERENCE_HOMEPAGE_URL_UPDATE_NEEDED";
}
================================================
FILE: app/src/main/java/com/weihuagu/receiptnotice/util/DataBaseHolder.java
================================================
package com.weihuagu.receiptnotice.util;
import android.database.sqlite.SQLiteDatabase;
import com.weihuagu.receiptnotice.DatabaseHelper;
import com.weihuagu.receiptnotice.MainApplication;
public class DataBaseHolder {
//创建 SingleObject 的一个对象
private static DataBaseHolder instance = new DataBaseHolder();
public DatabaseHelper dbHelper;
public SQLiteDatabase sqliteDatabase;
//让构造函数为 private,这样该类就不会被实例化
private DataBaseHolder(){
createDataBase();
}
//获取唯一可用的对象
public static DataBaseHolder getInstance(){
return instance;
}
private void createDataBase(){
dbHelper = new DatabaseHelper(MainApplication.getAppContext(),"receiptnotice",null,1);
sqliteDatabase = dbHelper.getWritableDatabase();
}
public SQLiteDatabase getDateBase(){
return sqliteDatabase;
}
}
================================================
FILE: app/src/main/java/com/weihuagu/receiptnotice/util/DeviceInfoUtil.java
================================================
/*
* Created By WeihuaGu (email:weihuagu_work@163.com)
*/
package com.weihuagu.receiptnotice.util;
import android.os.Build;
import java.util.UUID;
public class DeviceInfoUtil {
/**
* Return pseudo unique ID
* @return ID
*/
public static String getUniquePsuedoID() {
// If all else fails, if the user does have lower than API 9 (lower
// than Gingerbread), has reset their device or 'Secure.ANDROID_ID'
// returns 'null', then simply the ID returned will be solely based
// off their Android device information. This is where the collisions
// can happen.
// Thanks http://www.pocketmagic.net/?p=1662!
// Try not to use DISPLAY, HOST or ID - these items could change.
// If there are collisions, there will be overlapping data
String m_szDevIDShort = "35" + (Build.BOARD.length() % 10) + (Build.BRAND.length() % 10) + (Build.CPU_ABI.length() % 10) + (Build.DEVICE.length() % 10) + (Build.MANUFACTURER.length() % 10) + (Build.MODEL.length() % 10) + (Build.PRODUCT.length() % 10);
// Thanks to @Roman SL!
// http://stackoverflow.com/a/4789483/950427
// Only devices with API >= 9 have android.os.Build.SERIAL
// http://developer.android.com/reference/android/os/Build.html#SERIAL
// If a user upgrades software or roots their device, there will be a duplicate entry
String serial = null;
try {
serial = android.os.Build.class.getField("SERIAL").get(null).toString();
// Go ahead and return the serial for api => 9
return new UUID(m_szDevIDShort.hashCode(), serial.hashCode()).toString();
} catch (Exception exception) {
// String needs to be initialized
serial = "serial"; // some value
}
// Thanks @Joe!
// http://stackoverflow.com/a/2853253/950427
// Finally, combine the values we have found by using the UUID class to create a unique identifier
return new UUID(m_szDevIDShort.hashCode(), serial.hashCode()).toString();
}
}
================================================
FILE: app/src/main/java/com/weihuagu/receiptnotice/util/ExternalInfoUtil.java
================================================
/*
* Created By WeihuaGu (email:weihuagu_work@163.com)
* Copyright (c) 2017
* All right reserved.
*/
package com.weihuagu.receiptnotice.util;
import java.util.Map;
import java.util.HashMap;
public class ExternalInfoUtil {
/**
*
* 中国银行:106573095566、777795566;
招商银行:1065795555、10657559555、1065502010095555;
建设银行:106573095533、80095533;
工商银行:95588;62019558;010095588;
民生银行:10657109095568000、1069088895568;
农业银行:106366695599、6201395599;
华夏银行:1065800895577、1069088895577;
交通银行:106573095559、777795559、555595559000、80095559、
788895559、797995559
*
* */
public final static Map bankmessagenum = new HashMap() {{
put("95588", "icbc");
put("62019558", "icbc");
put("010095588", "icbc");
put("106573095566", "boc");
put("777795566", "boc");
put("1065795555", "cmb");
put("10657559555", "cmb");
put("1065502010095555", "cmb");
put("106573095533", "ccb");
put("80095533", "ccb");
put("10657109095568000", "cmbc");
put("1069088895568", "cmbc");
}};
public final static Map banksname = new HashMap() {{
put("工商银行", "icbc");
put("农业银行", "abc");
put("中国银行", "boc");
put("建设银行", "ccb");
put("邮政储蓄银行", "psbc");
put("招商银行", "cbm");
put("浦发银行", "spdb");
put("兴业银行", "cib");
put("民生银行", "cmbc");
put("光大银行", "ceb");
put("网商银行", "my");
put("北京银行", "bob");
}};
public final static String [] maybankmessagefeature = new String[]{
"收入",
"存入",
"转入",
"入账",
"来帐"
};
public static Map getBanksMessageNum(){
return bankmessagenum;
}
public static Map getAllBanksNameMap(){
return banksname;
}
public static String[] getBankmessageFeature(){
return maybankmessagefeature;
}
public static boolean containsBankmessageFeature(String content){
for(String x : maybankmessagefeature){
if(content.contains(x))
return true;
}
return false;
}
public static Map getCustomPostOption(String custom){
return getCustomOption(custom);
}
public static Map getCustomOption(String custom){
String s[] = custom.split(";");
Map customoption = new HashMap();
for(String x : s){
String ss[] = getOneitemKeyandValue(x);
if(ss!=null){
customoption.put(ss[0],ss[1]);
}
}
if(customoption.size()>0)
return customoption;
else
return null;
}
public static String[] getOneitemKeyandValue(String item){
String s[] = item.split(":");
if(s.length==2)
return s;
else
return null;
}
}
================================================
FILE: app/src/main/java/com/weihuagu/receiptnotice/util/FileLogUtil.java
================================================
/*
* Created By WeihuaGu (email:weihuagu_work@163.com)
* Copyright (c) 2017
* All right reserved.
*/
package com.weihuagu.receiptnotice.util;
import com.tao.admin.loglib.FileUtils;
import com.tao.admin.loglib.TLogApplication;
import com.tao.admin.loglib.IConfig;
import com.weihuagu.receiptnotice.util.OneFileUtil;
import java.io.File;
import java.util.ArrayList;
public class FileLogUtil extends FileUtils{
public static boolean clearLogFile() {
try {
File file = new File(TLogApplication.getAPP().getFilesDir(), IConfig.fileName);
if(file.delete())
return true;
else
return false;
} catch(Exception e) {
e.printStackTrace();
return false;
}
}
public static ArrayList getLogList(){
File file = new File(TLogApplication.getAPP().getFilesDir(), IConfig.fileName);
if (!file.exists())
return null;
OneFileUtil fileutil = new OneFileUtil(file);
ArrayList filelist=fileutil.getFileList();
String startflag="*********************************";
String endflag="------------------------------------------";
ArrayList filemergelist=fileutil.mergeByFlagline(startflag,endflag,filelist);
return filemergelist;
}
}
================================================
FILE: app/src/main/java/com/weihuagu/receiptnotice/util/LogUtil.java
================================================
/*
* Created By WeihuaGu (email:weihuagu_work@163.com)
* Copyright (c) 2017
* All right reserved.
*/
package com.weihuagu.receiptnotice.util;
import android.util.Log;
import com.tao.admin.loglib.Logger;
import com.weihuagu.receiptnotice.util.message.MessageSendBus;
public class LogUtil {
public static String TAG="NLService";
public static String DEBUGTAG="NLDebugService";
public static String EXCEPTIONTAG="NLExceptionService";
public static void infoLog(String info){
Log.i(TAG,info);
}
public static void debugLog(String info){
Log.d(TAG,info);
}
public static void debugLogWithDeveloper(String info){
Log.d(DEBUGTAG,info);
}
public static void debugLogWithJava(String info){
System.out.println(DEBUGTAG+":"+info);
}
public static void postRecordLog(String tasknum,String post){
Logger.i("*********************************");
Logger.i("开始推送", "随机序列号:"+tasknum);
Logger.i(post);
}
public static void postResultLog(String tasknum,String result,String returnstr){
Logger.i("推送结果","随机序列号:"+tasknum);
Logger.i("推送结果",result);
Logger.i("返回内容",returnstr);
Logger.i("------------------------------------------");
MessageSendBus.postInterfaceMessageWithUpdateTheRecordlist();
}
}
================================================
FILE: app/src/main/java/com/weihuagu/receiptnotice/util/NetUtil.java
================================================
package com.weihuagu.receiptnotice.util;
import android.os.Build;
import com.weihuagu.receiptnotice.MainApplication;
import java.io.IOException;
import java.io.PrintWriter;
import java.io.StringWriter;
import java.security.KeyManagementException;
import java.security.NoSuchAlgorithmException;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.TimeUnit;
import javax.net.ssl.HostnameVerifier;
import javax.net.ssl.SSLContext;
import javax.net.ssl.SSLSession;
import javax.net.ssl.SSLSocketFactory;
import javax.net.ssl.TrustManager;
import javax.net.ssl.X509TrustManager;
import okhttp3.ConnectionSpec;
import okhttp3.MediaType;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.RequestBody;
import okhttp3.Response;
import okhttp3.TlsVersion;
public class NetUtil {
public static final MediaType JSON = MediaType.get("application/json; charset=utf-8");
OkHttpClient client = new OkHttpClient();
PreferenceUtil preferceutil = new PreferenceUtil(MainApplication.getAppContext());
public String httppost(String url, String json) throws IOException {
RequestBody body = RequestBody.create(JSON, json);
OkHttpClient client = new OkHttpClient.Builder()
.connectTimeout(10, TimeUnit.SECONDS)//设置连接超时时间
.readTimeout(20, TimeUnit.SECONDS)//设置读取超时时间
.build();
Request.Builder request = new Request.Builder()
.url(url)
.post(body);
try (Response response = client.newCall(request.build()).execute()) {
return response.body().string();
}
}
public String httpspost(String url, String json) throws IOException {
if (Build.VERSION.SDK_INT >= 21) {
if (!preferceutil.isTrustAllCertificates())
return httppost(url, json);
else {
RequestBody body = RequestBody.create(JSON, json);
OkHttpClient clientwithtrustallcertificates = getHttpsClientWithTrustAllCertificates();
Request.Builder request = new Request.Builder()
.url(url)
.post(body);
try (Response response = clientwithtrustallcertificates.newCall(request.build()).execute()) {
return response.body().string();
}
}
} else
return doHttpsWithApi19(url, json);
}
public String doHttpsWithApi19(String url, String json) {
try {
RequestBody body = RequestBody.create(JSON, json);
SSLSocketFactory factory = new SSLSocketFactoryCompat();
ConnectionSpec cs = new ConnectionSpec.Builder(ConnectionSpec.MODERN_TLS)
.tlsVersions(TlsVersion.TLS_1_2)
.build();
List specs = new ArrayList<>();
specs.add(cs);
specs.add(ConnectionSpec.COMPATIBLE_TLS);
specs.add(ConnectionSpec.CLEARTEXT);
OkHttpClient client = new OkHttpClient.Builder()
.connectTimeout(10, TimeUnit.SECONDS)//设置连接超时时间
.readTimeout(20, TimeUnit.SECONDS)//设置读取超时时间
.sslSocketFactory(factory)
.connectionSpecs(specs)
.build();
Request.Builder request = new Request.Builder()
.url(url)
.post(body);
Response response = client.newCall(request.build()).execute();
return response.body().string();
} catch (IOException e) {
StringWriter sw = new StringWriter();
PrintWriter pw = new PrintWriter(sw);
e.printStackTrace(pw);
LogUtil.debugLog(sw.toString());
return null;
} catch (KeyManagementException e) {
e.printStackTrace();
return null;
} catch (NoSuchAlgorithmException e) {
e.printStackTrace();
return null;
}
}
private OkHttpClient getHttpsClientWithTrustAllCertificates() {
OkHttpClient.Builder okhttpClient = new OkHttpClient().newBuilder();
//信任所有服务器地址
okhttpClient. connectTimeout(10, TimeUnit.SECONDS)//设置连接超时时间
.readTimeout(20, TimeUnit.SECONDS);//设置读取超时时间
okhttpClient.hostnameVerifier(new HostnameVerifier() {
@Override
public boolean verify(String s, SSLSession sslSession) {
//设置为true
return true;
}
});
//创建管理器
TrustManager[] trustAllCerts = new TrustManager[]{new X509TrustManager() {
@Override
public void checkClientTrusted(
java.security.cert.X509Certificate[] x509Certificates,
String s) throws java.security.cert.CertificateException {
}
@Override
public void checkServerTrusted(
java.security.cert.X509Certificate[] x509Certificates,
String s) throws java.security.cert.CertificateException {
}
@Override
public java.security.cert.X509Certificate[] getAcceptedIssuers() {
return new java.security.cert.X509Certificate[]{};
}
}};
try {
SSLContext sslContext = SSLContext.getInstance("TLS");
sslContext.init(null, trustAllCerts, new java.security.SecureRandom());
//为OkHttpClient设置sslSocketFactory
okhttpClient.sslSocketFactory(sslContext.getSocketFactory());
} catch (Exception e) {
e.printStackTrace();
}
return okhttpClient.build();
}
}
================================================
FILE: app/src/main/java/com/weihuagu/receiptnotice/util/NotificationUtil.java
================================================
/*
* Created By WeihuaGu (email:weihuagu_work@163.com)
* Copyright (c) 2017
* All right reserved.
*/
package com.weihuagu.receiptnotice.util;
import android.app.Notification;
import android.os.Bundle;
import com.weihuagu.receiptnotice.util.LogUtil;
import java.text.SimpleDateFormat;
import java.util.Date;
public class NotificationUtil {
private static String getNotitime(Notification notification){
long when=notification.when;
Date date=new Date(when);
SimpleDateFormat format=new SimpleDateFormat("yyyy-MM-dd HH:mm");
String notitime=format.format(date);
return notitime;
}
private static String getNotiTitle(Bundle extras){
String title=null;
// 获取通知标题
title = extras.getString(Notification.EXTRA_TITLE, "");
return title;
}
private static String getNotiContent(Bundle extras){
String content=null;
// 获取通知内容
content = extras.getString(Notification.EXTRA_TEXT, "");
return content;
}
public static void printNotify(Notification notification){
if(notification==null){
LogUtil.debugLog("notificationutil report: notification is null");
return;
}
LogUtil.debugLog(getNotitime(notification));
LogUtil.debugLog(getNotiTitle(notification.extras));
LogUtil.debugLog(getNotiContent(notification.extras));
}
}
================================================
FILE: app/src/main/java/com/weihuagu/receiptnotice/util/OneFileLogItem.java
================================================
package com.weihuagu.receiptnotice.util;
public class OneFileLogItem {
public String getPlatName(){
return null;
}
public String getMoney(){
return null;
}
public String getReply(){
return null;
}
public boolean isRandomSequenceNumberMatches(){
return true;
}
}
================================================
FILE: app/src/main/java/com/weihuagu/receiptnotice/util/OneFileUtil.java
================================================
/*
* Created By WeihuaGu (email:weihuagu_work@163.com)
* Copyright (c) 2017
* All right reserved.
*/
package com.weihuagu.receiptnotice.util;
import java.io.File;
import java.io.FileReader;
import java.io.BufferedReader;
import java.io.IOException;
import java.util.Iterator;
import java.util.ArrayList;
import java.util.LinkedList;
import java.util.Deque;
public class OneFileUtil{
private File file;
public OneFileUtil(File file){
this.file=file;
}
private String clearOnegroup(Deque onegroup){
String tmp="";
while(onegroup.size()>0){
String first=onegroup.pollFirst();
tmp=tmp+"\n"+first;
}
return tmp;
}
public ArrayList mergeByFlagline(String startflagline,String endflagline,ArrayList filelist){
if(filelist.size()==0)
return null;
ArrayList merge=new ArrayList();
Iterator fileiterator = filelist.iterator();
Deque onegroup = new LinkedList();
while (fileiterator.hasNext()) {
String o = (String)fileiterator.next();
onegroup.offerLast(o);
if(onegroup.peekFirst().contains(startflagline)&&onegroup.peekLast().contains(endflagline)){
merge.add(clearOnegroup(onegroup));
}
}
return merge;
}
public ArrayList getFileList(){
ArrayList arrayList = new ArrayList();
FileReader fr = null;
try{
if (!file.exists())
return null;
fr = new FileReader(file);
BufferedReader bf = new BufferedReader(fr);
String str;
while ((str = bf.readLine()) != null) {
//按行处理
arrayList.add(str);
}
if(arrayList.size()==0)
return null;
else
return arrayList;
} catch (Throwable ex) {
ex.printStackTrace();
} finally {
try {
if (fr != null)
fr.close();
} catch (IOException e) {
e.printStackTrace();
}
}
return null;
}
}
================================================
FILE: app/src/main/java/com/weihuagu/receiptnotice/util/PreferenceUtil.java
================================================
package com.weihuagu.receiptnotice.util;
import android.content.Context;
import android.content.SharedPreferences;
import android.preference.PreferenceManager;
import android.widget.Toast;
public class PreferenceUtil {
SharedPreferences sharedPref = null;
Context context = null;
public PreferenceUtil(Context context) {
this.context = context;
init();
}
public void init() {
sharedPref = PreferenceManager.getDefaultSharedPreferences(this.context);
}
public String getDeviceid() {
return this.sharedPref.getString("deviceid", "");
}
public boolean isEncrypt() {
return this.sharedPref.getBoolean("isencrypt", false);
}
public boolean isEcho() {
return this.sharedPref.getBoolean("isecho", false);
}
public boolean isWakelock() {
return this.sharedPref.getBoolean("iswakelock", false);
}
public boolean isAppendDeviceiduuid() {
return this.sharedPref.getBoolean("isappenddeviceiduuid", false);
}
public boolean isSkipEncryptDeviceid() {
return this.sharedPref.getBoolean("isskipencryptdeviceid", false);
}
public boolean isTrustAllCertificates() {
return this.sharedPref.getBoolean("istrustallcertificates", false);
}
public boolean isAccessibilityService() {
return this.sharedPref.getBoolean("isaccessibilityservice", false);
}
public boolean isAgreeUserAgreement(){
return this.sharedPref.getBoolean("isagreeuseragreement", false);
}
public void setAgreeUserAgreement(boolean flag){
SharedPreferences.Editor edit = this.sharedPref.edit();
//通过editor对象写入数据
edit.putBoolean("isagreeuseragreement",flag);
//提交数据存入到xml文件中
edit.apply();
}
public void setNumOfPush(String op){
SharedPreferences.Editor edit = this.sharedPref.edit();
if(op.equals("add")){
int currentnum=getNumOfPush();
edit.putInt("numofpush",currentnum++);
//提交数据存入到xml文件中
edit.apply();
}
}
public void setPostUrl(String url) {
SharedPreferences.Editor edit = this.sharedPref.edit();
edit.putString("posturl", url);
//提交数据存入到xml文件中
edit.apply();
}
public String getPostUrl(){
return this.sharedPref.getString("posturl",null);
}
public int getNumOfPush(){
return this.sharedPref.getInt("numofpush",0);
}
public String getEchoServer() {
return this.sharedPref.getString("echoserver", null);
}
public String getEchoInterval() {
return this.sharedPref.getString("echointerval", "");
}
public String getEncryptMethod() {
return this.sharedPref.getString("encryptmethod", null);
}
public String getPasswd() {
return this.sharedPref.getString("passwd", null);
}
public boolean isRemoveNotification() {
return this.sharedPref.getBoolean("isremovenotification", false);
}
public boolean isPostRepeat() {
return this.sharedPref.getBoolean("ispostrepeat", false);
}
public String getPostRepeatNum() {
return this.sharedPref.getString("postrepeatnum", "3");
}
public String getCustomOption() {
return this.sharedPref.getString("custom_option", "");
}
public String getEchoCustomOption() {
return this.sharedPref.getString("echo_custom_option", "");
}
}
================================================
FILE: app/src/main/java/com/weihuagu/receiptnotice/util/RandomUtil.java
================================================
/*
* Created By WeihuaGu (email:weihuagu_work@163.com)
* Copyright (c) 2017
* All right reserved.
*/
package com.weihuagu.receiptnotice.util;
import java.util.Random;
public class RandomUtil {
public static String getRandomTaskNum(){
Random rand = new Random();
return String.valueOf(rand.nextInt(9000) + 1000);
}
}
================================================
FILE: app/src/main/java/com/weihuagu/receiptnotice/util/SSLSocketFactoryCompat.java
================================================
package com.weihuagu.receiptnotice.util;
import android.os.Build;
import java.io.IOException;
import java.net.InetAddress;
import java.net.Socket;
import java.security.KeyManagementException;
import java.security.NoSuchAlgorithmException;
import javax.net.ssl.SSLContext;
import javax.net.ssl.SSLSocket;
import javax.net.ssl.SSLSocketFactory;
public class SSLSocketFactoryCompat extends SSLSocketFactory{
private static final String[] TLS_V12_ONLY = {"TLSv1.2"};
private final SSLSocketFactory delegate;
public SSLSocketFactoryCompat() throws KeyManagementException, NoSuchAlgorithmException {
SSLContext sc = SSLContext.getInstance("TLS");
sc.init(null, null, null);
delegate = sc.getSocketFactory();
}
public SSLSocketFactoryCompat(SSLSocketFactory delegate) {
if (delegate == null) {
throw new NullPointerException();
}
this.delegate = delegate;
}
@Override
public String[] getDefaultCipherSuites() {
return delegate.getDefaultCipherSuites();
}
@Override
public String[] getSupportedCipherSuites() {
return delegate.getSupportedCipherSuites();
}
private Socket enableTls12(Socket socket) {
if (Build.VERSION.SDK_INT >= 16 && Build.VERSION.SDK_INT < 20) {
if (socket instanceof SSLSocket) {
((SSLSocket) socket).setEnabledProtocols(TLS_V12_ONLY);
}
}
return socket;
}
@Override
public Socket createSocket(Socket s, String host, int port, boolean autoClose) throws IOException {
return enableTls12(delegate.createSocket(s, host, port, autoClose));
}
@Override
public Socket createSocket(String host, int port) throws IOException {
return enableTls12(delegate.createSocket(host, port));
}
@Override
public Socket createSocket(String host, int port, InetAddress localHost, int localPort) throws IOException {
return enableTls12(delegate.createSocket(host, port, localHost, localPort));
}
@Override
public Socket createSocket(InetAddress host, int port) throws IOException {
return enableTls12(delegate.createSocket(host, port));
}
@Override
public Socket createSocket(InetAddress address, int port, InetAddress localAddress, int localPort) throws IOException {
return enableTls12(delegate.createSocket(address, port, localAddress, localPort));
}
}
================================================
FILE: app/src/main/java/com/weihuagu/receiptnotice/util/UrlUtil.java
================================================
/*
* Created By WeihuaGu (email:weihuagu_work@163.com)
* Copyright (c) 2017
* All right reserved.
*/
package com.weihuagu.receiptnotice.util;
public class UrlUtil {
public static String [] commonusedurls={"m.baidu.com","www.baidu.com","cn.bing.com","Jd.com","weibo.com","weibo.cn","sina.cn","www.tmall.com","www.taobao.com","tianya.cn","github.com","news.163.com","mail.163.com","image.baidu.com","wwww.zhihu.com","www.huanqiu.com","www.ifeng.com","www.jianshu.com","www.xueqiu.com"};
public static String [] getCommonlyUsedUrls(){
return commonusedurls;
}
public static boolean isUrl(String url) {
return
url.contains(".") ||
url.equals(Constants.URL_ABOUT_BLANK) ||
url.equals(Constants.URL_ABOUT_START) ||
url.equals(Constants.URL_ABOUT_TUTORIAL);
}
public static String getSearchUrl(String searchurl,String serchcontent) {
return searchurl.replaceAll("\\{searchTerms\\}", serchcontent);
}
public static String httpOrHttps(String address){
if(address.startsWith("http://")){
return "http";
}
if(address.startsWith("https://"))
return "https";
return null;
}
public static String addressMatch(String address){
if(address.startsWith("jian://")){
return address;
}
if(address.startsWith("alipay://")){
return address;
}
if(address.startsWith("wechat://")){
return address;
}
if(address.startsWith("http://")){
return address;
}
if(address.startsWith("https://"))
return address;
if(!address.startsWith("http://")|!address.startsWith("https://")) {
address = "http://" + address;
} // 如果不以http://开头,识别不了,所以判断
return address;
}
public static String addressMatchInHttps(String address){
if(address.startsWith("https://")){
return address;
}
if(address.startsWith("http://")){
return address.replaceAll("http","https");
}
else{
return "https://"+address;
}
}
}
================================================
FILE: app/src/main/java/com/weihuagu/receiptnotice/util/encrypt/AES.java
================================================
package com.weihuagu.receiptnotice.util.encrypt;
import com.weihuagu.receiptnotice.util.encrypt.Encrypter;
import java.util.Map;
import java.util.HashMap;
import java.util.Iterator;
public class AES extends Encrypter {
public AES(String key){
super(key);
}
public Map transferMapValue(Map params){
Map postmap=new HashMap();
Iterator entries = params.entrySet().iterator();
while (entries.hasNext()) {
Map.Entry entry = (Map.Entry) entries.next();
String paramkey = (String)entry.getKey();
String paramvalue = (String)entry.getValue();
//String aesStr = AESUtil.aes(paramvalue, key, Cipher.ENCRYPT_MODE);
String aesStr=null;
postmap.put(paramkey,aesStr);
}
postmap.put("encrypt","1");
return postmap;
}
}
================================================
FILE: app/src/main/java/com/weihuagu/receiptnotice/util/encrypt/DES.java
================================================
package com.weihuagu.receiptnotice.util.encrypt;
import com.weihuagu.receiptnotice.util.LogUtil;
import java.util.Map;
import java.util.HashMap;
import java.util.Iterator;
import javax.crypto.Cipher;
public class DES extends Encrypter{
public DES(String key){
super(key);
}
public Map transferMapValue(Map params){
Map postmap=new HashMap();
Iterator entries = params.entrySet().iterator();
while (entries.hasNext()) {
Map.Entry entry = (Map.Entry) entries.next();
String paramkey = (String)entry.getKey();
String paramvalue = (String)entry.getValue();
String desStr = DESUtilWithIV.des(paramvalue, key, Cipher.ENCRYPT_MODE);
postmap.put(paramkey,desStr);
}
postmap.put("encrypt","1");
LogUtil.debugLogWithJava("调试,开始加密字符串");
LogUtil.debugLogWithJava("加密后的map");
LogUtil.debugLogWithJava(postmap.toString());
return postmap;
}
}
================================================
FILE: app/src/main/java/com/weihuagu/receiptnotice/util/encrypt/DESUtilWithIV.java
================================================
package com.weihuagu.receiptnotice.util.encrypt;
import android.annotation.SuppressLint;
import androidx.annotation.IntDef;
import com.weihuagu.receiptnotice.util.ByteUtil;
import java.io.UnsupportedEncodingException;
import java.security.InvalidKeyException;
import java.security.NoSuchAlgorithmException;
import java.security.spec.InvalidKeySpecException;
import javax.crypto.Cipher;
import javax.crypto.BadPaddingException;
import javax.crypto.IllegalBlockSizeException;
import javax.crypto.NoSuchPaddingException;
import java.security.InvalidAlgorithmParameterException;
import javax.crypto.SecretKeyFactory;
import javax.crypto.spec.DESKeySpec;
import javax.crypto.spec.IvParameterSpec;
public class DESUtilWithIV{
@IntDef({Cipher.ENCRYPT_MODE, Cipher.DECRYPT_MODE})
@interface DESType {}
/**
* Des加密/解密
*
* @param content 字符串内容
* @param password 密钥
* @param type 加密:{@link Cipher#ENCRYPT_MODE},解密:{@link Cipher#DECRYPT_MODE}
* @return 加密/解密结果
*/
public static String des(String content, String password, int type) {
try {
IvParameterSpec iv = new IvParameterSpec(password.getBytes());
DESKeySpec desKey = new DESKeySpec(password.getBytes());
SecretKeyFactory keyFactory = SecretKeyFactory.getInstance("DES");
@SuppressLint("GetInstance") Cipher cipher = Cipher.getInstance("DES/CBC/PKCS5Padding");
cipher.init(type, keyFactory.generateSecret(desKey), iv);
if (type == Cipher.ENCRYPT_MODE) {
byte[] byteContent = content.getBytes("utf-8");
return ByteUtil.parseByte2HexStr(cipher.doFinal(byteContent));
} else {
byte[] byteContent = ByteUtil.parseHexStr2Byte(content);
return new String(cipher.doFinal(byteContent));
}
} catch (InvalidAlgorithmParameterException | NoSuchAlgorithmException | BadPaddingException | IllegalBlockSizeException |
UnsupportedEncodingException | InvalidKeyException | NoSuchPaddingException |
InvalidKeySpecException e) {
e.printStackTrace();
}
return null;
}
}
================================================
FILE: app/src/main/java/com/weihuagu/receiptnotice/util/encrypt/EncryptFactory.java
================================================
package com.weihuagu.receiptnotice.util.encrypt;
import com.weihuagu.receiptnotice.util.LogUtil;
public class EncryptFactory{
private String key;
public EncryptFactory(String key){
this.key=key;
}
public Encrypter getEncrypter(String encrypt_type){
if(encrypt_type.equals("des"))
return new DES(key);
if(encrypt_type.equals("aes"))
return new AES(key);
if(encrypt_type.equals("md5"))
return new MD5(key);
LogUtil.debugLog("没有匹配到合适的Encrypter");
return null;
}
}
================================================
FILE: app/src/main/java/com/weihuagu/receiptnotice/util/encrypt/Encrypter.java
================================================
package com.weihuagu.receiptnotice.util.encrypt;
import java.util.Map;
public abstract class Encrypter implements IDataTrans {
protected String key;
public Encrypter(String key){
this.key=key;
}
public Encrypter(){}
public abstract Map transferMapValue(Map params);
}
================================================
FILE: app/src/main/java/com/weihuagu/receiptnotice/util/encrypt/IDataTrans.java
================================================
package com.weihuagu.receiptnotice.util.encrypt;
import java.util.Map;
public interface IDataTrans{
public Map transferMapValue(Map params);
}
================================================
FILE: app/src/main/java/com/weihuagu/receiptnotice/util/encrypt/MD5.java
================================================
package com.weihuagu.receiptnotice.util.encrypt;
import com.weihuagu.receiptnotice.util.ByteUtil;
import com.weihuagu.receiptnotice.util.LogUtil;
import com.weihuagu.receiptnotice.util.encrypt.Encrypter;
import java.security.MessageDigest;
import java.util.HashMap;
import java.util.Map;
public class MD5 extends Encrypter {
public MD5(String key) {
super(key);
}
public MD5(){
}
public Map transferMapValue(Map params) {
if(params.get("type")!=null&¶ms.get("money")!=null&&key!=null) {
Map postmap = new HashMap();
postmap.putAll(params);
postmap.put("sign", getSignMd5WithSecretkey(params.get("type"), params.get("money"), key));
LogUtil.debugLogWithJava("调试,sign md5");
return postmap;
}else
return params;
}
public String getMd5String(String str) {
try {
byte[] bytesOfMessage = str.getBytes("UTF-8");
MessageDigest md = MessageDigest.getInstance("MD5");
byte[] thedigest = md.digest(bytesOfMessage);
return ByteUtil.parseByte2HexStr(thedigest);
} catch (java.io.UnsupportedEncodingException exception) {
return null;
} catch (java.security.NoSuchAlgorithmException exception) {
return null;
}
}
public String getSignMd5(String type, String price) {
String md5str=getMd5String(getMd5String(type+price));
LogUtil.debugLog("md5 string: type is"+type+" price is "+ price + " md5str:"+md5str);
return md5str;
}
public String getSignMd5WithSecretkey(String type, String price, String secretkey) {
String md5str=getMd5String(getMd5String(type+price)+secretkey);
return md5str;
}
}
================================================
FILE: app/src/main/java/com/weihuagu/receiptnotice/util/message/MessageConsumer.java
================================================
package com.weihuagu.receiptnotice.util.message;
public interface MessageConsumer {
public void subMessage();
}
================================================
FILE: app/src/main/java/com/weihuagu/receiptnotice/util/message/MessageSendBus.java
================================================
package com.weihuagu.receiptnotice.util.message;
import com.jeremyliao.liveeventbus.LiveEventBus;
import com.weihuagu.receiptnotice.filteringmiddleware.AlipayTransferBean;
import com.weihuagu.receiptnotice.TestBeanWithPostFullInformationMap;
public class MessageSendBus {
//请求硬件模拟类
public static void postActionRequestWithReturn(){
LiveEventBus
.get("action_request_return")
.post("return");
}
public static void postActionRequestWithHome(){
LiveEventBus
.get("action_request_home")
.post("home");
}
//收到活动改变等检测信息
public static void postMessageWithCommonAccessibilityEvent(String event){
LiveEventBus.get("get_new_accessibilityevent").post(event);
}
//消息发送类
public static void postMessageWithFinishedonePost(String[] returnstr){
LiveEventBus
.get("message_finished_one_post")
.post(returnstr);
}
public static void postMessageWithReceiptAlipayTransfer(String transferinfo){
LiveEventBus
.get("message_noti_alipay_transfer_arrive")
.post(transferinfo);
}
public static void postMessageWithUpdateTheLastPostString(String str){
LiveEventBus.get("update_laststr").post(str);
}
public static void postMessageWithget_alipay_transfer_money(AlipayTransferBean transferbean){
LiveEventBus
.get("get_alipay_transfer_money")
.post(transferbean);
}
//模型改变通知界面类
public static void postInterfaceMessageWithUpdateTheRecordlist(){
LiveEventBus
.get("update_recordlist")
.post("update");
}
//用户点击类消息
public static void userMessageWithSetPostUrl(String url){
LiveEventBus
.get("user_set_posturl")
.post(url);
}
//测试消息类
public static void postTestMessageWithPostFullInformationMap(TestBeanWithPostFullInformationMap bean){
LiveEventBus
.get("testmessage_post_full_information_map")
.post(bean);
}
//时间心跳类
//默认以一定时间发送一次的时间间隔消息.时间间隔是一分钟.
public static void postBaseTimeInterval(){
LiveEventBus
.get("time_interval")
.post("base_time_interval");
}
}
================================================
FILE: app/src/main/java/com/weihuagu/receiptnotice/view/FileLogActivity.java
================================================
package com.weihuagu.receiptnotice.view;
import java.util.ArrayList;
import java.util.Collections;
import android.os.Bundle;
import androidx.annotation.Nullable;
import androidx.appcompat.app.AppCompatActivity;
import android.widget.TextView;
import androidx.appcompat.widget.Toolbar;
import androidx.recyclerview.widget.RecyclerView;
import androidx.recyclerview.widget.LinearLayoutManager;
import android.view.MenuItem;
import android.view.Menu;
import android.view.MenuInflater;
import android.widget.Toast;
import com.weihuagu.receiptnotice.util.FileLogUtil;
import com.weihuagu.receiptnotice.R;
public class FileLogActivity extends AppCompatActivity {
private RecyclerView recyclerView;
private LogListAdapter mAdapter;
private RecyclerView.LayoutManager layoutManager;
private TextView mTextView;
private Toolbar myToolbar;
private boolean loglist_is_a_wholetext=true;
@Override
protected void onCreate(@Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_log);
initView();
setLogText();
}
private void initView(){
myToolbar= (Toolbar) findViewById(R.id.my_toolbar);
setSupportActionBar(myToolbar);
mTextView = (TextView) findViewById(R.id.tv_log);
}
private void initLoglistView(boolean reverseorder){
recyclerView = (RecyclerView) findViewById(R.id.my_recycler_view);
//recyclerView.setHasFixedSize(true);
// use a linear layout manager
layoutManager = new LinearLayoutManager(this);
recyclerView.setLayoutManager(layoutManager);
// specify an adapter (see also next example)
mAdapter = new LogListAdapter(getApplicationContext());
ArrayList loglist= FileLogUtil.getLogList();
//LogUtil.debugLogWithDeveloper("打印通过filelogutil获取到的file log list");
if(loglist!=null&&loglist.size()>0){
loglist_is_a_wholetext=false;
if(reverseorder)
Collections.reverse(loglist);
}
else{
loglist_is_a_wholetext=true;
return;
}
mAdapter.setLoglist(loglist);
recyclerView.setAdapter(mAdapter);
}
private void setLogText(){
initLoglistView(false);
if(loglist_is_a_wholetext){
String log = FileLogUtil.readLogText();
mTextView.setText(log);
}
}
private void clearLog(){
FileLogUtil.clearLogFile();
setLogText();
Toast.makeText(getApplicationContext(), "已经清空日志",Toast.LENGTH_SHORT).show();
}
private void showReverse(){
initLoglistView(true);
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
// TODO Auto-generated method stub
MenuInflater inflater = getMenuInflater();
inflater.inflate(R.menu.log, menu);
return true;
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case R.id.action_clearlog:
// User chose the "Settings" item, show the app settings UI...
clearLog();
return true;
case R.id.action_reverseshow:
showReverse();
return true;
default:
// If we got here, the user's action was not recognized.
// Invoke the superclass to handle it.
return super.onOptionsItemSelected(item);
}
}
@Override
protected void onResume() {
super.onResume();
setLogText();
}
}
================================================
FILE: app/src/main/java/com/weihuagu/receiptnotice/view/FollowThirdAppActivity.java
================================================
package com.weihuagu.receiptnotice.view;
import android.os.Bundle;
import android.widget.EditText;
import android.widget.TextView;
import androidx.annotation.Nullable;
import androidx.appcompat.app.AppCompatActivity;
import com.weihuagu.receiptnotice.R;
public class FollowThirdAppActivity extends AppCompatActivity {
private EditText pkg;
private EditText keyword;
private EditText type;
@Override
protected void onCreate(@Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_followthirdapp);
}
private void initView() {
pkg=(EditText)findViewById(R.id.pkg);
keyword=(EditText)findViewById(R.id.pkg);
type=(EditText)findViewById(R.id.pkg);
}
}
================================================
FILE: app/src/main/java/com/weihuagu/receiptnotice/view/HelloFragment.java
================================================
package com.weihuagu.receiptnotice.view;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;
import android.widget.Toast;
import androidx.annotation.Nullable;
import androidx.fragment.app.Fragment;
import androidx.lifecycle.Observer;
import com.jeremyliao.liveeventbus.LiveEventBus;
import com.weihuagu.receiptnotice.MainApplication;
import com.weihuagu.receiptnotice.R;
import com.weihuagu.receiptnotice.util.LogUtil;
import com.weihuagu.receiptnotice.util.PreferenceUtil;
public class HelloFragment extends Fragment {
private TextView numofpush;
private TextView posturl;
private View rootview;
private PreferenceUtil preference;
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
rootview=inflater.inflate(R.layout.fragment_hello,container, false);
return rootview;
}
@Override
public void onActivityCreated(@Nullable Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
initView();
subMessage();
}
private void initView(){
preference=new PreferenceUtil(getContext());
numofpush=(TextView)rootview.findViewById(R.id.numofpush);
setTextWithNumofpush();
posturl=(TextView)rootview.findViewById(R.id.posturl);
setTextWithPosturl();
}
private void setTextWithNumofpush(){
numofpush.setText("推送次数"+preference.getNumOfPush());
}
private void setTextWithPosturl(){
if(preference.getPostUrl()!=null)
posturl.setText("目前的推送地址:"+preference.getPostUrl());
}
private void resetText(){
setTextWithPosturl();
setTextWithNumofpush();
}
private void subMessage(){
LiveEventBus
.get("message_finished_one_post",String[].class)
.observeForever(new Observer() {
@Override
public void onChanged(@Nullable String[] testpostbean) {
resetText();
}
});
LiveEventBus
.get("user_set_posturl",String.class)
.observeForever(new Observer() {
@Override
public void onChanged(@Nullable String url) {
resetText();
}
});
LiveEventBus
.get("time_interval",String.class)
.observeForever(new Observer() {
@Override
public void onChanged(@Nullable String baseinterval) {
Toast.makeText(MainApplication.getAppContext(), "接受到一分钟间隔事件,更新推送次数",
Toast.LENGTH_SHORT).show();
LogUtil.debugLog("接受到一分钟一次的时间间隔事件");
resetText();
}
});
}
}
================================================
FILE: app/src/main/java/com/weihuagu/receiptnotice/view/HomeFragmentsAdapter.java
================================================
package com.weihuagu.receiptnotice.view;
import androidx.annotation.NonNull;
import androidx.fragment.app.Fragment;
import androidx.fragment.app.FragmentActivity;
import androidx.viewpager2.adapter.FragmentStateAdapter;
import java.util.ArrayList;
public class HomeFragmentsAdapter extends FragmentStateAdapter {
private ArrayList fragmentslist = new ArrayList<>();
public HomeFragmentsAdapter(@NonNull FragmentActivity fragmentActivity) {
super(fragmentActivity);
fragmentslist.add(new HelloFragment());
fragmentslist.add(new LogListFragment());
}
@NonNull
@Override
public Fragment createFragment(int position) {
return fragmentslist.get(position);
}
@Override
public int getItemCount() {
return fragmentslist.size();
}
}
================================================
FILE: app/src/main/java/com/weihuagu/receiptnotice/view/IllustrateDecryptActivity.java
================================================
package com.weihuagu.receiptnotice.view;
import android.os.Bundle;
import androidx.annotation.Nullable;
import androidx.appcompat.app.AppCompatActivity;
import android.widget.TextView;
import com.weihuagu.receiptnotice.util.PreferenceUtil;
import com.weihuagu.receiptnotice.R;
public class IllustrateDecryptActivity extends AppCompatActivity {
private TextView text_method;
private TextView text_passwd;
private TextView text_iv;
private PreferenceUtil preference;
private void initView() {
text_method = (TextView) findViewById(R.id.info_text_method);
text_passwd = (TextView) findViewById(R.id.info_text_passwd);
text_iv = (TextView) findViewById(R.id.info_text_iv);
preference=new PreferenceUtil(getBaseContext());
}
@Override
protected void onCreate(@Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_illustratedecrypt);
initView();
setText();
}
private void setText(){
String encrypt_type=preference.getEncryptMethod();
if(encrypt_type==null){
text_method.setText("您没有设置加密方法");
return;
}
if(encrypt_type.equals("des")){
String method="DES/CBC/PKCS5Padding";
text_method.setText("解密的方法为:"+method);
String key=preference.getPasswd();
if(key!=null){
text_passwd.setText("解密秘钥为:"+key+"(des秘钥必须为8位,如果你设置的不是8位,请修改)");
text_iv.setText("解密的初始化向量为:"+key);
}
}
if(encrypt_type.equals("md5")){
text_method.setText("解密的方法为:"+"md5校验");
String key=preference.getPasswd();
if(key!=null){
text_passwd.setText("md5加密方法为md5(md5(price + type) + secretkey)");
}
}
}
}
================================================
FILE: app/src/main/java/com/weihuagu/receiptnotice/view/LogListAdapter.java
================================================
package com.weihuagu.receiptnotice.view;
import android.view.View;
import android.view.ViewGroup;
import androidx.recyclerview.widget.RecyclerView;
import androidx.recyclerview.widget.RecyclerView.Adapter;
import android.view.LayoutInflater;
import android.widget.TextView;
import android.content.Context;
import com.weihuagu.receiptnotice.util.LogUtil;
import com.weihuagu.receiptnotice.R;
import java.util.ArrayList;
public class LogListAdapter extends Adapter{
private final LayoutInflater mLayoutInflater;
private ArrayList loglist;
LogListAdapter(Context context){
mLayoutInflater = LayoutInflater.from(context);
}
public void setLoglist(ArrayList loglist){
this.loglist=loglist;
}
@Override
public int getItemCount() {
return loglist == null ? 0 : loglist.size();
}
@Override
public void onBindViewHolder(RecyclerHolder holder, int position) {
String onerecord=(String)loglist.get(position);
if(holder.recordtext==null)
return;
if(onerecord!=null)
holder.recordtext.setText(onerecord);
else
LogUtil.debugLogWithDeveloper("获取到的loglist 的item text为空");
}
@Override
public RecyclerHolder onCreateViewHolder(ViewGroup parent, int viewType) {
return new RecyclerHolder(mLayoutInflater.inflate(R.layout.item_log_text, parent, false));
}
class RecyclerHolder extends RecyclerView.ViewHolder {
private TextView recordtext;
RecyclerHolder(View view){
super(view);
recordtext=view.findViewById(R.id.text_view);
}
}
}
================================================
FILE: app/src/main/java/com/weihuagu/receiptnotice/view/LogListFragment.java
================================================
package com.weihuagu.receiptnotice.view;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Toast;
import androidx.annotation.Nullable;
import androidx.fragment.app.Fragment;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import androidx.lifecycle.Observer;
import com.jeremyliao.liveeventbus.LiveEventBus;
import com.weihuagu.receiptnotice.util.FileLogUtil;
import com.weihuagu.receiptnotice.util.LogUtil;
import com.weihuagu.receiptnotice.MainApplication;
import com.weihuagu.receiptnotice.util.message.MessageConsumer;
import com.weihuagu.receiptnotice.R;
import java.util.ArrayList;
import java.util.Collections;
public class LogListFragment extends Fragment implements MessageConsumer {
private RecyclerView recyclerView;
private LogListAdapter mAdapter;
private ArrayList loglist;
private RecyclerView.LayoutManager layoutManager;
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
return inflater.inflate(R.layout.fragment_loglist, container, false);
}
@Override
public void onActivityCreated(@Nullable Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
initLoglistView(false);
subMessage();
}
private void initLoglistView(boolean reverseorder) {
recyclerView = (RecyclerView) getView().findViewById(R.id.my_recycler_view);
layoutManager = new LinearLayoutManager(getContext());
recyclerView.setLayoutManager(layoutManager);
mAdapter = new LogListAdapter(getContext());
loglist = FileLogUtil.getLogList();
if (loglist == null) {
loglist = new ArrayList();
loglist.add("推送记录为空");
}
//LogUtil.debugLogWithDeveloper("打印通过filelogutil获取到的file log list");
if(reverseorder)
Collections.reverse(loglist);
mAdapter.setLoglist(loglist);
recyclerView.setAdapter(mAdapter);
}
private void clearLog() {
FileLogUtil.clearLogFile();
loglist.clear();
mAdapter.notifyDataSetChanged();
Toast.makeText(MainApplication.getAppContext(), "已经清空日志", Toast.LENGTH_SHORT).show();
}
private void showReverse() {
initLoglistView(true);
}
private void updateList() {
loglist.clear();
loglist.addAll(FileLogUtil.getLogList());
mAdapter.notifyDataSetChanged();
LogUtil.debugLog("更新Loglist in Fragment列表:");
}
public void subMessage() {
LiveEventBus
.get("update_recordlist", String.class)
.observe(this, new Observer() {
@Override
public void onChanged(@Nullable String s) {
LogUtil.debugLog("收到订阅消息:update_recordlist " + s);
updateList();
}
});
}
}
================================================
FILE: app/src/main/java/com/weihuagu/receiptnotice/view/MainActivity.java
================================================
package com.weihuagu.receiptnotice.view;
import androidx.appcompat.app.AlertDialog;
import androidx.appcompat.app.AppCompatActivity;
import android.content.Context;
import android.content.DialogInterface;
import android.view.MenuItem;
import android.view.Menu;
import android.content.SharedPreferences;
import android.widget.Toast;
import android.content.Intent;
import android.os.Bundle;
import androidx.core.app.NotificationManagerCompat;
import android.view.View;
import android.widget.Button;
import android.widget.AutoCompleteTextView;
import com.google.android.material.floatingactionbutton.FloatingActionButton;
import androidx.appcompat.widget.Toolbar;
import android.view.MenuInflater;
import android.widget.ArrayAdapter;
import androidx.viewpager2.widget.ViewPager2;
import com.github.pedrovgs.lynx.LynxConfig;
import com.github.pedrovgs.lynx.LynxActivity;
import com.weihuagu.receiptnotice.MainApplication;
import com.weihuagu.receiptnotice.util.PreferenceUtil;
import com.weihuagu.receiptnotice.R;
import com.weihuagu.receiptnotice.util.message.MessageSendBus;
public class MainActivity extends AppCompatActivity implements View.OnClickListener {
private static final String TAG = "MainActivity";
private Toolbar myToolbar;
private ViewPager2 viewpage;
private Button btnsetposturl;
private FloatingActionButton btnshowlog;
private AutoCompleteTextView posturltextview;
private SharedPreferences sp;
public PreferenceUtil preference ;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
initView();
posturlSuggestion();
}
private void initView() {
preference = new PreferenceUtil(this);
sp = getSharedPreferences("url", Context.MODE_PRIVATE);
myToolbar = (Toolbar) findViewById(R.id.my_toolbar);
setSupportActionBar(myToolbar);
ViewPager2 viewpage = findViewById(R.id.viewpager);
HomeFragmentsAdapter viewpageadapter = new HomeFragmentsAdapter(this);
viewpage.setAdapter(viewpageadapter);
btnsetposturl = (Button) findViewById(R.id.btnsetposturl);
btnsetposturl.setOnClickListener(this);
btnshowlog = (FloatingActionButton) findViewById(R.id.floatingshowlog);
btnshowlog.setOnClickListener(this);
posturltextview = (AutoCompleteTextView) findViewById(R.id.posturl);
if (getPostUrl() != null)
posturltextview.setHint(getPostUrl());
}
private void setListerner() {
}
@Override
protected void onResume() {
super.onResume();
boolean isAuthor = isNotificationServiceEnable();
if (!preference.isAgreeUserAgreement()) {
jumpUserAgreement();
}
if (!isAuthor) {
//直接跳转通知授权界面
//android.settings.ACTION_NOTIFICATION_LISTENER_SETTINGS是API 22才加入到Settings里,这里直接写死
startActivity(new Intent("android.settings.ACTION_NOTIFICATION_LISTENER_SETTINGS"));
}
}
@Override
protected void onDestroy() {
super.onDestroy();
}
/**
* 是否已授权
*
* @return
*/
private boolean isNotificationServiceEnable() {
return NotificationManagerCompat.getEnabledListenerPackages(this).contains(getPackageName());
}
@Override
public void onClick(View v) {
switch (v.getId()) {
case R.id.btnsetposturl:
posturltextview.setHint(null);
setPostUrl();
break;
case R.id.floatingshowlog:
showLog();
break;
}
}
private void setPostUrl() {
PreferenceUtil preference=new PreferenceUtil(getBaseContext());
preference.setPostUrl(posturltextview.getText().toString());
MessageSendBus.userMessageWithSetPostUrl(posturltextview.getText().toString());
Toast.makeText(getApplicationContext(), "已经设置posturl为:" + preference.getPostUrl(),
Toast.LENGTH_SHORT).show();
}
private String getPostUrl() {
PreferenceUtil preference=new PreferenceUtil(MainApplication.getAppContext());
return preference.getPostUrl();
}
private void jumpUserAgreement() {
showAgreeMentDialog();
}
private void posturlSuggestion() {
String[] str = new String[2];
str[0] = "";
if(getPostUrl()!=null)
str[1] = getPostUrl();
else str[1] = "";
posturltextview.setThreshold(0);
ArrayAdapter adapter = new ArrayAdapter(getApplicationContext(), android.R.layout.simple_list_item_1, str);
posturltextview.setAdapter(adapter);
posturltextview.setOnFocusChangeListener(new View.OnFocusChangeListener() {
@Override
public void onFocusChange(View v, boolean hasFocus) {
AutoCompleteTextView view = (AutoCompleteTextView) v;
if (hasFocus) {
view.showDropDown();
}
}
});
//Toast.makeText(getApplicationContext(), str[0], Toast.LENGTH_SHORT).show();
}
private void showLog() {
//startActivity(new Intent(this, LogActivity.class));
openLynxActivity();
}
private void openLynxActivity() {
LynxConfig lynxConfig = new LynxConfig();
lynxConfig.setMaxNumberOfTracesToShow(4000)
.setFilter("NLService");
Intent lynxActivityIntent = LynxActivity.getIntent(this, lynxConfig);
startActivity(lynxActivityIntent);
}
private void openSettingActivity() {
Intent intent = new Intent(MainActivity.this, PreferenceActivity.class);
startActivity(intent);
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
// TODO Auto-generated method stub
MenuInflater inflater = getMenuInflater();
inflater.inflate(R.menu.main, menu);
return true;
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case R.id.action_settings:
// User chose the "Settings" item, show the app settings UI...
openSettingActivity();
return true;
default:
// If we got here, the user's action was not recognized.
// Invoke the superclass to handle it.
return super.onOptionsItemSelected(item);
}
}
private void showAgreeMentDialog() {
AlertDialog.Builder normalDialog =
new AlertDialog.Builder(MainActivity.this);
normalDialog.setTitle("用户协议").setMessage("您必须同意该用户协议才能使用该应用。点击下方的按钮以查看完整的用户协议");
normalDialog.setPositiveButton("查看用户协议",
new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
// ...To-do
Intent intent = new Intent(getBaseContext(), UserAgreementActiviy.class);
startActivity(intent);
}
});
normalDialog.setNeutralButton("同意",
new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
// ...To-do
preference.setAgreeUserAgreement(true);
}
});
normalDialog.setNegativeButton("退出", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
// ...To-do
finish();
}
});
// 创建实例并显示
normalDialog.show();
}
}
================================================
FILE: app/src/main/java/com/weihuagu/receiptnotice/view/PreferenceActivity.java
================================================
package com.weihuagu.receiptnotice.view;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.preference.PreferenceFragment;
import android.provider.Settings;
import androidx.appcompat.app.AppCompatActivity;
import com.weihuagu.receiptnotice.util.AuthorityUtil;
import com.weihuagu.receiptnotice.MainApplication;
import com.weihuagu.receiptnotice.R;
public class PreferenceActivity extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
getFragmentManager().beginTransaction().replace(android.R.id.content, new GeneralPreferenceFragment()).commit();
}
public static class GeneralPreferenceFragment extends PreferenceFragment implements SharedPreferences.OnSharedPreferenceChangeListener {
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
addPreferencesFromResource(R.xml.pref_general);
}
@Override
public void onSharedPreferenceChanged(SharedPreferences sharedPreferences, String s) {
if (s.equals("isaccessibilityservice") && sharedPreferences.getBoolean(s, false) == true) {
if (! AuthorityUtil.isAccessibilitySettingsOn(MainApplication.getAppContext()))
startActivity(new Intent(Settings.ACTION_ACCESSIBILITY_SETTINGS));
}
}
@Override
public void onResume() {
super.onResume();
// Set up a listener whenever a key changes
getPreferenceScreen().getSharedPreferences().registerOnSharedPreferenceChangeListener(this);
}
@Override
public void onPause() {
super.onPause();
// Set up a listener whenever a key changes
getPreferenceScreen().getSharedPreferences().unregisterOnSharedPreferenceChangeListener(this);
}
}
}
================================================
FILE: app/src/main/java/com/weihuagu/receiptnotice/view/TestActiviy.java
================================================
package com.weihuagu.receiptnotice.view;
import android.os.Bundle;
import android.webkit.WebView;
import android.widget.TextView;
import androidx.annotation.Nullable;
import androidx.appcompat.app.AppCompatActivity;
import com.weihuagu.receiptnotice.R;
import com.weihuagu.receiptnotice.ForTest;
import org.w3c.dom.Text;
import android.widget.Button;
import android.view.View;
public class TestActiviy extends AppCompatActivity implements View.OnClickListener{
private TextView money;
private Button button;
@Override
protected void onCreate(@Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_test);
money = (TextView) findViewById(R.id.money);
button = (Button) findViewById(R.id.action_nitification);
button.setOnClickListener(this);
}
@Override
public void onClick(View v) {
switch (v.getId()) {
case R.id.action_nitification:
new ForTest();
break;
}
}
}
================================================
FILE: app/src/main/java/com/weihuagu/receiptnotice/view/UserAgreementActiviy.java
================================================
package com.weihuagu.receiptnotice.view;
import android.os.Bundle;
import android.webkit.WebView;
import androidx.annotation.Nullable;
import androidx.appcompat.app.AppCompatActivity;
import com.weihuagu.receiptnotice.R;
public class UserAgreementActiviy extends AppCompatActivity {
WebView webView =null;
@Override
protected void onCreate(@Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_useragreement);
webView = (WebView) findViewById(R.id.webview);
webView.loadUrl("file:///android_asset/web/useragreement.html");
}
}
================================================
FILE: app/src/main/res/drawable/ic_launcher_background.xml
================================================
================================================
FILE: app/src/main/res/drawable-v24/ic_launcher_foreground.xml
================================================
================================================
FILE: app/src/main/res/layout/activity_followthirdapp.xml
================================================
================================================
FILE: app/src/main/res/layout/activity_illustratedecrypt.xml
================================================
================================================
FILE: app/src/main/res/layout/activity_log.xml
================================================
================================================
FILE: app/src/main/res/layout/activity_main.xml
================================================
================================================
FILE: app/src/main/res/layout/activity_test.xml
================================================
================================================
FILE: app/src/main/res/layout/activity_useragreement.xml
================================================
================================================
FILE: app/src/main/res/layout/fragment_hello.xml
================================================
================================================
FILE: app/src/main/res/layout/fragment_loglist.xml
================================================
================================================
FILE: app/src/main/res/layout/item_home_viewpage_fragment.xml
================================================
================================================
FILE: app/src/main/res/layout/item_log_text.xml
================================================
================================================
FILE: app/src/main/res/menu/log.xml
================================================
================================================
FILE: app/src/main/res/menu/main.xml
================================================
================================================
FILE: app/src/main/res/mipmap-anydpi-v26/ic_launcher.xml
================================================
================================================
FILE: app/src/main/res/mipmap-anydpi-v26/ic_launcher_round.xml
================================================
================================================
FILE: app/src/main/res/values/colors.xml
================================================
#3F51B5
#303F9F
#FF4081
================================================
FILE: app/src/main/res/values/strings.xml
================================================
receiptnotice
Setting
clear log
reverse display
earn tip
swip left to receipt record
post record
Illustrate Decrypt
set the post url
receiptnotice accessibility
receiptnotice find info by this server
set the third follow app
- des
- md5
- des
- md5
================================================
FILE: app/src/main/res/values/styles.xml
================================================
================================================
FILE: app/src/main/res/values-zh/strings.xml
================================================
接收推送
推送记录
解密说明
设置post地址
设置
清空记录
逆序显示
愿你赚很多钱
左滑切换到收款记录
receiptnotice 辅助功能
receiptnotice 需要使用此服务来获取必要的信息
设置第三方app
================================================
FILE: app/src/main/res/xml/network_security_config.xml
================================================
================================================
FILE: app/src/main/res/xml/pref_general.xml
================================================
================================================
FILE: app/src/main/res/xml/pref_headers.xml
================================================
================================================
FILE: app/src/main/res/xml/receiptnoticeaccessibilityservice_config.xml
================================================
================================================
FILE: app/src/test/java/com/weihuagu/receiptnotice/TestBankDistinguisher.java
================================================
package com.weihuagu.receiptnotice;
import com.weihuagu.receiptnotice.pushclassification.pmentay.BankDistinguisher;
import junit.framework.TestCase;
import org.junit.Test;
public class TestBankDistinguisher extends TestCase{
BankDistinguisher onedistinguisher=null;
protected void setUp() throws Exception {
super.setUp();
onedistinguisher = new BankDistinguisher();
}
@Test
public void testDistinguishByMessageContent() throws Exception{
String test1= "您尾号0345卡8月15日23:46工商银行收入(他行汇入)1,000元,余额1,000.00元。【工商银行】";
String test2= "您尾号7865卡人民币活期07:45存入10,00.00[银联入账:(特约)京东],可用余额1000.00。【浦发银行】";
String test3="【网商银行】您尾号8225的账户,于08月22日 09:32通过支付宝账户(183******13)成功转入20,000.00元。";
String test4="不是银行正确的胡乱测试短信";
String test5="【北京银行】您尾号为****的京卡于19年9月16日10:49银联入账收入1.00元。活期余额435.45元。对方账号尾号:7207。对方户名:二维码快速收款码专用";
System.out.println("test1 工商");
if(onedistinguisher.distinguishByMessageContent(test1)!=null)
System.out.println(onedistinguisher.distinguishByMessageContent(test1));
else
System.out.println("非银行短信");
////////////////////////////////////////
System.out.println("test2 浦发");
if(onedistinguisher.distinguishByMessageContent(test2)!=null)
System.out.println(onedistinguisher.distinguishByMessageContent(test2));
else
System.out.println("非银行短信");
////////////////////////////////////////
System.out.println("test3 网商");
if(onedistinguisher.distinguishByMessageContent(test3)!=null)
System.out.println(onedistinguisher.distinguishByMessageContent(test3));
else
System.out.println("非银行短信");
/////////////////////////////////
if(onedistinguisher.distinguishByMessageContent(test4)!=null)
System.out.println(onedistinguisher.distinguishByMessageContent(test4));
else
System.out.println("非银行短信");
System.out.println(onedistinguisher.distinguishByMessageContent(test5));
}
@Test
public void testExtractMoney() throws Exception{
String test1= "您尾号0345卡8月15日23:46工商银行收入(他行汇入)1,000元,余额1,000.00元。【工商银行】";
String test2= "您尾号7865卡人民币活期07:45存入10,00.00[银联入账:(特约)京东],可用余额1000.00。【浦发银行】";
String test3="【网商银行】您尾号8225的账户,于08月22日 09:32通过支付宝账户(183******13)成功转入20,000.00元。";
String test4="不是银行正确的胡乱测试短信";
System.out.println(onedistinguisher.extractMoney(test1));
}
@Test
public void testExtractCardNum() throws Exception{
String test1= "您尾号0345卡8月15日23:46工商银行收入(他行汇入)1,000元,余额1,000.00元。【工商银行】";
String test3="【网商银行】您尾号8225的账户,于08月22日 09:32通过支付宝账户(183******13)成功转入20,000.00元。";
System.out.println(onedistinguisher.extractCardNum(test1));
}
@Test
public void testExtractTime() throws Exception{
String test1= "您尾号0345卡8月15日23:46工商银行收入(他>行汇入)1,000元,余额1,000.00元。【工商银行】";
String time= "2019-09-16 22:37:37";
System.out.println(onedistinguisher.extractTime(test1,time));
}
}
================================================
FILE: app/src/test/java/com/weihuagu/receiptnotice/TestDES.java
================================================
package com.weihuagu.receiptnotice;
import com.weihuagu.receiptnotice.util.encrypt.DES;
import junit.framework.TestCase;
import org.junit.Test;
import java.util.Map;
import java.util.HashMap;
public class TestDES extends TestCase{
DES des=null;
protected void setUp() throws Exception {
super.setUp();
des =new DES("abcd12345678");
}
@Test
public void testTransferMapValue() throws Exception{
Map postmap=new HashMap();
postmap.put("time","2090 12 04");
postmap.put("title","支付宝支付");
postmap.put("money","345.56");
postmap.put("content","测试des伪造的");
des.transferMapValue(postmap);
}
}
================================================
FILE: app/src/test/java/com/weihuagu/receiptnotice/TestExternalInfoUtil.java
================================================
package com.weihuagu.receiptnotice;
import com.weihuagu.receiptnotice.util.ExternalInfoUtil;
import junit.framework.TestCase;
import org.junit.Test;
import java.util.Map;
import java.util.HashMap;
public class TestExternalInfoUtil extends TestCase{
protected void setUp() throws Exception {
super.setUp();
}
@Test
public void testGetCustomPostOption() throws Exception{
String test="test1-test1value;test2:test2vvalue;test3:test3value";
Map map1 = new HashMap(); //定义Map集合对象
map1.put("apple", "新鲜的苹果"); //向集合中添加对象
map1.put("computer", "配置优良的计算机");
map1.put("book", "堆积成山的图书");
Map haha= ExternalInfoUtil.getCustomPostOption(test);
map1.putAll(haha);
System.out.println(map1.toString());
}
}
================================================
FILE: app/src/test/java/com/weihuagu/receiptnotice/TestOneFileUtil.java
================================================
package com.weihuagu.receiptnotice;
import com.weihuagu.receiptnotice.util.OneFileUtil;
import junit.framework.TestCase;
import org.junit.Test;
public class TestOneFileUtil extends TestCase{
OneFileUtil onefile=null;
protected void setUp() throws Exception {
super.setUp();
//File testlog=new File(this.getClass().getResource("/testlog").getFile());
//onefile =new OneFileUtil(testlog);
}
@Test
public void testGetFileList() throws Exception{
// ArrayList filelist=onefile.getFileList();
// ArrayList filemergelist=onefile.mergeByFlagline("*********************************","------------------------------------------",filelist);
// System.out.println("test log file is:"+this.getClass().getResource("/testlog").toString());
// System.out.println(filemergelist.toString());
}
}
================================================
FILE: build.gradle
================================================
// Top-level build file where you can add configuration options common to all sub-projects/modules.
buildscript {
repositories {
maven { url 'http://maven.aliyun.com/nexus/content/groups/public/' }
maven { url 'http://maven.aliyun.com/nexus/content/repositories/google' }
jcenter()
google()
}
dependencies {
classpath 'com.android.tools.build:gradle:3.5.2'
// NOTE: Do not place your application dependencies here; they belong
// in the individual module build.gradle files
}
}
allprojects {
repositories {
maven { url 'http://maven.aliyun.com/nexus/content/groups/public/' }
maven { url 'http://maven.aliyun.com/nexus/content/repositories/google' }
jcenter()
maven { url 'https://jitpack.io' }
google()
}
}
task clean(type: Delete) {
delete rootProject.buildDir
}
================================================
FILE: gradle/wrapper/gradle-wrapper.properties
================================================
#Thu Dec 05 09:29:01 CST 2019
distributionBase=GRADLE_USER_HOME
distributionPath=wrapper/dists
zipStoreBase=GRADLE_USER_HOME
zipStorePath=wrapper/dists
distributionUrl=https\://services.gradle.org/distributions/gradle-5.4.1-all.zip
================================================
FILE: gradle.properties
================================================
# Project-wide Gradle settings.
# IDE (e.g. Android Studio) users:
# Gradle settings configured through the IDE *will override*
# any settings specified in this file.
# For more details on how to configure your build environment visit
# http://www.gradle.org/docs/current/userguide/build_environment.html
# Specifies the JVM arguments used for the daemon process.
# The setting is particularly useful for tweaking memory settings.
org.gradle.jvmargs=-Xmx1536m
# When configured, Gradle will run in incubating parallel mode.
# This option should only be used with decoupled projects. More details, visit
# http://www.gradle.org/docs/current/userguide/multi_project_builds.html#sec:decoupled_projects
# org.gradle.parallel=true
#如果进行安卓单元测试出现DexArchiveBuilderException
#android.enableD8=true
android.useAndroidX=true
android.enableJetifier=true
================================================
FILE: gradlew
================================================
#!/usr/bin/env bash
##############################################################################
##
## Gradle start up script for UN*X
##
##############################################################################
# Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script.
DEFAULT_JVM_OPTS=""
APP_NAME="Gradle"
APP_BASE_NAME=`basename "$0"`
# Use the maximum available, or set MAX_FD != -1 to use that value.
MAX_FD="maximum"
warn ( ) {
echo "$*"
}
die ( ) {
echo
echo "$*"
echo
exit 1
}
# OS specific support (must be 'true' or 'false').
cygwin=false
msys=false
darwin=false
case "`uname`" in
CYGWIN* )
cygwin=true
;;
Darwin* )
darwin=true
;;
MINGW* )
msys=true
;;
esac
# Attempt to set APP_HOME
# Resolve links: $0 may be a link
PRG="$0"
# Need this for relative symlinks.
while [ -h "$PRG" ] ; do
ls=`ls -ld "$PRG"`
link=`expr "$ls" : '.*-> \(.*\)$'`
if expr "$link" : '/.*' > /dev/null; then
PRG="$link"
else
PRG=`dirname "$PRG"`"/$link"
fi
done
SAVED="`pwd`"
cd "`dirname \"$PRG\"`/" >/dev/null
APP_HOME="`pwd -P`"
cd "$SAVED" >/dev/null
CLASSPATH=$APP_HOME/gradle/wrapper/gradle-wrapper.jar
# Determine the Java command to use to start the JVM.
if [ -n "$JAVA_HOME" ] ; then
if [ -x "$JAVA_HOME/jre/sh/java" ] ; then
# IBM's JDK on AIX uses strange locations for the executables
JAVACMD="$JAVA_HOME/jre/sh/java"
else
JAVACMD="$JAVA_HOME/bin/java"
fi
if [ ! -x "$JAVACMD" ] ; then
die "ERROR: JAVA_HOME is set to an invalid directory: $JAVA_HOME
Please set the JAVA_HOME variable in your environment to match the
location of your Java installation."
fi
else
JAVACMD="java"
which java >/dev/null 2>&1 || die "ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH.
Please set the JAVA_HOME variable in your environment to match the
location of your Java installation."
fi
# Increase the maximum file descriptors if we can.
if [ "$cygwin" = "false" -a "$darwin" = "false" ] ; then
MAX_FD_LIMIT=`ulimit -H -n`
if [ $? -eq 0 ] ; then
if [ "$MAX_FD" = "maximum" -o "$MAX_FD" = "max" ] ; then
MAX_FD="$MAX_FD_LIMIT"
fi
ulimit -n $MAX_FD
if [ $? -ne 0 ] ; then
warn "Could not set maximum file descriptor limit: $MAX_FD"
fi
else
warn "Could not query maximum file descriptor limit: $MAX_FD_LIMIT"
fi
fi
# For Darwin, add options to specify how the application appears in the dock
if $darwin; then
GRADLE_OPTS="$GRADLE_OPTS \"-Xdock:name=$APP_NAME\" \"-Xdock:icon=$APP_HOME/media/gradle.icns\""
fi
# For Cygwin, switch paths to Windows format before running java
if $cygwin ; then
APP_HOME=`cygpath --path --mixed "$APP_HOME"`
CLASSPATH=`cygpath --path --mixed "$CLASSPATH"`
JAVACMD=`cygpath --unix "$JAVACMD"`
# We build the pattern for arguments to be converted via cygpath
ROOTDIRSRAW=`find -L / -maxdepth 1 -mindepth 1 -type d 2>/dev/null`
SEP=""
for dir in $ROOTDIRSRAW ; do
ROOTDIRS="$ROOTDIRS$SEP$dir"
SEP="|"
done
OURCYGPATTERN="(^($ROOTDIRS))"
# Add a user-defined pattern to the cygpath arguments
if [ "$GRADLE_CYGPATTERN" != "" ] ; then
OURCYGPATTERN="$OURCYGPATTERN|($GRADLE_CYGPATTERN)"
fi
# Now convert the arguments - kludge to limit ourselves to /bin/sh
i=0
for arg in "$@" ; do
CHECK=`echo "$arg"|egrep -c "$OURCYGPATTERN" -`
CHECK2=`echo "$arg"|egrep -c "^-"` ### Determine if an option
if [ $CHECK -ne 0 ] && [ $CHECK2 -eq 0 ] ; then ### Added a condition
eval `echo args$i`=`cygpath --path --ignore --mixed "$arg"`
else
eval `echo args$i`="\"$arg\""
fi
i=$((i+1))
done
case $i in
(0) set -- ;;
(1) set -- "$args0" ;;
(2) set -- "$args0" "$args1" ;;
(3) set -- "$args0" "$args1" "$args2" ;;
(4) set -- "$args0" "$args1" "$args2" "$args3" ;;
(5) set -- "$args0" "$args1" "$args2" "$args3" "$args4" ;;
(6) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" ;;
(7) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" ;;
(8) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" "$args7" ;;
(9) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" "$args7" "$args8" ;;
esac
fi
# Split up the JVM_OPTS And GRADLE_OPTS values into an array, following the shell quoting and substitution rules
function splitJvmOpts() {
JVM_OPTS=("$@")
}
eval splitJvmOpts $DEFAULT_JVM_OPTS $JAVA_OPTS $GRADLE_OPTS
JVM_OPTS[${#JVM_OPTS[*]}]="-Dorg.gradle.appname=$APP_BASE_NAME"
exec "$JAVACMD" "${JVM_OPTS[@]}" -classpath "$CLASSPATH" org.gradle.wrapper.GradleWrapperMain "$@"
================================================
FILE: gradlew.bat
================================================
@if "%DEBUG%" == "" @echo off
@rem ##########################################################################
@rem
@rem Gradle startup script for Windows
@rem
@rem ##########################################################################
@rem Set local scope for the variables with windows NT shell
if "%OS%"=="Windows_NT" setlocal
@rem Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script.
set DEFAULT_JVM_OPTS=
set DIRNAME=%~dp0
if "%DIRNAME%" == "" set DIRNAME=.
set APP_BASE_NAME=%~n0
set APP_HOME=%DIRNAME%
@rem Find java.exe
if defined JAVA_HOME goto findJavaFromJavaHome
set JAVA_EXE=java.exe
%JAVA_EXE% -version >NUL 2>&1
if "%ERRORLEVEL%" == "0" goto init
echo.
echo ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH.
echo.
echo Please set the JAVA_HOME variable in your environment to match the
echo location of your Java installation.
goto fail
:findJavaFromJavaHome
set JAVA_HOME=%JAVA_HOME:"=%
set JAVA_EXE=%JAVA_HOME%/bin/java.exe
if exist "%JAVA_EXE%" goto init
echo.
echo ERROR: JAVA_HOME is set to an invalid directory: %JAVA_HOME%
echo.
echo Please set the JAVA_HOME variable in your environment to match the
echo location of your Java installation.
goto fail
:init
@rem Get command-line arguments, handling Windowz variants
if not "%OS%" == "Windows_NT" goto win9xME_args
if "%@eval[2+2]" == "4" goto 4NT_args
:win9xME_args
@rem Slurp the command line arguments.
set CMD_LINE_ARGS=
set _SKIP=2
:win9xME_args_slurp
if "x%~1" == "x" goto execute
set CMD_LINE_ARGS=%*
goto execute
:4NT_args
@rem Get arguments from the 4NT Shell from JP Software
set CMD_LINE_ARGS=%$
:execute
@rem Setup the command line
set CLASSPATH=%APP_HOME%\gradle\wrapper\gradle-wrapper.jar
@rem Execute Gradle
"%JAVA_EXE%" %DEFAULT_JVM_OPTS% %JAVA_OPTS% %GRADLE_OPTS% "-Dorg.gradle.appname=%APP_BASE_NAME%" -classpath "%CLASSPATH%" org.gradle.wrapper.GradleWrapperMain %CMD_LINE_ARGS%
:end
@rem End local scope for the variables with windows NT shell
if "%ERRORLEVEL%"=="0" goto mainEnd
:fail
rem Set variable GRADLE_EXIT_CONSOLE if you need the _script_ return code instead of
rem the _cmd.exe /c_ return code!
if not "" == "%GRADLE_EXIT_CONSOLE%" exit 1
exit /b 1
:mainEnd
if "%OS%"=="Windows_NT" endlocal
:omega
================================================
FILE: settings.gradle
================================================
include ':app'