├── app
├── .gitignore
├── src
│ ├── main
│ │ ├── res
│ │ │ ├── values
│ │ │ │ ├── strings.xml
│ │ │ │ ├── colors.xml
│ │ │ │ └── themes.xml
│ │ │ ├── drawable
│ │ │ │ ├── point1.png
│ │ │ │ ├── point2.png
│ │ │ │ ├── point3.png
│ │ │ │ ├── point4.png
│ │ │ │ ├── point5.png
│ │ │ │ ├── point6.png
│ │ │ │ ├── point7.png
│ │ │ │ ├── point8.png
│ │ │ │ ├── point9.png
│ │ │ │ ├── point10.png
│ │ │ │ ├── point11.png
│ │ │ │ ├── point12.png
│ │ │ │ ├── point13.png
│ │ │ │ ├── point14.png
│ │ │ │ ├── point15.png
│ │ │ │ ├── ic_launcher_foreground.xml
│ │ │ │ └── ic_launcher_background.xml
│ │ │ ├── mipmap-hdpi
│ │ │ │ ├── ic_launcher.webp
│ │ │ │ └── ic_launcher_round.webp
│ │ │ ├── mipmap-mdpi
│ │ │ │ ├── ic_launcher.webp
│ │ │ │ └── ic_launcher_round.webp
│ │ │ ├── mipmap-xhdpi
│ │ │ │ ├── ic_launcher.webp
│ │ │ │ └── ic_launcher_round.webp
│ │ │ ├── mipmap-xxhdpi
│ │ │ │ ├── ic_launcher.webp
│ │ │ │ └── ic_launcher_round.webp
│ │ │ ├── mipmap-xxxhdpi
│ │ │ │ ├── ic_launcher.webp
│ │ │ │ └── ic_launcher_round.webp
│ │ │ ├── values-night
│ │ │ │ └── themes.xml
│ │ │ ├── mipmap-anydpi
│ │ │ │ ├── ic_launcher.xml
│ │ │ │ └── ic_launcher_round.xml
│ │ │ ├── xml
│ │ │ │ ├── backup_rules.xml
│ │ │ │ └── data_extraction_rules.xml
│ │ │ └── layout
│ │ │ │ ├── activity_main.xml
│ │ │ │ └── floating_layout.xml
│ │ ├── AndroidManifest.xml
│ │ └── java
│ │ │ └── com
│ │ │ └── yangda
│ │ │ └── cardrecorder
│ │ │ ├── ImageUtils.java
│ │ │ ├── CardDetectionUtil.java
│ │ │ ├── MainActivity.java
│ │ │ └── FloatingWindowService.java
│ ├── test
│ │ └── java
│ │ │ └── com
│ │ │ └── yangda
│ │ │ └── cardrecorder
│ │ │ └── ExampleUnitTest.java
│ └── androidTest
│ │ └── java
│ │ └── com
│ │ └── yangda
│ │ └── cardrecorder
│ │ └── ExampleInstrumentedTest.java
├── proguard-rules.pro
└── build.gradle
├── .idea
├── .gitignore
├── compiler.xml
├── vcs.xml
├── misc.xml
└── gradle.xml
├── img
├── img.png
├── 98bdca77ddc635d2b3366d6002741c0.jpg
├── a5e03d0e3b8c8e28b9b52e601ff0c1e.jpg
└── fc92f3ece413e2fa4d486f8487bde90.jpg
├── gradle
└── wrapper
│ ├── gradle-wrapper.jar
│ └── gradle-wrapper.properties
├── .gitignore
├── settings.gradle
├── README.md
├── gradle.properties
├── gradlew.bat
└── gradlew
/app/.gitignore:
--------------------------------------------------------------------------------
1 | /build
--------------------------------------------------------------------------------
/.idea/.gitignore:
--------------------------------------------------------------------------------
1 | # Default ignored files
2 | /shelf/
3 | /workspace.xml
4 |
--------------------------------------------------------------------------------
/img/img.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/yangdayangda/cardRecorder/HEAD/img/img.png
--------------------------------------------------------------------------------
/app/src/main/res/values/strings.xml:
--------------------------------------------------------------------------------
1 |
2 | cardRecorder
3 |
--------------------------------------------------------------------------------
/gradle/wrapper/gradle-wrapper.jar:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/yangdayangda/cardRecorder/HEAD/gradle/wrapper/gradle-wrapper.jar
--------------------------------------------------------------------------------
/app/src/main/res/drawable/point1.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/yangdayangda/cardRecorder/HEAD/app/src/main/res/drawable/point1.png
--------------------------------------------------------------------------------
/app/src/main/res/drawable/point2.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/yangdayangda/cardRecorder/HEAD/app/src/main/res/drawable/point2.png
--------------------------------------------------------------------------------
/app/src/main/res/drawable/point3.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/yangdayangda/cardRecorder/HEAD/app/src/main/res/drawable/point3.png
--------------------------------------------------------------------------------
/app/src/main/res/drawable/point4.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/yangdayangda/cardRecorder/HEAD/app/src/main/res/drawable/point4.png
--------------------------------------------------------------------------------
/app/src/main/res/drawable/point5.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/yangdayangda/cardRecorder/HEAD/app/src/main/res/drawable/point5.png
--------------------------------------------------------------------------------
/app/src/main/res/drawable/point6.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/yangdayangda/cardRecorder/HEAD/app/src/main/res/drawable/point6.png
--------------------------------------------------------------------------------
/app/src/main/res/drawable/point7.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/yangdayangda/cardRecorder/HEAD/app/src/main/res/drawable/point7.png
--------------------------------------------------------------------------------
/app/src/main/res/drawable/point8.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/yangdayangda/cardRecorder/HEAD/app/src/main/res/drawable/point8.png
--------------------------------------------------------------------------------
/app/src/main/res/drawable/point9.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/yangdayangda/cardRecorder/HEAD/app/src/main/res/drawable/point9.png
--------------------------------------------------------------------------------
/app/src/main/res/drawable/point10.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/yangdayangda/cardRecorder/HEAD/app/src/main/res/drawable/point10.png
--------------------------------------------------------------------------------
/app/src/main/res/drawable/point11.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/yangdayangda/cardRecorder/HEAD/app/src/main/res/drawable/point11.png
--------------------------------------------------------------------------------
/app/src/main/res/drawable/point12.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/yangdayangda/cardRecorder/HEAD/app/src/main/res/drawable/point12.png
--------------------------------------------------------------------------------
/app/src/main/res/drawable/point13.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/yangdayangda/cardRecorder/HEAD/app/src/main/res/drawable/point13.png
--------------------------------------------------------------------------------
/app/src/main/res/drawable/point14.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/yangdayangda/cardRecorder/HEAD/app/src/main/res/drawable/point14.png
--------------------------------------------------------------------------------
/app/src/main/res/drawable/point15.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/yangdayangda/cardRecorder/HEAD/app/src/main/res/drawable/point15.png
--------------------------------------------------------------------------------
/img/98bdca77ddc635d2b3366d6002741c0.jpg:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/yangdayangda/cardRecorder/HEAD/img/98bdca77ddc635d2b3366d6002741c0.jpg
--------------------------------------------------------------------------------
/img/a5e03d0e3b8c8e28b9b52e601ff0c1e.jpg:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/yangdayangda/cardRecorder/HEAD/img/a5e03d0e3b8c8e28b9b52e601ff0c1e.jpg
--------------------------------------------------------------------------------
/img/fc92f3ece413e2fa4d486f8487bde90.jpg:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/yangdayangda/cardRecorder/HEAD/img/fc92f3ece413e2fa4d486f8487bde90.jpg
--------------------------------------------------------------------------------
/app/src/main/res/mipmap-hdpi/ic_launcher.webp:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/yangdayangda/cardRecorder/HEAD/app/src/main/res/mipmap-hdpi/ic_launcher.webp
--------------------------------------------------------------------------------
/app/src/main/res/mipmap-mdpi/ic_launcher.webp:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/yangdayangda/cardRecorder/HEAD/app/src/main/res/mipmap-mdpi/ic_launcher.webp
--------------------------------------------------------------------------------
/app/src/main/res/mipmap-xhdpi/ic_launcher.webp:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/yangdayangda/cardRecorder/HEAD/app/src/main/res/mipmap-xhdpi/ic_launcher.webp
--------------------------------------------------------------------------------
/app/src/main/res/mipmap-xxhdpi/ic_launcher.webp:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/yangdayangda/cardRecorder/HEAD/app/src/main/res/mipmap-xxhdpi/ic_launcher.webp
--------------------------------------------------------------------------------
/app/src/main/res/mipmap-xxxhdpi/ic_launcher.webp:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/yangdayangda/cardRecorder/HEAD/app/src/main/res/mipmap-xxxhdpi/ic_launcher.webp
--------------------------------------------------------------------------------
/app/src/main/res/mipmap-hdpi/ic_launcher_round.webp:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/yangdayangda/cardRecorder/HEAD/app/src/main/res/mipmap-hdpi/ic_launcher_round.webp
--------------------------------------------------------------------------------
/app/src/main/res/mipmap-mdpi/ic_launcher_round.webp:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/yangdayangda/cardRecorder/HEAD/app/src/main/res/mipmap-mdpi/ic_launcher_round.webp
--------------------------------------------------------------------------------
/app/src/main/res/mipmap-xhdpi/ic_launcher_round.webp:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/yangdayangda/cardRecorder/HEAD/app/src/main/res/mipmap-xhdpi/ic_launcher_round.webp
--------------------------------------------------------------------------------
/app/src/main/res/mipmap-xxhdpi/ic_launcher_round.webp:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/yangdayangda/cardRecorder/HEAD/app/src/main/res/mipmap-xxhdpi/ic_launcher_round.webp
--------------------------------------------------------------------------------
/app/src/main/res/mipmap-xxxhdpi/ic_launcher_round.webp:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/yangdayangda/cardRecorder/HEAD/app/src/main/res/mipmap-xxxhdpi/ic_launcher_round.webp
--------------------------------------------------------------------------------
/app/src/main/res/values/colors.xml:
--------------------------------------------------------------------------------
1 |
2 |
3 | #FF000000
4 | #FFFFFFFF
5 |
--------------------------------------------------------------------------------
/.idea/compiler.xml:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 |
6 |
--------------------------------------------------------------------------------
/.idea/vcs.xml:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 |
6 |
--------------------------------------------------------------------------------
/gradle/wrapper/gradle-wrapper.properties:
--------------------------------------------------------------------------------
1 | #Sat Jan 06 15:32:47 CST 2024
2 | distributionBase=GRADLE_USER_HOME
3 | distributionPath=wrapper/dists
4 | distributionUrl=https\://services.gradle.org/distributions/gradle-8.0-bin.zip
5 | zipStoreBase=GRADLE_USER_HOME
6 | zipStorePath=wrapper/dists
7 |
--------------------------------------------------------------------------------
/.gitignore:
--------------------------------------------------------------------------------
1 | *.iml
2 | .gradle
3 | /local.properties
4 | /.idea/caches
5 | /.idea/libraries
6 | /.idea/modules.xml
7 | /.idea/workspace.xml
8 | /.idea/navEditor.xml
9 | /.idea/assetWizardSettings.xml
10 | .DS_Store
11 | /build
12 | /captures
13 | .externalNativeBuild
14 | .cxx
15 | local.properties
16 |
--------------------------------------------------------------------------------
/app/src/main/res/values-night/themes.xml:
--------------------------------------------------------------------------------
1 |
2 |
3 |
7 |
--------------------------------------------------------------------------------
/app/src/main/res/mipmap-anydpi/ic_launcher.xml:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 |
6 |
--------------------------------------------------------------------------------
/app/src/main/res/mipmap-anydpi/ic_launcher_round.xml:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 |
6 |
--------------------------------------------------------------------------------
/settings.gradle:
--------------------------------------------------------------------------------
1 | pluginManagement {
2 | repositories {
3 | google()
4 | mavenCentral()
5 | gradlePluginPortal()
6 | }
7 | }
8 | dependencyResolutionManagement {
9 | repositoriesMode.set(RepositoriesMode.FAIL_ON_PROJECT_REPOS)
10 | repositories {
11 | google()
12 | mavenCentral()
13 | }
14 | }
15 |
16 | rootProject.name = "cardRecorder"
17 | include ':app'
18 |
--------------------------------------------------------------------------------
/.idea/misc.xml:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 |
6 |
7 |
8 |
9 |
--------------------------------------------------------------------------------
/app/src/main/res/values/themes.xml:
--------------------------------------------------------------------------------
1 |
2 |
3 |
7 |
8 |
9 |
--------------------------------------------------------------------------------
/app/src/test/java/com/yangda/cardrecorder/ExampleUnitTest.java:
--------------------------------------------------------------------------------
1 | package com.yangda.cardrecorder;
2 |
3 | import org.junit.Test;
4 |
5 | import static org.junit.Assert.*;
6 |
7 | /**
8 | * Example local unit test, which will execute on the development machine (host).
9 | *
10 | * @see Testing documentation
11 | */
12 | public class ExampleUnitTest {
13 | @Test
14 | public void addition_isCorrect() {
15 | assertEquals(4, 2 + 2);
16 | }
17 | }
--------------------------------------------------------------------------------
/app/src/main/res/xml/backup_rules.xml:
--------------------------------------------------------------------------------
1 |
8 |
9 |
13 |
--------------------------------------------------------------------------------
/app/src/main/res/xml/data_extraction_rules.xml:
--------------------------------------------------------------------------------
1 |
6 |
7 |
8 |
12 |
13 |
19 |
--------------------------------------------------------------------------------
/.idea/gradle.xml:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 |
19 |
20 |
--------------------------------------------------------------------------------
/README.md:
--------------------------------------------------------------------------------
1 | ## 基于安卓opencv实现的欢乐斗地主记牌器
2 |
3 | ### 使用效果图
4 | 停止后面显示的信息分别为玩家一的出牌区域识别的点数,玩家二的点数,以及一个时间(每次识别屏幕一次都会更新一次,单位为s)
5 |
6 | 
7 |
8 | ### 安装与使用
9 |
10 | 安装好应用程序以后,点击打开,此时会申请开启悬浮窗权限,以及录屏权限,同意即可。
11 |
12 | 
13 |
14 | 到达游戏界面,等待发牌以后点击开始,此时程序会初始化,记牌器的数量就是全部牌数量减去自己手牌的数量,只有在初始化时才会减去手牌的数量,所以需要在每次游戏开始时,都需要点击开始按钮。可以看到,记牌器的数量就是减去手牌数量以后的牌数。
15 |
16 | 程序的运行逻辑大致如下:
17 |
18 | 1.开始时识别手牌区域,记牌器显示手牌外还剩余多少牌。
19 |
20 | 2.每间隔1.5s(该时间可以设置)获取一次屏幕截图,识别玩家一和玩家二的出牌区域点数,如果当前时间和上次时间的点数相同,就不更新记牌器,如果不同,说明该玩家出了新的牌,那么更新记牌器。程序识别牌点数需要耗费一定时间,所以记牌器显示的时间间隔一定是大于1.5s的。
21 |
22 | 
23 |
24 | 此程序使用的是opecv的模板匹配进行识别牌名的,所以涉及到像素操作,在某些尺寸的手机上面运行可能会出错(虽然程序做了不同屏幕的适配),可以自行修改项目里面的出牌区域或者每一个点数的截图。在手机屏幕为3200x1440和2400x1080上面运行是没有问题的。
25 |
26 | 
27 |
--------------------------------------------------------------------------------
/app/proguard-rules.pro:
--------------------------------------------------------------------------------
1 | # Add project specific ProGuard rules here.
2 | # You can control the set of applied configuration files using the
3 | # proguardFiles setting in build.gradle.
4 | #
5 | # For more details, see
6 | # http://developer.android.com/guide/developing/tools/proguard.html
7 |
8 | # If your project uses WebView with JS, uncomment the following
9 | # and specify the fully qualified class name to the JavaScript interface
10 | # class:
11 | #-keepclassmembers class fqcn.of.javascript.interface.for.webview {
12 | # public *;
13 | #}
14 |
15 | # Uncomment this to preserve the line number information for
16 | # debugging stack traces.
17 | #-keepattributes SourceFile,LineNumberTable
18 |
19 | # If you keep the line number information, uncomment this to
20 | # hide the original source file name.
21 | #-renamesourcefileattribute SourceFile
--------------------------------------------------------------------------------
/app/src/androidTest/java/com/yangda/cardrecorder/ExampleInstrumentedTest.java:
--------------------------------------------------------------------------------
1 | package com.yangda.cardrecorder;
2 |
3 | import android.content.Context;
4 |
5 | import androidx.test.platform.app.InstrumentationRegistry;
6 | import androidx.test.ext.junit.runners.AndroidJUnit4;
7 |
8 | import org.junit.Test;
9 | import org.junit.runner.RunWith;
10 |
11 | import static org.junit.Assert.*;
12 |
13 | /**
14 | * Instrumented test, which will execute on an Android device.
15 | *
16 | * @see Testing documentation
17 | */
18 | @RunWith(AndroidJUnit4.class)
19 | public class ExampleInstrumentedTest {
20 | @Test
21 | public void useAppContext() {
22 | // Context of the app under test.
23 | Context appContext = InstrumentationRegistry.getInstrumentation().getTargetContext();
24 | assertEquals("com.yangda.cardrecorder", appContext.getPackageName());
25 | }
26 | }
--------------------------------------------------------------------------------
/app/build.gradle:
--------------------------------------------------------------------------------
1 | plugins {
2 | id 'com.android.application'
3 | }
4 |
5 | android {
6 | namespace 'com.yangda.cardrecorder'
7 | compileSdk 33
8 |
9 | defaultConfig {
10 | applicationId "com.yangda.cardrecorder"
11 | minSdk 26
12 | targetSdk 33
13 | versionCode 1
14 | versionName "1.0"
15 |
16 | testInstrumentationRunner "androidx.test.runner.AndroidJUnitRunner"
17 | }
18 |
19 | buildTypes {
20 | release {
21 | minifyEnabled false
22 | proguardFiles getDefaultProguardFile('proguard-android-optimize.txt'), 'proguard-rules.pro'
23 | }
24 | }
25 | compileOptions {
26 | sourceCompatibility JavaVersion.VERSION_1_8
27 | targetCompatibility JavaVersion.VERSION_1_8
28 | }
29 | }
30 |
31 | dependencies {
32 | implementation 'com.quickbirdstudios:opencv:4.5.3.0'
33 | implementation 'androidx.appcompat:appcompat:1.6.1'
34 | implementation 'com.google.android.material:material:1.8.0'
35 | implementation 'androidx.constraintlayout:constraintlayout:2.1.4'
36 | testImplementation 'junit:junit:4.13.2'
37 | androidTestImplementation 'androidx.test.ext:junit:1.1.5'
38 | androidTestImplementation 'androidx.test.espresso:espresso-core:3.5.1'
39 | }
--------------------------------------------------------------------------------
/gradle.properties:
--------------------------------------------------------------------------------
1 | # Project-wide Gradle settings.
2 | # IDE (e.g. Android Studio) users:
3 | # Gradle settings configured through the IDE *will override*
4 | # any settings specified in this file.
5 | # For more details on how to configure your build environment visit
6 | # http://www.gradle.org/docs/current/userguide/build_environment.html
7 | # Specifies the JVM arguments used for the daemon process.
8 | # The setting is particularly useful for tweaking memory settings.
9 | org.gradle.jvmargs=-Xmx2048m -Dfile.encoding=UTF-8
10 | # When configured, Gradle will run in incubating parallel mode.
11 | # This option should only be used with decoupled projects. More details, visit
12 | # http://www.gradle.org/docs/current/userguide/multi_project_builds.html#sec:decoupled_projects
13 | # org.gradle.parallel=true
14 | # AndroidX package structure to make it clearer which packages are bundled with the
15 | # Android operating system, and which are packaged with your app's APK
16 | # https://developer.android.com/topic/libraries/support-library/androidx-rn
17 | android.useAndroidX=true
18 | # Enables namespacing of each library's R class so that its R class includes only the
19 | # resources declared in the library itself and none from the library's dependencies,
20 | # thereby reducing the size of the R class for that library
21 | android.nonTransitiveRClass=true
--------------------------------------------------------------------------------
/app/src/main/AndroidManifest.xml:
--------------------------------------------------------------------------------
1 |
2 |
4 |
5 |
7 |
8 |
18 |
21 |
22 |
23 |
24 |
25 |
26 |
27 |
31 |
32 |
33 |
--------------------------------------------------------------------------------
/app/src/main/res/drawable/ic_launcher_foreground.xml:
--------------------------------------------------------------------------------
1 |
7 |
8 |
9 |
15 |
18 |
21 |
22 |
23 |
24 |
30 |
--------------------------------------------------------------------------------
/app/src/main/res/layout/activity_main.xml:
--------------------------------------------------------------------------------
1 |
2 |
8 |
9 |
21 |
22 |
30 |
31 |
36 |
37 |
43 |
44 |
50 |
51 |
52 |
53 |
54 |
--------------------------------------------------------------------------------
/gradlew.bat:
--------------------------------------------------------------------------------
1 | @rem
2 | @rem Copyright 2015 the original author or authors.
3 | @rem
4 | @rem Licensed under the Apache License, Version 2.0 (the "License");
5 | @rem you may not use this file except in compliance with the License.
6 | @rem You may obtain a copy of the License at
7 | @rem
8 | @rem https://www.apache.org/licenses/LICENSE-2.0
9 | @rem
10 | @rem Unless required by applicable law or agreed to in writing, software
11 | @rem distributed under the License is distributed on an "AS IS" BASIS,
12 | @rem WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 | @rem See the License for the specific language governing permissions and
14 | @rem limitations under the License.
15 | @rem
16 |
17 | @if "%DEBUG%" == "" @echo off
18 | @rem ##########################################################################
19 | @rem
20 | @rem Gradle startup script for Windows
21 | @rem
22 | @rem ##########################################################################
23 |
24 | @rem Set local scope for the variables with windows NT shell
25 | if "%OS%"=="Windows_NT" setlocal
26 |
27 | set DIRNAME=%~dp0
28 | if "%DIRNAME%" == "" set DIRNAME=.
29 | set APP_BASE_NAME=%~n0
30 | set APP_HOME=%DIRNAME%
31 |
32 | @rem Resolve any "." and ".." in APP_HOME to make it shorter.
33 | for %%i in ("%APP_HOME%") do set APP_HOME=%%~fi
34 |
35 | @rem Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script.
36 | set DEFAULT_JVM_OPTS="-Xmx64m" "-Xms64m"
37 |
38 | @rem Find java.exe
39 | if defined JAVA_HOME goto findJavaFromJavaHome
40 |
41 | set JAVA_EXE=java.exe
42 | %JAVA_EXE% -version >NUL 2>&1
43 | if "%ERRORLEVEL%" == "0" goto execute
44 |
45 | echo.
46 | echo ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH.
47 | echo.
48 | echo Please set the JAVA_HOME variable in your environment to match the
49 | echo location of your Java installation.
50 |
51 | goto fail
52 |
53 | :findJavaFromJavaHome
54 | set JAVA_HOME=%JAVA_HOME:"=%
55 | set JAVA_EXE=%JAVA_HOME%/bin/java.exe
56 |
57 | if exist "%JAVA_EXE%" goto execute
58 |
59 | echo.
60 | echo ERROR: JAVA_HOME is set to an invalid directory: %JAVA_HOME%
61 | echo.
62 | echo Please set the JAVA_HOME variable in your environment to match the
63 | echo location of your Java installation.
64 |
65 | goto fail
66 |
67 | :execute
68 | @rem Setup the command line
69 |
70 | set CLASSPATH=%APP_HOME%\gradle\wrapper\gradle-wrapper.jar
71 |
72 |
73 | @rem Execute Gradle
74 | "%JAVA_EXE%" %DEFAULT_JVM_OPTS% %JAVA_OPTS% %GRADLE_OPTS% "-Dorg.gradle.appname=%APP_BASE_NAME%" -classpath "%CLASSPATH%" org.gradle.wrapper.GradleWrapperMain %*
75 |
76 | :end
77 | @rem End local scope for the variables with windows NT shell
78 | if "%ERRORLEVEL%"=="0" goto mainEnd
79 |
80 | :fail
81 | rem Set variable GRADLE_EXIT_CONSOLE if you need the _script_ return code instead of
82 | rem the _cmd.exe /c_ return code!
83 | if not "" == "%GRADLE_EXIT_CONSOLE%" exit 1
84 | exit /b 1
85 |
86 | :mainEnd
87 | if "%OS%"=="Windows_NT" endlocal
88 |
89 | :omega
90 |
--------------------------------------------------------------------------------
/app/src/main/java/com/yangda/cardrecorder/ImageUtils.java:
--------------------------------------------------------------------------------
1 | package com.yangda.cardrecorder;
2 |
3 | import android.content.ContentResolver;
4 | import android.content.ContentValues;
5 | import android.content.Context;
6 | import android.graphics.Bitmap;
7 | import android.graphics.Matrix;
8 | import android.media.Image;
9 | import android.net.Uri;
10 | import android.os.Environment;
11 | import android.provider.MediaStore;
12 | import android.util.DisplayMetrics;
13 | import android.view.Display;
14 | import android.view.WindowManager;
15 |
16 | import java.io.IOException;
17 | import java.io.OutputStream;
18 | import java.lang.reflect.Method;
19 | import java.nio.ByteBuffer;
20 |
21 | public class ImageUtils {
22 | public static Bitmap imageToBitmap(Image image) {
23 | int width = image.getWidth();
24 | int height = image.getHeight();
25 | Image.Plane[] planes = image.getPlanes();
26 | ByteBuffer buffer = planes[0].getBuffer();
27 | // 两个像素的距离
28 | int pixelStride = planes[0].getPixelStride();
29 | // 整行的距离
30 | int rowStride = planes[0].getRowStride();
31 | int rowPadding = rowStride - pixelStride * width;
32 | Bitmap bitmap = Bitmap.createBitmap(width + rowPadding / pixelStride, height, Bitmap.Config.ARGB_8888);
33 | bitmap.copyPixelsFromBuffer(buffer);
34 | bitmap = Bitmap.createBitmap(bitmap, 0, 0, width, height);
35 |
36 | image.close();
37 | return bitmap;
38 | }
39 |
40 | /**
41 | * 通过反射,获取包含虚拟键的整体屏幕高度
42 | * @return
43 | */
44 | public static int getHasVirtualKey(WindowManager windowManager) {
45 | int dpi = 0;
46 | Display display = windowManager.getDefaultDisplay();
47 | DisplayMetrics dm = new DisplayMetrics();
48 | @SuppressWarnings("rawtypes")
49 | Class c;
50 | try {
51 | c = Class.forName("android.view.Display");
52 | @SuppressWarnings("unchecked")
53 | Method method = c.getMethod("getRealMetrics", DisplayMetrics.class);
54 | method.invoke(display, dm);
55 | dpi = dm.heightPixels;
56 | } catch (Exception e) {
57 | e.printStackTrace();
58 | }
59 | return dpi;
60 | }
61 |
62 | public static Bitmap cropBitmap(Bitmap sourceBitmap, int[] area) {
63 | Bitmap croppedBitmap = Bitmap.createBitmap(sourceBitmap, area[0], area[1], area[2] - area[0], area[3] - area[1]);
64 | return croppedBitmap;
65 | }
66 |
67 | public static void saveScreenshot(Context context, Bitmap screenshot, String fileName) {
68 | if (screenshot != null) {
69 | ContentValues values = new ContentValues();
70 | values.put(MediaStore.Images.Media.DISPLAY_NAME, fileName);
71 | values.put(MediaStore.Images.Media.MIME_TYPE, "image/png");
72 | values.put(MediaStore.Images.Media.RELATIVE_PATH, Environment.DIRECTORY_PICTURES);
73 |
74 | ContentResolver resolver = context.getContentResolver();
75 | Uri imageUri = resolver.insert(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, values);
76 | try {
77 | if (imageUri != null) {
78 | OutputStream outputStream = resolver.openOutputStream(imageUri);
79 | if (outputStream != null) {
80 | screenshot.compress(Bitmap.CompressFormat.PNG, 100, outputStream);
81 | outputStream.close();
82 | }
83 | }
84 | } catch (IOException e) {
85 | e.printStackTrace();
86 | }
87 | }
88 | }
89 |
90 | /**
91 | * 把bitmap按照比例转换成scale的width
92 | * @param bm 原始图片
93 | * @param scale 目标宽度
94 | * @return
95 | */
96 | public static Bitmap setImgSize(Bitmap bm, float scale){
97 | // 获得图片的宽高.
98 | int width = bm.getWidth();
99 | int height = bm.getHeight();
100 | // 计算缩放比例.
101 | float k = scale / width;
102 | // 取得想要缩放的matrix参数.
103 | Matrix matrix = new Matrix();
104 | matrix.postScale(k, k);
105 | // 得到新的图片.
106 | Bitmap newbm = Bitmap.createBitmap(bm, 0, 0, width, height, matrix, true);
107 | return newbm;
108 | }
109 | }
110 |
--------------------------------------------------------------------------------
/app/src/main/java/com/yangda/cardrecorder/CardDetectionUtil.java:
--------------------------------------------------------------------------------
1 | package com.yangda.cardrecorder;
2 |
3 | import android.content.Context;
4 | import android.graphics.Bitmap;
5 | import android.graphics.BitmapFactory;
6 |
7 | import org.opencv.android.Utils;
8 | import org.opencv.core.Mat;
9 | import org.opencv.core.Point;
10 | import org.opencv.core.Rect;
11 | import org.opencv.core.Size;
12 | import org.opencv.imgproc.Imgproc;
13 |
14 | import java.util.ArrayList;
15 | import java.util.List;
16 |
17 | public class CardDetectionUtil {
18 | /**
19 | * 模板匹配函数,threshold为阈值,0-1,越大表示要求越高
20 | * @param bgBitmap
21 | * @param templeteBitmap
22 | * @param threshold
23 | * @return
24 | */
25 | public static int matchImgNum(Bitmap bgBitmap, Bitmap templeteBitmap, double threshold) {
26 | // 将 Bitmap 转换为 OpenCV 的 Mat 对象
27 | Mat bgMat = new Mat();
28 | Mat templeteMat = new Mat();
29 | Utils.bitmapToMat(bgBitmap, bgMat);
30 | Utils.bitmapToMat(templeteBitmap, templeteMat);
31 |
32 | //使用图像金字塔进行下采样,加快查找时间
33 | Imgproc.pyrDown(bgMat, bgMat, new Size(bgMat.cols() / 2, bgMat.rows() / 2));
34 | Imgproc.pyrDown(templeteMat, templeteMat, new Size(templeteMat.cols() / 2, templeteMat.rows() / 2));
35 |
36 | // 执行模板匹配
37 | Mat result = new Mat();
38 | Imgproc.matchTemplate(bgMat, templeteMat, result, Imgproc.TM_CCOEFF_NORMED);
39 |
40 | // 设置阈值,找到匹配得分高于阈值的区域
41 | List detectedRectangles = new ArrayList<>();
42 | for (int row = 0; row < result.rows(); row++) {
43 | for (int col = 0; col < result.cols(); col++) {
44 | double score = result.get(row, col)[0];
45 | if (score >= threshold) {
46 | // 使用阈值确定匹配的区域
47 | Point matchLoc = new Point(col, row);
48 | Rect matchRect = new Rect(matchLoc, new Point(matchLoc.x + templeteMat.cols(), matchLoc.y + templeteMat.rows()));
49 | // 检查是否与已检测的区域重叠
50 | boolean isOverlapping = false;
51 | for (Rect existingRect : detectedRectangles) {
52 | if (isRectOverlapping(matchRect, existingRect)) {
53 | isOverlapping = true;
54 | break;
55 | }
56 | }
57 | // 如果没有重叠,将匹配的区域添加到列表中
58 | if (!isOverlapping) {
59 | detectedRectangles.add(matchRect);
60 | // 在原图上标记匹配区域,可选,调试时配合下面查看标记的位置
61 | // Imgproc.rectangle(bgMat, matchRect.tl(), matchRect.br(), new Scalar(0, 0, 0), 3);
62 | }
63 | }
64 | }
65 | }
66 | // // 将 Mat 转换为 Bitmap
67 | // Bitmap resultBitmap = Bitmap.createBitmap(bgMat.cols(), bgMat.rows(), Bitmap.Config.ARGB_8888);
68 | // Utils.matToBitmap(bgMat, resultBitmap);
69 | // 释放 Mat 对象
70 | bgMat.release();
71 | templeteMat.release();
72 | result.release();
73 | // 返回匹配得分高于阈值的区域数量
74 | return detectedRectangles.size();
75 | }
76 |
77 | private static boolean isRectOverlapping(Rect rect1, Rect rect2) {
78 | return (rect1.x < rect2.x + rect2.width &&
79 | rect1.x + rect1.width > rect2.x &&
80 | rect1.y < rect2.y + rect2.height &&
81 | rect1.y + rect1.height > rect2.y);
82 | }
83 |
84 | /**
85 | * 获取图像中存在的点数
86 | * @param context
87 | * @param inputBitmap 输入图像
88 | * @param threshold 阈值,阈值越大,要求的精度越高
89 | * @param handCard 是否是手牌,由于手牌和出牌区的牌大小不一致,所以需要区分
90 | * @param ratio 缩放比例,适配不同屏幕大小
91 | * @return 返回一个点数的数组,1到14,分别对应A,2,3,4,5... J,Q,K,王
92 | */
93 | public static int[] findMatches(Context context, Bitmap inputBitmap, double threshold, boolean handCard, float ratio) {
94 | int[] result = new int[15];
95 | float scale = handCard ? 80f : 60f;
96 | for (int i = 1; i <= 15; i++) {
97 | String imageName = "point"+ i ; // 替换成你需要查找的图片名称
98 | int resourceId = context.getResources().getIdentifier(imageName, "drawable", context.getPackageName());
99 | Bitmap smallBitmap = BitmapFactory.decodeResource(context.getResources(), resourceId);
100 | smallBitmap = ImageUtils.setImgSize(smallBitmap, scale * ratio);
101 | int num = matchImgNum(inputBitmap, smallBitmap, threshold);
102 | if (i == 15){
103 | //由于出牌区的王和手牌区的王不一样,所以需要重新识别一次
104 | result[14] += num;
105 | break;
106 | }
107 | result[i] = num;
108 | }
109 | return result;
110 | }
111 | }
--------------------------------------------------------------------------------
/app/src/main/java/com/yangda/cardrecorder/MainActivity.java:
--------------------------------------------------------------------------------
1 | package com.yangda.cardrecorder;
2 |
3 | import static android.content.ContentValues.TAG;
4 |
5 | import androidx.appcompat.app.AppCompatActivity;
6 |
7 | import android.app.AlertDialog;
8 | import android.content.Context;
9 | import android.content.DialogInterface;
10 | import android.content.Intent;
11 | import android.content.SharedPreferences;
12 | import android.media.projection.MediaProjectionManager;
13 | import android.net.Uri;
14 | import android.os.Build;
15 | import android.os.Bundle;
16 | import android.provider.Settings;
17 | import android.util.Log;
18 | import android.view.View;
19 | import android.widget.Button;
20 | import android.widget.EditText;
21 | import android.widget.Toast;
22 |
23 | import org.opencv.android.OpenCVLoader;
24 |
25 | import java.util.Objects;
26 |
27 | public class MainActivity extends AppCompatActivity {
28 | private AlertDialog dialog;
29 | @Override
30 | protected void onCreate(Bundle savedInstanceState) {
31 | super.onCreate(savedInstanceState);
32 | setContentView(R.layout.activity_main);
33 | OpenCVLoader.initDebug();
34 | if (!checkOverlayDisplayPermission()) requestOverlayDisplayPermission();
35 | Button initButton = findViewById(R.id.init);
36 | initButton.setOnClickListener(new View.OnClickListener() {
37 | @Override
38 | public void onClick(View v) {
39 | initMediaProjectionManager();
40 | }
41 | });
42 |
43 | SharedPreferences sharedPreferences = getSharedPreferences("MySettings", Context.MODE_PRIVATE);
44 | int time = sharedPreferences.getInt("time", 2000);
45 | EditText editText = findViewById(R.id.editTextNumberSigned);
46 | editText.setText(String.valueOf(time));
47 |
48 | Button save = findViewById(R.id.button);
49 | save.setOnClickListener(new View.OnClickListener() {
50 | @Override
51 | public void onClick(View view) {
52 | SharedPreferences sharedPreferences = getSharedPreferences("MySettings", Context.MODE_PRIVATE);
53 | SharedPreferences.Editor editor = sharedPreferences.edit();
54 | EditText editText = findViewById(R.id.editTextNumberSigned);
55 | Integer time = Integer.valueOf(editText.getText().toString());
56 | editor.putInt("time",time);
57 | editor.apply(); // 提交保存
58 | Toast.makeText(MainActivity.this, "保存成功", Toast.LENGTH_SHORT).show();
59 | }
60 | });
61 | }
62 |
63 | private void requestOverlayDisplayPermission() {
64 | AlertDialog.Builder builder = new AlertDialog.Builder(this);
65 | builder.setCancelable(true);
66 | builder.setTitle("需要打开悬浮窗权限");
67 | builder.setMessage("在系统设置中为本应用打开悬浮窗权限,或允许该应用显示在其他应用上层。");
68 | builder.setPositiveButton("打开设置", new DialogInterface.OnClickListener() {
69 | @Override
70 | public void onClick(DialogInterface dialog, int which) {
71 | Intent intent = new Intent(Settings.ACTION_MANAGE_OVERLAY_PERMISSION, Uri.parse("package:" + getPackageName()));
72 | startActivityForResult(intent, RESULT_OK);
73 | }
74 | });
75 | dialog = builder.create();
76 | dialog.show();
77 | }
78 |
79 | /**
80 | * 检查是否已经打开悬浮窗权限
81 | * @return
82 | */
83 | private boolean checkOverlayDisplayPermission() {
84 | if (Build.VERSION.SDK_INT > Build.VERSION_CODES.M) {
85 | if (!Settings.canDrawOverlays(this)) {
86 | return false;
87 | } else {
88 | return true;
89 | }
90 | } else {
91 | return true;
92 | }
93 | }
94 | MediaProjectionManager mediaProjectionManager;
95 | public static final int REQUEST_MEDIA_PROJECTION = 18;
96 |
97 | private void initMediaProjectionManager() {
98 | if (mediaProjectionManager != null) return;
99 | mediaProjectionManager = (MediaProjectionManager)getSystemService(Context.MEDIA_PROJECTION_SERVICE);
100 | startActivityForResult(mediaProjectionManager.createScreenCaptureIntent(), REQUEST_MEDIA_PROJECTION);
101 | }
102 |
103 | @Override
104 | protected void onActivityResult(int requestCode, int resultCode, Intent data) {
105 | super.onActivityResult(requestCode, resultCode, data);
106 | if (resultCode == RESULT_OK && data != null) {
107 | Intent intent = new Intent(MainActivity.this, FloatingWindowService.class);
108 | intent.putExtra("code", resultCode);
109 | intent.putExtra("data", data);
110 | startForegroundService(intent);
111 | finish();
112 | }
113 | }
114 | }
--------------------------------------------------------------------------------
/app/src/main/res/drawable/ic_launcher_background.xml:
--------------------------------------------------------------------------------
1 |
2 |
7 |
10 |
15 |
20 |
25 |
30 |
35 |
40 |
45 |
50 |
55 |
60 |
65 |
70 |
75 |
80 |
85 |
90 |
95 |
100 |
105 |
110 |
115 |
120 |
125 |
130 |
135 |
140 |
145 |
150 |
155 |
160 |
165 |
170 |
171 |
--------------------------------------------------------------------------------
/app/src/main/res/layout/floating_layout.xml:
--------------------------------------------------------------------------------
1 |
2 |
7 |
11 |
12 |
19 |
20 |
27 |
28 |
35 |
36 |
43 |
44 |
51 |
52 |
59 |
60 |
67 |
68 |
75 |
76 |
83 |
84 |
91 |
92 |
99 |
100 |
107 |
108 |
115 |
116 |
123 |
124 |
131 |
132 |
139 |
140 |
147 |
148 |
155 |
156 |
163 |
164 |
165 |
--------------------------------------------------------------------------------
/gradlew:
--------------------------------------------------------------------------------
1 | #!/usr/bin/env sh
2 |
3 | #
4 | # Copyright 2015 the original author or authors.
5 | #
6 | # Licensed under the Apache License, Version 2.0 (the "License");
7 | # you may not use this file except in compliance with the License.
8 | # You may obtain a copy of the License at
9 | #
10 | # https://www.apache.org/licenses/LICENSE-2.0
11 | #
12 | # Unless required by applicable law or agreed to in writing, software
13 | # distributed under the License is distributed on an "AS IS" BASIS,
14 | # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
15 | # See the License for the specific language governing permissions and
16 | # limitations under the License.
17 | #
18 |
19 | ##############################################################################
20 | ##
21 | ## Gradle start up script for UN*X
22 | ##
23 | ##############################################################################
24 |
25 | # Attempt to set APP_HOME
26 | # Resolve links: $0 may be a link
27 | PRG="$0"
28 | # Need this for relative symlinks.
29 | while [ -h "$PRG" ] ; do
30 | ls=`ls -ld "$PRG"`
31 | link=`expr "$ls" : '.*-> \(.*\)$'`
32 | if expr "$link" : '/.*' > /dev/null; then
33 | PRG="$link"
34 | else
35 | PRG=`dirname "$PRG"`"/$link"
36 | fi
37 | done
38 | SAVED="`pwd`"
39 | cd "`dirname \"$PRG\"`/" >/dev/null
40 | APP_HOME="`pwd -P`"
41 | cd "$SAVED" >/dev/null
42 |
43 | APP_NAME="Gradle"
44 | APP_BASE_NAME=`basename "$0"`
45 |
46 | # Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script.
47 | DEFAULT_JVM_OPTS='"-Xmx64m" "-Xms64m"'
48 |
49 | # Use the maximum available, or set MAX_FD != -1 to use that value.
50 | MAX_FD="maximum"
51 |
52 | warn () {
53 | echo "$*"
54 | }
55 |
56 | die () {
57 | echo
58 | echo "$*"
59 | echo
60 | exit 1
61 | }
62 |
63 | # OS specific support (must be 'true' or 'false').
64 | cygwin=false
65 | msys=false
66 | darwin=false
67 | nonstop=false
68 | case "`uname`" in
69 | CYGWIN* )
70 | cygwin=true
71 | ;;
72 | Darwin* )
73 | darwin=true
74 | ;;
75 | MINGW* )
76 | msys=true
77 | ;;
78 | NONSTOP* )
79 | nonstop=true
80 | ;;
81 | esac
82 |
83 | CLASSPATH=$APP_HOME/gradle/wrapper/gradle-wrapper.jar
84 |
85 |
86 | # Determine the Java command to use to start the JVM.
87 | if [ -n "$JAVA_HOME" ] ; then
88 | if [ -x "$JAVA_HOME/jre/sh/java" ] ; then
89 | # IBM's JDK on AIX uses strange locations for the executables
90 | JAVACMD="$JAVA_HOME/jre/sh/java"
91 | else
92 | JAVACMD="$JAVA_HOME/bin/java"
93 | fi
94 | if [ ! -x "$JAVACMD" ] ; then
95 | die "ERROR: JAVA_HOME is set to an invalid directory: $JAVA_HOME
96 |
97 | Please set the JAVA_HOME variable in your environment to match the
98 | location of your Java installation."
99 | fi
100 | else
101 | JAVACMD="java"
102 | which java >/dev/null 2>&1 || die "ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH.
103 |
104 | Please set the JAVA_HOME variable in your environment to match the
105 | location of your Java installation."
106 | fi
107 |
108 | # Increase the maximum file descriptors if we can.
109 | if [ "$cygwin" = "false" -a "$darwin" = "false" -a "$nonstop" = "false" ] ; then
110 | MAX_FD_LIMIT=`ulimit -H -n`
111 | if [ $? -eq 0 ] ; then
112 | if [ "$MAX_FD" = "maximum" -o "$MAX_FD" = "max" ] ; then
113 | MAX_FD="$MAX_FD_LIMIT"
114 | fi
115 | ulimit -n $MAX_FD
116 | if [ $? -ne 0 ] ; then
117 | warn "Could not set maximum file descriptor limit: $MAX_FD"
118 | fi
119 | else
120 | warn "Could not query maximum file descriptor limit: $MAX_FD_LIMIT"
121 | fi
122 | fi
123 |
124 | # For Darwin, add options to specify how the application appears in the dock
125 | if $darwin; then
126 | GRADLE_OPTS="$GRADLE_OPTS \"-Xdock:name=$APP_NAME\" \"-Xdock:icon=$APP_HOME/media/gradle.icns\""
127 | fi
128 |
129 | # For Cygwin or MSYS, switch paths to Windows format before running java
130 | if [ "$cygwin" = "true" -o "$msys" = "true" ] ; then
131 | APP_HOME=`cygpath --path --mixed "$APP_HOME"`
132 | CLASSPATH=`cygpath --path --mixed "$CLASSPATH"`
133 |
134 | JAVACMD=`cygpath --unix "$JAVACMD"`
135 |
136 | # We build the pattern for arguments to be converted via cygpath
137 | ROOTDIRSRAW=`find -L / -maxdepth 1 -mindepth 1 -type d 2>/dev/null`
138 | SEP=""
139 | for dir in $ROOTDIRSRAW ; do
140 | ROOTDIRS="$ROOTDIRS$SEP$dir"
141 | SEP="|"
142 | done
143 | OURCYGPATTERN="(^($ROOTDIRS))"
144 | # Add a user-defined pattern to the cygpath arguments
145 | if [ "$GRADLE_CYGPATTERN" != "" ] ; then
146 | OURCYGPATTERN="$OURCYGPATTERN|($GRADLE_CYGPATTERN)"
147 | fi
148 | # Now convert the arguments - kludge to limit ourselves to /bin/sh
149 | i=0
150 | for arg in "$@" ; do
151 | CHECK=`echo "$arg"|egrep -c "$OURCYGPATTERN" -`
152 | CHECK2=`echo "$arg"|egrep -c "^-"` ### Determine if an option
153 |
154 | if [ $CHECK -ne 0 ] && [ $CHECK2 -eq 0 ] ; then ### Added a condition
155 | eval `echo args$i`=`cygpath --path --ignore --mixed "$arg"`
156 | else
157 | eval `echo args$i`="\"$arg\""
158 | fi
159 | i=`expr $i + 1`
160 | done
161 | case $i in
162 | 0) set -- ;;
163 | 1) set -- "$args0" ;;
164 | 2) set -- "$args0" "$args1" ;;
165 | 3) set -- "$args0" "$args1" "$args2" ;;
166 | 4) set -- "$args0" "$args1" "$args2" "$args3" ;;
167 | 5) set -- "$args0" "$args1" "$args2" "$args3" "$args4" ;;
168 | 6) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" ;;
169 | 7) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" ;;
170 | 8) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" "$args7" ;;
171 | 9) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" "$args7" "$args8" ;;
172 | esac
173 | fi
174 |
175 | # Escape application args
176 | save () {
177 | for i do printf %s\\n "$i" | sed "s/'/'\\\\''/g;1s/^/'/;\$s/\$/' \\\\/" ; done
178 | echo " "
179 | }
180 | APP_ARGS=`save "$@"`
181 |
182 | # Collect all arguments for the java command, following the shell quoting and substitution rules
183 | eval set -- $DEFAULT_JVM_OPTS $JAVA_OPTS $GRADLE_OPTS "\"-Dorg.gradle.appname=$APP_BASE_NAME\"" -classpath "\"$CLASSPATH\"" org.gradle.wrapper.GradleWrapperMain "$APP_ARGS"
184 |
185 | exec "$JAVACMD" "$@"
186 |
--------------------------------------------------------------------------------
/app/src/main/java/com/yangda/cardrecorder/FloatingWindowService.java:
--------------------------------------------------------------------------------
1 | package com.yangda.cardrecorder;
2 |
3 | import static android.content.ContentValues.TAG;
4 |
5 | import android.app.Notification;
6 | import android.app.NotificationChannel;
7 | import android.app.NotificationManager;
8 | import android.app.PendingIntent;
9 | import android.app.Service;
10 | import android.content.Context;
11 | import android.content.Intent;
12 | import android.content.SharedPreferences;
13 | import android.content.res.Configuration;
14 | import android.graphics.Bitmap;
15 | import android.graphics.BitmapFactory;
16 | import android.graphics.PixelFormat;
17 | import android.hardware.display.DisplayManager;
18 | import android.hardware.display.VirtualDisplay;
19 | import android.media.Image;
20 | import android.media.ImageReader;
21 | import android.media.projection.MediaProjection;
22 | import android.media.projection.MediaProjectionManager;
23 | import android.os.Build;
24 | import android.os.Handler;
25 | import android.os.IBinder;
26 | import android.util.DisplayMetrics;
27 | import android.util.Log;
28 | import android.view.Gravity;
29 | import android.view.LayoutInflater;
30 | import android.view.MotionEvent;
31 | import android.view.View;
32 | import android.view.ViewGroup;
33 | import android.view.WindowManager;
34 | import android.widget.Button;
35 | import android.widget.TextView;
36 |
37 | import androidx.annotation.Nullable;
38 |
39 | import java.util.Arrays;
40 | import java.util.Objects;
41 |
42 | public class FloatingWindowService extends Service {
43 | private WindowManager windowManager;
44 | private ViewGroup floatView;
45 | private int LAYOUT_TYPE;
46 | private WindowManager.LayoutParams floatWindowLayoutParam;
47 | private Context context;
48 | private int[] cardCounts, player1Card, player2Card;
49 | private int[] handCard = {245 , 900, 2800, 1050};
50 | private int[] player1 = {1890, 321, 2664, 554};
51 | private int[] player2 = {460, 321, 1300, 554};
52 | private float ratio;//适配不同屏幕大小,需要缩放或扩大的比例
53 |
54 | private int time;
55 | @Override
56 | public void onCreate() {
57 | super.onCreate();
58 | this.context = this.getApplicationContext();
59 | windowManager = (WindowManager) getSystemService(WINDOW_SERVICE);
60 | DisplayMetrics metrics = new DisplayMetrics();
61 | windowManager.getDefaultDisplay().getMetrics(metrics);
62 | mScreenDensity = metrics.densityDpi;
63 | mScreenWidth = metrics.widthPixels;
64 | mScreenHeight = ImageUtils.getHasVirtualKey(windowManager);
65 | ratio = mScreenHeight / 3200f;
66 | for (int i = 0; i < handCard.length; i++) {
67 | handCard[i] = (int)(handCard[i] * ratio);
68 | player1[i] = (int)(player1[i] * ratio);
69 | player2[i] = (int)(player2[i] * ratio);
70 | }
71 | LayoutInflater inflater = (LayoutInflater) getBaseContext().getSystemService(LAYOUT_INFLATER_SERVICE);
72 | floatView = (ViewGroup) inflater.inflate(R.layout.floating_layout, null);
73 | if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
74 | LAYOUT_TYPE = WindowManager.LayoutParams.TYPE_APPLICATION_OVERLAY;
75 | } else {
76 | LAYOUT_TYPE = WindowManager.LayoutParams.TYPE_TOAST;
77 | }
78 | floatWindowLayoutParam = new WindowManager.LayoutParams(mScreenWidth, mScreenHeight / 10, LAYOUT_TYPE, WindowManager.LayoutParams.FLAG_NOT_FOCUSABLE, PixelFormat.TRANSLUCENT);
79 | floatWindowLayoutParam.gravity = Gravity.CENTER;
80 | floatWindowLayoutParam.x = 0;
81 | floatWindowLayoutParam.y = 0;
82 | SharedPreferences sharedPreferences = getSharedPreferences("MySettings", Context.MODE_PRIVATE);
83 | time = sharedPreferences.getInt("time", 2000);
84 | windowManager.addView(floatView, floatWindowLayoutParam);
85 | //触摸移动悬浮框
86 | floatView.setOnTouchListener(new View.OnTouchListener() {
87 | final WindowManager.LayoutParams floatWindowLayoutUpdateParam = floatWindowLayoutParam;
88 | double x,y,px,py;
89 | @Override
90 | public boolean onTouch(View v, MotionEvent event) {
91 | switch (event.getAction()) {
92 | case MotionEvent.ACTION_DOWN:
93 | x = floatWindowLayoutUpdateParam.x;
94 | y = floatWindowLayoutUpdateParam.y;
95 | px = event.getRawX();
96 | py = event.getRawY();
97 | break;
98 | case MotionEvent.ACTION_MOVE:
99 | floatWindowLayoutUpdateParam.x = (int) ((x + event.getRawX()) - px);
100 | floatWindowLayoutUpdateParam.y = (int) ((y + event.getRawY()) - py);
101 | windowManager.updateViewLayout(floatView, floatWindowLayoutUpdateParam);
102 | break;
103 | }
104 | return false;
105 | }
106 | });
107 |
108 | Button startButton = floatView.findViewById(R.id.startButton);
109 | startButton.setOnClickListener(new View.OnClickListener() {
110 | @Override
111 | public void onClick(View v) {
112 | createImageReader();
113 | virtualDisplay();
114 | initScreenShot();
115 | }
116 | });
117 | Button stopButton = floatView.findViewById(R.id.stopButton);
118 | stopButton.setOnClickListener(new View.OnClickListener() {
119 | @Override
120 | public void onClick(View v) {
121 | stopScreenShot();
122 | }
123 | });
124 | }
125 | MediaProjectionManager mediaProjectionManager;
126 | MediaProjection mMediaProjection;
127 |
128 | /**
129 | * 由于创建MediaProjection必须要code和Data数据而这数据只能在activity里获取,所以使用Intent传递来自Activity的数据
130 | * @param intent
131 | * @param flags
132 | * @param startId
133 | * @return
134 | */
135 | @Override
136 | public int onStartCommand(final Intent intent, int flags, int startId) {
137 | createNotificationChannel();
138 | int mResultCode = intent.getIntExtra("code", -1);
139 | Intent mResultData = intent.getParcelableExtra("data");
140 | mediaProjectionManager = (MediaProjectionManager)getSystemService(Context.MEDIA_PROJECTION_SERVICE);
141 | mMediaProjection = mediaProjectionManager.getMediaProjection(mResultCode, Objects.requireNonNull(mResultData));
142 | Log.e(TAG, "mMediaProjection created: " + mMediaProjection);
143 | return super.onStartCommand(intent, flags, startId);
144 | }
145 |
146 | /**
147 | * 当切换横屏竖屏时需要转换的数据
148 | * @param newConfig
149 | */
150 | @Override
151 | public void onConfigurationChanged(Configuration newConfig) {
152 | super.onConfigurationChanged(newConfig);
153 | int big = Math.max(mScreenHeight, mScreenWidth), small = Math.min(mScreenHeight, mScreenWidth);
154 | // 检查是否是横屏模式
155 | if (newConfig.orientation == Configuration.ORIENTATION_LANDSCAPE) {
156 | mScreenWidth = big;
157 | mScreenHeight = small;
158 | } else if (newConfig.orientation == Configuration.ORIENTATION_PORTRAIT) {
159 | mScreenWidth = small;
160 | mScreenHeight = big;
161 | }
162 | // 更新窗口布局
163 | WindowManager windowManager = (WindowManager) getSystemService(WINDOW_SERVICE);
164 | if (windowManager != null) {
165 | floatWindowLayoutParam.width = mScreenWidth;
166 | floatWindowLayoutParam.height = 200;
167 | windowManager.updateViewLayout(floatView, floatWindowLayoutParam);
168 | }
169 | }
170 |
171 | private void createNotificationChannel() {
172 | Notification.Builder builder = new Notification.Builder(this.getApplicationContext()); //获取一个Notification构造器
173 | Intent nfIntent = new Intent(this, MainActivity.class); //点击后跳转的界面,可以设置跳转数据
174 | builder.setContentIntent(PendingIntent.getActivity(this, 0, nfIntent, PendingIntent.FLAG_IMMUTABLE)) // 设置PendingIntent
175 | .setLargeIcon(BitmapFactory.decodeResource(this.getResources(), R.mipmap.ic_launcher)) // 设置下拉列表中的图标(大图标)
176 | .setSmallIcon(R.mipmap.ic_launcher) // 设置状态栏内的小图标
177 | .setContentText("is running......") // 设置上下文内容
178 | .setWhen(System.currentTimeMillis()); // 设置该通知发生的时间
179 | /*以下是对Android 8.0的适配*/
180 | //普通notification适配
181 | if(Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
182 | builder.setChannelId("notification_id");
183 | }
184 | //前台服务notification适配
185 | if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
186 | NotificationManager notificationManager = (NotificationManager)getSystemService(NOTIFICATION_SERVICE);
187 | NotificationChannel channel = new NotificationChannel("notification_id", "notification_name", NotificationManager.IMPORTANCE_LOW);
188 | notificationManager.createNotificationChannel(channel);
189 | }
190 | Notification notification = builder.build(); // 获取构建好的Notification
191 | notification.defaults = Notification.DEFAULT_SOUND; //设置为默认的声音
192 | startForeground(110, notification);
193 | }
194 | private int mScreenWidth;
195 | private int mScreenHeight;
196 | private int mScreenDensity;
197 | private ImageReader mImageReader;
198 | private void createImageReader() {
199 | if (mImageReader != null)return;
200 | // 设置截屏的宽高
201 | mImageReader = ImageReader.newInstance(mScreenWidth, mScreenHeight, PixelFormat.RGBA_8888, 1);
202 | }
203 |
204 | private VirtualDisplay mVirtualDisplay;
205 | /**
206 | * 最终得到当前屏幕的内容,注意这里mImageReader.getSurface()被传入,屏幕的数据也将会在ImageReader中的Surface中
207 | */
208 | private void virtualDisplay() {
209 | if (mVirtualDisplay != null)return;
210 | mVirtualDisplay = mMediaProjection.createVirtualDisplay("screen-mirror",
211 | mScreenWidth, mScreenHeight, mScreenDensity, DisplayManager.VIRTUAL_DISPLAY_FLAG_AUTO_MIRROR,
212 | mImageReader.getSurface(), null, null);
213 | }
214 |
215 | private boolean isScreenshotEnabled = true;
216 |
217 | public boolean isChange(int[] last,int[] current){
218 | for (int i = 0; i < last.length; i++) {
219 | if (current[i] != 0){
220 | break;
221 | }
222 | }
223 | for (int i = 0; i < last.length; i++) {
224 | if (current[i] != last[i]){
225 | return true;
226 | }
227 | }
228 | return false;
229 | }
230 | private Handler handler = new Handler();
231 | public void initScreenShot(){
232 | handler.removeCallbacksAndMessages(null);
233 | isScreenshotEnabled = true;
234 | TextView textView1 = floatView.findViewById(getResources().getIdentifier("stopButton", "id", getPackageName()));
235 | textView1.setText("停止");
236 | this.cardCounts = new int[15];
237 | this.player1Card = new int[15];
238 | this.player2Card = new int[15];
239 | Arrays.fill(cardCounts,4);
240 | cardCounts[14] = 2;
241 | updatePlayerCard();
242 | handler.postDelayed(new Runnable() {
243 | public void run() {
244 | Image image = mImageReader.acquireLatestImage();
245 | Bitmap bitmap = ImageUtils.imageToBitmap(image);
246 | bitmap = ImageUtils.cropBitmap(bitmap, handCard);
247 | int[] matches = CardDetectionUtil.findMatches(context, bitmap, 0.85, true, ratio);
248 | updateContent(matches);
249 | startScreenShot();
250 | }
251 | }, 1000);
252 | }
253 |
254 | private void startScreenShot() {
255 | if (isScreenshotEnabled) {
256 | handler.postDelayed(new Runnable() {
257 | public void run() {
258 | Image image = mImageReader.acquireLatestImage();
259 | Bitmap bitmap = ImageUtils.imageToBitmap(image);
260 | Bitmap bitmap1 = ImageUtils.cropBitmap(bitmap, player1);
261 | Bitmap bitmap2 = ImageUtils.cropBitmap(bitmap, player2);
262 | int[] matches1 = CardDetectionUtil.findMatches(context, bitmap1, 0.85, false, ratio);
263 | int[] matches2 = CardDetectionUtil.findMatches(context, bitmap2, 0.85, false, ratio);
264 | if (isChange(player1Card, matches1))updateContent(matches1);
265 | if (isChange(player2Card, matches2))updateContent(matches2);
266 | player1Card = matches1;
267 | player2Card = matches2;
268 | updatePlayerCard();
269 | startScreenShot();
270 | }
271 | }, time);
272 | }
273 | }
274 | String[] name = {" ","A","2","3","4","5","6","7","8","9","10","J","Q","K","王"};
275 |
276 | /**
277 | * 更新界面上记牌器的显示,传入的参数为此次更新需要减点的点数
278 | * @param value
279 | */
280 | public void updateContent(int[] value){
281 | for (int i = 1; i < 15; i++) {
282 | cardCounts[i] -= value[i];
283 | TextView textView = floatView.findViewById(getResources().getIdentifier("textView" + i, "id", getPackageName()));
284 | textView.setText(name[i] + "\n" +cardCounts[i]);
285 | }
286 | }
287 |
288 | /**
289 | * 更新玩家当前的出牌数,以及当前时间
290 | */
291 | public void updatePlayerCard(){
292 | StringBuilder s1 = new StringBuilder();
293 | StringBuilder s2 = new StringBuilder();
294 | for (int i = 1; i < 15; i++) {
295 | if (player1Card[i] != 0){
296 | for (int j = 0; j < player1Card[i]; j++) {
297 | s1.append(name[i]);
298 | }
299 | }
300 | if (player2Card[i] != 0){
301 | for (int j = 0; j < player2Card[i]; j++) {
302 | s2.append(name[i]);
303 | }
304 | }
305 | }
306 | if (s1.length()==0)s1.append("空");
307 | if (s2.length()==0)s2.append("空");
308 | TextView textView1 = floatView.findViewById(getResources().getIdentifier("player1", "id", getPackageName()));
309 | textView1.setText(s1.toString());
310 | TextView textView2 = floatView.findViewById(getResources().getIdentifier("player2", "id", getPackageName()));
311 | textView2.setText(s2.toString());
312 | TextView textView = floatView.findViewById(getResources().getIdentifier("textView", "id", getPackageName()));
313 | textView.setText("时间" + (System.currentTimeMillis()/1000) % 100);
314 | }
315 | // 在需要停止截图的地方调用此方法
316 | private void stopScreenShot() {
317 | if(isScreenshotEnabled){
318 | isScreenshotEnabled = false;
319 | handler.removeCallbacksAndMessages(null);
320 | TextView textView1 = floatView.findViewById(getResources().getIdentifier("stopButton", "id", getPackageName()));
321 | textView1.setText("继续");
322 | }else {
323 | isScreenshotEnabled = true;
324 | TextView textView1 = floatView.findViewById(getResources().getIdentifier("stopButton", "id", getPackageName()));
325 | textView1.setText("停止");
326 | startScreenShot();
327 | }
328 | }
329 | @Nullable
330 | @Override
331 | public IBinder onBind(Intent intent) {
332 | return null;
333 | }
334 | }
335 |
--------------------------------------------------------------------------------