├── app
├── .gitignore
├── src
│ ├── main
│ │ ├── res
│ │ │ ├── values
│ │ │ │ ├── strings.xml
│ │ │ │ ├── colors.xml
│ │ │ │ └── styles.xml
│ │ │ ├── mipmap-hdpi
│ │ │ │ ├── ic_launcher.png
│ │ │ │ └── ic_launcher_round.png
│ │ │ ├── mipmap-mdpi
│ │ │ │ ├── ic_launcher.png
│ │ │ │ └── ic_launcher_round.png
│ │ │ ├── mipmap-xhdpi
│ │ │ │ ├── ic_launcher.png
│ │ │ │ └── ic_launcher_round.png
│ │ │ ├── mipmap-xxhdpi
│ │ │ │ ├── ic_launcher.png
│ │ │ │ └── ic_launcher_round.png
│ │ │ ├── mipmap-xxxhdpi
│ │ │ │ ├── ic_launcher.png
│ │ │ │ └── ic_launcher_round.png
│ │ │ ├── mipmap-anydpi-v26
│ │ │ │ ├── ic_launcher.xml
│ │ │ │ └── ic_launcher_round.xml
│ │ │ ├── xml
│ │ │ │ └── nfc_tech_filter.xml
│ │ │ ├── layout
│ │ │ │ ├── activity_main.xml
│ │ │ │ └── activity_nfc.xml
│ │ │ ├── drawable-v24
│ │ │ │ └── ic_launcher_foreground.xml
│ │ │ └── drawable
│ │ │ │ └── ic_launcher_background.xml
│ │ ├── java
│ │ │ └── com
│ │ │ │ └── example
│ │ │ │ └── chenqiuyang
│ │ │ │ └── nfcread
│ │ │ │ ├── MainActivity.java
│ │ │ │ ├── read
│ │ │ │ ├── ParsedNdefRecord.java
│ │ │ │ ├── TextRecord.java
│ │ │ │ ├── UriRecord.java
│ │ │ │ └── SmartPoster.java
│ │ │ │ ├── NdefMessageParser.java
│ │ │ │ ├── NfcActivity.java
│ │ │ │ └── NfcUtil.java
│ │ └── AndroidManifest.xml
│ ├── test
│ │ └── java
│ │ │ └── com
│ │ │ └── example
│ │ │ └── chenqiuyang
│ │ │ └── nfcread
│ │ │ └── ExampleUnitTest.java
│ └── androidTest
│ │ └── java
│ │ └── com
│ │ └── example
│ │ └── chenqiuyang
│ │ └── nfcread
│ │ └── ExampleInstrumentedTest.java
├── proguard-rules.pro
└── build.gradle
├── settings.gradle
├── gradle
└── wrapper
│ ├── gradle-wrapper.jar
│ └── gradle-wrapper.properties
├── .idea
├── caches
│ └── build_file_checksums.ser
├── vcs.xml
├── kotlinc.xml
├── runConfigurations.xml
├── gradle.xml
├── misc.xml
└── codeStyles
│ └── Project.xml
├── .gitignore
├── gradle.properties
├── gradlew.bat
└── gradlew
/app/.gitignore:
--------------------------------------------------------------------------------
1 | /build
2 |
--------------------------------------------------------------------------------
/settings.gradle:
--------------------------------------------------------------------------------
1 | include ':app'
2 |
--------------------------------------------------------------------------------
/app/src/main/res/values/strings.xml:
--------------------------------------------------------------------------------
1 |
2 | NFCRead
3 |
4 |
--------------------------------------------------------------------------------
/gradle/wrapper/gradle-wrapper.jar:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/younger96/NFCRead/HEAD/gradle/wrapper/gradle-wrapper.jar
--------------------------------------------------------------------------------
/.idea/caches/build_file_checksums.ser:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/younger96/NFCRead/HEAD/.idea/caches/build_file_checksums.ser
--------------------------------------------------------------------------------
/app/src/main/res/mipmap-hdpi/ic_launcher.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/younger96/NFCRead/HEAD/app/src/main/res/mipmap-hdpi/ic_launcher.png
--------------------------------------------------------------------------------
/app/src/main/res/mipmap-mdpi/ic_launcher.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/younger96/NFCRead/HEAD/app/src/main/res/mipmap-mdpi/ic_launcher.png
--------------------------------------------------------------------------------
/app/src/main/res/mipmap-xhdpi/ic_launcher.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/younger96/NFCRead/HEAD/app/src/main/res/mipmap-xhdpi/ic_launcher.png
--------------------------------------------------------------------------------
/app/src/main/res/mipmap-xxhdpi/ic_launcher.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/younger96/NFCRead/HEAD/app/src/main/res/mipmap-xxhdpi/ic_launcher.png
--------------------------------------------------------------------------------
/app/src/main/res/mipmap-xxxhdpi/ic_launcher.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/younger96/NFCRead/HEAD/app/src/main/res/mipmap-xxxhdpi/ic_launcher.png
--------------------------------------------------------------------------------
/app/src/main/res/mipmap-hdpi/ic_launcher_round.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/younger96/NFCRead/HEAD/app/src/main/res/mipmap-hdpi/ic_launcher_round.png
--------------------------------------------------------------------------------
/app/src/main/res/mipmap-mdpi/ic_launcher_round.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/younger96/NFCRead/HEAD/app/src/main/res/mipmap-mdpi/ic_launcher_round.png
--------------------------------------------------------------------------------
/app/src/main/res/mipmap-xhdpi/ic_launcher_round.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/younger96/NFCRead/HEAD/app/src/main/res/mipmap-xhdpi/ic_launcher_round.png
--------------------------------------------------------------------------------
/app/src/main/res/mipmap-xxhdpi/ic_launcher_round.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/younger96/NFCRead/HEAD/app/src/main/res/mipmap-xxhdpi/ic_launcher_round.png
--------------------------------------------------------------------------------
/app/src/main/res/mipmap-xxxhdpi/ic_launcher_round.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/younger96/NFCRead/HEAD/app/src/main/res/mipmap-xxxhdpi/ic_launcher_round.png
--------------------------------------------------------------------------------
/.gitignore:
--------------------------------------------------------------------------------
1 | *.iml
2 | .gradle
3 | /local.properties
4 | /.idea/libraries
5 | /.idea/modules.xml
6 | /.idea/workspace.xml
7 | .DS_Store
8 | /build
9 | /captures
10 | .externalNativeBuild
11 |
--------------------------------------------------------------------------------
/.idea/vcs.xml:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 |
6 |
--------------------------------------------------------------------------------
/.idea/kotlinc.xml:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 |
6 |
7 |
--------------------------------------------------------------------------------
/app/src/main/res/values/colors.xml:
--------------------------------------------------------------------------------
1 |
2 |
3 | #3F51B5
4 | #303F9F
5 | #FF4081
6 |
7 |
--------------------------------------------------------------------------------
/gradle/wrapper/gradle-wrapper.properties:
--------------------------------------------------------------------------------
1 | #Fri Jul 06 17:30:06 CST 2018
2 | distributionBase=GRADLE_USER_HOME
3 | distributionPath=wrapper/dists
4 | zipStoreBase=GRADLE_USER_HOME
5 | zipStorePath=wrapper/dists
6 | distributionUrl=https\://services.gradle.org/distributions/gradle-4.4-all.zip
7 |
--------------------------------------------------------------------------------
/app/src/main/res/mipmap-anydpi-v26/ic_launcher.xml:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 |
--------------------------------------------------------------------------------
/app/src/main/res/xml/nfc_tech_filter.xml:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 | android.nfc.tech.IsoDep
5 |
6 |
7 | android.nfc.tech.NfcV
8 |
9 |
--------------------------------------------------------------------------------
/app/src/main/res/mipmap-anydpi-v26/ic_launcher_round.xml:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 |
--------------------------------------------------------------------------------
/app/src/main/res/values/styles.xml:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
10 |
11 |
12 |
--------------------------------------------------------------------------------
/app/src/main/java/com/example/chenqiuyang/nfcread/MainActivity.java:
--------------------------------------------------------------------------------
1 | package com.example.chenqiuyang.nfcread;
2 |
3 |
4 | import android.os.Bundle;
5 |
6 | import android.support.v7.app.AppCompatActivity;
7 |
8 |
9 |
10 | public class MainActivity extends AppCompatActivity {
11 |
12 |
13 |
14 | @Override
15 | protected void onCreate(Bundle savedInstanceState) {
16 | super.onCreate(savedInstanceState);
17 | setContentView(R.layout.activity_main);
18 |
19 |
20 | }
21 |
22 | }
23 |
--------------------------------------------------------------------------------
/app/src/test/java/com/example/chenqiuyang/nfcread/ExampleUnitTest.java:
--------------------------------------------------------------------------------
1 | package com.example.chenqiuyang.nfcread;
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 | }
--------------------------------------------------------------------------------
/.idea/runConfigurations.xml:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
11 |
12 |
--------------------------------------------------------------------------------
/.idea/gradle.xml:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 |
6 |
7 |
8 |
9 |
10 |
11 |
12 |
13 |
14 |
15 |
16 |
17 |
18 |
--------------------------------------------------------------------------------
/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=-Xmx1536m
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 |
--------------------------------------------------------------------------------
/app/src/main/res/layout/activity_main.xml:
--------------------------------------------------------------------------------
1 |
2 |
8 |
9 |
17 |
18 |
--------------------------------------------------------------------------------
/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
22 |
--------------------------------------------------------------------------------
/app/src/androidTest/java/com/example/chenqiuyang/nfcread/ExampleInstrumentedTest.java:
--------------------------------------------------------------------------------
1 | package com.example.chenqiuyang.nfcread;
2 |
3 | import android.content.Context;
4 | import android.support.test.InstrumentationRegistry;
5 | import android.support.test.runner.AndroidJUnit4;
6 |
7 | import org.junit.Test;
8 | import org.junit.runner.RunWith;
9 |
10 | import static org.junit.Assert.*;
11 |
12 | /**
13 | * Instrumented test, which will execute on an Android device.
14 | *
15 | * @see Testing documentation
16 | */
17 | @RunWith(AndroidJUnit4.class)
18 | public class ExampleInstrumentedTest {
19 | @Test
20 | public void useAppContext() {
21 | // Context of the app under test.
22 | Context appContext = InstrumentationRegistry.getTargetContext();
23 |
24 | assertEquals("com.example.chenqiuyang.nfcread", appContext.getPackageName());
25 | }
26 | }
27 |
--------------------------------------------------------------------------------
/app/src/main/java/com/example/chenqiuyang/nfcread/read/ParsedNdefRecord.java:
--------------------------------------------------------------------------------
1 | /*
2 | * Copyright (C) 2010 The Android Open Source Project
3 | *
4 | * Licensed under the Apache License, Version 2.0 (the "License");
5 | * you may not use this file except in compliance with the License.
6 | * You may obtain a copy of the License at
7 | *
8 | * http://www.apache.org/licenses/LICENSE-2.0
9 | *
10 | * Unless required by applicable law or agreed to in writing, software
11 | * distributed under the License is distributed on an "AS IS" BASIS,
12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 | * See the License for the specific language governing permissions and
14 | * limitations under the License.
15 | */
16 |
17 | package com.example.chenqiuyang.nfcread.read;
18 |
19 | public interface ParsedNdefRecord {
20 |
21 | /**
22 | * Returns a view to display this record.
23 | */
24 | public String getViewText();
25 |
26 | }
27 |
--------------------------------------------------------------------------------
/app/build.gradle:
--------------------------------------------------------------------------------
1 | apply plugin: 'com.android.application'
2 |
3 | android {
4 | compileSdkVersion 27
5 | defaultConfig {
6 | applicationId "com.example.chenqiuyang.nfcread"
7 | minSdkVersion 21
8 | targetSdkVersion 27
9 | versionCode 1
10 | versionName "1.0"
11 | testInstrumentationRunner "android.support.test.runner.AndroidJUnitRunner"
12 | }
13 | buildTypes {
14 | release {
15 | minifyEnabled false
16 | proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
17 | }
18 | }
19 | }
20 |
21 | dependencies {
22 | implementation fileTree(dir: 'libs', include: ['*.jar'])
23 | //noinspection GradleCompatible
24 | implementation 'com.android.support:appcompat-v7:27.1.1'
25 | implementation 'com.android.support.constraint:constraint-layout:1.0.2'
26 | testImplementation 'junit:junit:4.12'
27 | androidTestImplementation 'com.android.support.test:runner:1.0.1'
28 | androidTestImplementation 'com.android.support.test.espresso:espresso-core:3.0.1'
29 |
30 | api 'com.google.guava:guava:25.1-android'
31 | }
32 |
--------------------------------------------------------------------------------
/app/src/main/res/layout/activity_nfc.xml:
--------------------------------------------------------------------------------
1 |
2 |
8 |
9 |
10 |
20 |
21 |
22 |
33 |
34 |
--------------------------------------------------------------------------------
/app/src/main/AndroidManifest.xml:
--------------------------------------------------------------------------------
1 |
2 |
4 |
5 |
6 |
7 |
8 |
9 |
10 |
11 |
12 |
19 |
20 |
21 |
22 |
23 |
24 |
25 |
26 |
28 |
29 |
30 |
31 |
32 |
33 |
34 |
35 |
36 |
39 |
40 |
41 |
42 |
43 |
44 |
45 |
46 |
47 |
--------------------------------------------------------------------------------
/.idea/misc.xml:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 |
6 |
7 |
8 |
9 |
10 |
11 |
12 |
13 |
14 |
15 |
16 |
17 |
18 |
19 |
20 |
21 |
22 |
23 |
24 |
25 |
26 |
27 |
28 |
29 |
30 |
31 |
32 |
33 |
34 |
--------------------------------------------------------------------------------
/.idea/codeStyles/Project.xml:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 |
6 |
7 |
8 |
9 |
10 |
11 |
12 |
13 |
14 |
15 |
16 |
17 |
18 |
19 |
20 |
21 |
22 |
23 |
24 |
25 |
26 |
27 |
28 |
29 |
--------------------------------------------------------------------------------
/app/src/main/res/drawable-v24/ic_launcher_foreground.xml:
--------------------------------------------------------------------------------
1 |
7 |
12 |
13 |
19 |
22 |
25 |
26 |
27 |
28 |
34 |
35 |
--------------------------------------------------------------------------------
/gradlew.bat:
--------------------------------------------------------------------------------
1 | @if "%DEBUG%" == "" @echo off
2 | @rem ##########################################################################
3 | @rem
4 | @rem Gradle startup script for Windows
5 | @rem
6 | @rem ##########################################################################
7 |
8 | @rem Set local scope for the variables with windows NT shell
9 | if "%OS%"=="Windows_NT" setlocal
10 |
11 | set DIRNAME=%~dp0
12 | if "%DIRNAME%" == "" set DIRNAME=.
13 | set APP_BASE_NAME=%~n0
14 | set APP_HOME=%DIRNAME%
15 |
16 | @rem Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script.
17 | set DEFAULT_JVM_OPTS=
18 |
19 | @rem Find java.exe
20 | if defined JAVA_HOME goto findJavaFromJavaHome
21 |
22 | set JAVA_EXE=java.exe
23 | %JAVA_EXE% -version >NUL 2>&1
24 | if "%ERRORLEVEL%" == "0" goto init
25 |
26 | echo.
27 | echo ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH.
28 | echo.
29 | echo Please set the JAVA_HOME variable in your environment to match the
30 | echo location of your Java installation.
31 |
32 | goto fail
33 |
34 | :findJavaFromJavaHome
35 | set JAVA_HOME=%JAVA_HOME:"=%
36 | set JAVA_EXE=%JAVA_HOME%/bin/java.exe
37 |
38 | if exist "%JAVA_EXE%" goto init
39 |
40 | echo.
41 | echo ERROR: JAVA_HOME is set to an invalid directory: %JAVA_HOME%
42 | echo.
43 | echo Please set the JAVA_HOME variable in your environment to match the
44 | echo location of your Java installation.
45 |
46 | goto fail
47 |
48 | :init
49 | @rem Get command-line arguments, handling Windows variants
50 |
51 | if not "%OS%" == "Windows_NT" goto win9xME_args
52 |
53 | :win9xME_args
54 | @rem Slurp the command line arguments.
55 | set CMD_LINE_ARGS=
56 | set _SKIP=2
57 |
58 | :win9xME_args_slurp
59 | if "x%~1" == "x" goto execute
60 |
61 | set CMD_LINE_ARGS=%*
62 |
63 | :execute
64 | @rem Setup the command line
65 |
66 | set CLASSPATH=%APP_HOME%\gradle\wrapper\gradle-wrapper.jar
67 |
68 | @rem Execute Gradle
69 | "%JAVA_EXE%" %DEFAULT_JVM_OPTS% %JAVA_OPTS% %GRADLE_OPTS% "-Dorg.gradle.appname=%APP_BASE_NAME%" -classpath "%CLASSPATH%" org.gradle.wrapper.GradleWrapperMain %CMD_LINE_ARGS%
70 |
71 | :end
72 | @rem End local scope for the variables with windows NT shell
73 | if "%ERRORLEVEL%"=="0" goto mainEnd
74 |
75 | :fail
76 | rem Set variable GRADLE_EXIT_CONSOLE if you need the _script_ return code instead of
77 | rem the _cmd.exe /c_ return code!
78 | if not "" == "%GRADLE_EXIT_CONSOLE%" exit 1
79 | exit /b 1
80 |
81 | :mainEnd
82 | if "%OS%"=="Windows_NT" endlocal
83 |
84 | :omega
85 |
--------------------------------------------------------------------------------
/app/src/main/java/com/example/chenqiuyang/nfcread/NdefMessageParser.java:
--------------------------------------------------------------------------------
1 | /*
2 | * Copyright (C) 2010 The Android Open Source Project
3 | *
4 | * Licensed under the Apache License, Version 2.0 (the "License"); you may not
5 | * use this file except in compliance with the License. You may obtain a copy of
6 | * the License at
7 | *
8 | * http://www.apache.org/licenses/LICENSE-2.0
9 | *
10 | * Unless required by applicable law or agreed to in writing, software
11 | * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
12 | * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
13 | * License for the specific language governing permissions and limitations under
14 | * the License.
15 | */
16 | package com.example.chenqiuyang.nfcread;
17 |
18 | import java.io.ByteArrayOutputStream;
19 | import java.util.ArrayList;
20 | import java.util.List;
21 |
22 |
23 | import android.nfc.NdefMessage;
24 | import android.nfc.NdefRecord;
25 |
26 | import com.example.chenqiuyang.nfcread.read.ParsedNdefRecord;
27 | import com.example.chenqiuyang.nfcread.read.SmartPoster;
28 | import com.example.chenqiuyang.nfcread.read.TextRecord;
29 | import com.example.chenqiuyang.nfcread.read.UriRecord;
30 |
31 | /**
32 | *
33 | */
34 | public class NdefMessageParser {
35 |
36 | // Utility class
37 | private NdefMessageParser() {
38 |
39 | }
40 |
41 | /** Parse an NdefMessage */
42 | public static List parse(NdefMessage message) {
43 | return getRecords(message.getRecords());
44 | }
45 |
46 | public static List getRecords(NdefRecord[] records) {
47 | List elements = new ArrayList();
48 | for (final NdefRecord record : records) {
49 | if (UriRecord.isUri(record)) {
50 | elements.add(UriRecord.parse(record));
51 | } else if (TextRecord.isText(record)) {
52 | elements.add(TextRecord.parse(record));
53 | } else if (SmartPoster.isPoster(record)) {
54 | elements.add(SmartPoster.parse(record));
55 | } else {
56 | // String temp ="";
57 | // temp = new String(record.getPayload());
58 | // temp = bytesToHexString(record.getPayload(),true);
59 | elements.add(new ParsedNdefRecord() {
60 | @Override
61 | public String getViewText() {
62 | String temp = new String(record.getPayload()) + "\n";
63 | return temp;
64 | }
65 | });
66 | }
67 | }
68 | return elements;
69 | }
70 |
71 | private static String hexString="0123456789ABCDEF";
72 | public static String decode(String bytes) {
73 | ByteArrayOutputStream baos = new ByteArrayOutputStream(
74 | bytes.length() / 2);
75 | // ��ÿ2λ16����������װ��һ���ֽ�
76 | for (int i = 0; i < bytes.length(); i += 2)
77 | baos.write((hexString.indexOf(bytes.charAt(i)) << 4 | hexString
78 | .indexOf(bytes.charAt(i + 1))));
79 | return new String(baos.toByteArray());
80 | }
81 |
82 |
83 | private static String bytesToHexString(byte[] src, boolean isPrefix) {
84 | StringBuilder stringBuilder = new StringBuilder();
85 | if (isPrefix == true) {
86 | stringBuilder.append("0x");
87 | }
88 | if (src == null || src.length <= 0) {
89 | return null;
90 | }
91 | char[] buffer = new char[2];
92 | for (int i = 0; i < src.length; i++) {
93 | buffer[0] = Character.toUpperCase(Character.forDigit(
94 | (src[i] >>> 4) & 0x0F, 16));
95 | buffer[1] = Character.toUpperCase(Character.forDigit(src[i] & 0x0F,
96 | 16));
97 | System.out.println(buffer);
98 | stringBuilder.append(buffer);
99 | }
100 | return stringBuilder.toString();
101 | }
102 | }
103 |
--------------------------------------------------------------------------------
/app/src/main/java/com/example/chenqiuyang/nfcread/read/TextRecord.java:
--------------------------------------------------------------------------------
1 | /*
2 | * Copyright (C) 2010 The Android Open Source Project
3 | *
4 | * Licensed under the Apache License, Version 2.0 (the "License"); you may not
5 | * use this file except in compliance with the License. You may obtain a copy of
6 | * the License at
7 | *
8 | * http://www.apache.org/licenses/LICENSE-2.0
9 | *
10 | * Unless required by applicable law or agreed to in writing, software
11 | * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
12 | * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
13 | * License for the specific language governing permissions and limitations under
14 | * the License.
15 | */
16 | package com.example.chenqiuyang.nfcread.read;
17 |
18 | import java.io.UnsupportedEncodingException;
19 | import java.nio.charset.Charset;
20 | import java.util.Arrays;
21 |
22 | import android.app.Activity;
23 | import android.nfc.NdefRecord;
24 | import android.view.LayoutInflater;
25 | import android.view.View;
26 | import android.view.ViewGroup;
27 | import android.widget.TextView;
28 |
29 | import com.google.common.base.Preconditions;
30 |
31 | /**
32 | * An NFC Text Record
33 | */
34 | public class TextRecord implements ParsedNdefRecord{
35 |
36 | /** ISO/IANA language code */
37 | private final String mLanguageCode;
38 |
39 | private final String mText;
40 |
41 | public TextRecord(String languageCode, String text) {
42 | mLanguageCode = Preconditions.checkNotNull(languageCode);
43 | mText = Preconditions.checkNotNull(text);
44 | }
45 |
46 | @Override
47 | public String getViewText() {
48 | return mText;
49 | }
50 |
51 | public String getText() {
52 | return mText;
53 | }
54 |
55 | /**
56 | * Returns the ISO/IANA language code associated with this text element.
57 | */
58 | public String getLanguageCode() {
59 | return mLanguageCode;
60 | }
61 |
62 | // TODO: deal with text fields which span multiple NdefRecords
63 | public static TextRecord parse(NdefRecord record) {
64 | Preconditions.checkArgument(record.getTnf() == NdefRecord.TNF_WELL_KNOWN);
65 | Preconditions.checkArgument(Arrays.equals(record.getType(), NdefRecord.RTD_TEXT));
66 | try {
67 | byte[] payload = record.getPayload();
68 | /*
69 | * payload[0] contains the "Status Byte Encodings" field, per the
70 | * NFC Forum "Text Record Type Definition" section 3.2.1.
71 | *
72 | * bit7 is the Text Encoding Field.
73 | *
74 | * if (Bit_7 == 0): The text is encoded in UTF-8 if (Bit_7 == 1):
75 | * The text is encoded in UTF16
76 | *
77 | * Bit_6 is reserved for future use and must be set to zero.
78 | *
79 | * Bits 5 to 0 are the length of the IANA language code.
80 | */
81 |
82 | //��payloadΪ�յ�ʱ��ᱨ����Ϊrecord.getPayload()û��ֵ
83 | if (payload.length <= 0) {
84 | payload = record.getType();
85 | return null;
86 | }
87 | String textEncoding = ((payload[0] & 0200) == 0) ? "UTF-8" : "UTF-16";
88 | int languageCodeLength = payload[0] & 0077;
89 | String languageCode = new String(payload, 1, languageCodeLength, "US-ASCII");
90 | String text =
91 | new String(payload, languageCodeLength + 1,
92 | payload.length - languageCodeLength - 1, textEncoding);
93 | return new TextRecord(languageCode, text);
94 | } catch (UnsupportedEncodingException e) {
95 | // should never happen unless we get a malformed tag.
96 | throw new IllegalArgumentException(e);
97 | }
98 | }
99 |
100 | public static boolean isText(NdefRecord record) {
101 | try {
102 | parse(record);
103 | return true;
104 | } catch (IllegalArgumentException e) {
105 | return false;
106 | }
107 | }
108 | }
109 |
--------------------------------------------------------------------------------
/app/src/main/java/com/example/chenqiuyang/nfcread/NfcActivity.java:
--------------------------------------------------------------------------------
1 | package com.example.chenqiuyang.nfcread;
2 |
3 | import android.annotation.SuppressLint;
4 | import android.app.Activity;
5 | import android.app.PendingIntent;
6 | import android.content.Intent;
7 | import android.nfc.NdefMessage;
8 | import android.nfc.NdefRecord;
9 | import android.nfc.NfcAdapter;
10 | import android.nfc.NfcEvent;
11 | import android.nfc.Tag;
12 | import android.nfc.tech.MifareClassic;
13 | import android.nfc.tech.MifareUltralight;
14 | import android.os.Bundle;
15 |
16 | import android.util.Log;
17 | import android.view.View;
18 | import android.widget.Button;
19 | import android.widget.TextView;
20 | import android.widget.Toast;
21 |
22 | import com.example.chenqiuyang.nfcread.read.ParsedNdefRecord;
23 | import com.example.chenqiuyang.nfcread.read.TextRecord;
24 |
25 | import java.util.Calendar;
26 | import java.util.Date;
27 | import java.util.List;
28 | import java.util.Locale;
29 | import java.util.Timer;
30 |
31 | /**
32 | * TODO:功能说明
33 | *
34 | * @author: chenqiuyang
35 | * @date: 2018-07-12 11:18
36 | */
37 | public class NfcActivity extends Activity {
38 |
39 | private static final String TAG = "NfcActivity";
40 | private TextView tvNFCMessage;
41 | private PendingIntent mPendingIntent;
42 | private NfcAdapter mNfcAdapter;
43 | private Button btnClean;
44 |
45 | @Override
46 | protected void onCreate(Bundle savedInstanceState) {
47 | super.onCreate(savedInstanceState);
48 | setContentView(R.layout.activity_nfc);
49 | Log.i(TAG, "onCreate: ");
50 | btnClean = findViewById(R.id.btn_clean);
51 | tvNFCMessage = findViewById(R.id.tv_show_nfc);
52 |
53 |
54 | resolveIntent(getIntent());
55 |
56 | //初始化nfc
57 | mNfcAdapter = NfcAdapter.getDefaultAdapter(this);
58 | mPendingIntent = PendingIntent.getActivity(this, 0,
59 | new Intent(this, getClass()).addFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP), 0);
60 | if (mNfcAdapter == null) {
61 | Toast.makeText(NfcActivity.this, "nfc is not available", Toast.LENGTH_SHORT).show();
62 | finish();
63 | return;
64 | }
65 |
66 |
67 | btnClean.setOnClickListener(new View.OnClickListener() {
68 | @Override
69 | public void onClick(View v) {
70 | tvNFCMessage.setText("");
71 | }
72 | });
73 | }
74 |
75 | @Override
76 | protected void onResume() {
77 | super.onResume();
78 | Log.i(TAG, "onResume: ");
79 | if (mNfcAdapter != null) { //有nfc功能
80 | if (mNfcAdapter.isEnabled()) {
81 | //nfc功能打开了
82 | //隐式启动
83 | mNfcAdapter.enableForegroundDispatch(this, mPendingIntent, null, null);
84 | } else {
85 | Toast.makeText(NfcActivity.this, "请打开nfc功能", Toast.LENGTH_SHORT).show();
86 | }
87 | }
88 | }
89 |
90 | @Override
91 | protected void onNewIntent(Intent intent) {
92 | super.onNewIntent(intent);
93 | Log.i(TAG, "onNewIntent: ");
94 | setIntent(intent);
95 | if (mNfcAdapter != null) { //有nfc功能
96 | if (mNfcAdapter.isEnabled()) {//nfc功能打开了
97 | resolveIntent(getIntent());
98 | } else {
99 | Toast.makeText(NfcActivity.this, "请打开nfc功能", Toast.LENGTH_SHORT).show();
100 | }
101 | }
102 | }
103 |
104 |
105 | @Override
106 | protected void onPause() {
107 | super.onPause();
108 | if (mNfcAdapter != null) {
109 | mNfcAdapter.disableForegroundDispatch(this);
110 | }
111 | }
112 |
113 | //初次判断是什么类型的NFC卡
114 | private void resolveIntent(Intent intent) {
115 | NdefMessage[] msgs = NfcUtil.getNdefMsg(intent); //重点功能,解析nfc标签中的数据
116 |
117 | if (msgs == null) {
118 | Toast.makeText(NfcActivity.this, "非NFC启动", Toast.LENGTH_SHORT).show();
119 | } else {
120 | setNFCMsgView(msgs);
121 | }
122 |
123 | }
124 |
125 | /**
126 | * 显示扫描后的信息
127 | *
128 | * @param ndefMessages ndef数据
129 | */
130 | @SuppressLint("SetTextI18n")
131 | private void setNFCMsgView(NdefMessage[] ndefMessages) {
132 | if (ndefMessages == null || ndefMessages.length == 0) {
133 | return;
134 | }
135 |
136 | // tvNFCMessage.setText("Payload:" + new String(ndefMessages[0].getRecords()[0].getPayload()) + "\n");
137 |
138 | Calendar calendar = Calendar.getInstance();
139 | int hour = calendar.get(Calendar.HOUR_OF_DAY);
140 | int minute = calendar.get(Calendar.MINUTE);
141 | tvNFCMessage.append(hour + ":" + minute + "\n");
142 | List records = NdefMessageParser.parse(ndefMessages[0]);
143 | final int size = records.size();
144 | for (int i = 0; i < size; i++) {
145 | ParsedNdefRecord record = records.get(i);
146 | tvNFCMessage.append(record.getViewText() + "\n");
147 | }
148 | }
149 |
150 | }
151 |
--------------------------------------------------------------------------------
/app/src/main/java/com/example/chenqiuyang/nfcread/read/UriRecord.java:
--------------------------------------------------------------------------------
1 | /*
2 | * Copyright (C) 2010 The Android Open Source Project
3 | *
4 | * Licensed under the Apache License, Version 2.0 (the "License");
5 | * you may not use this file except in compliance with the License.
6 | * You may obtain a copy of the License at
7 | *
8 | * http://www.apache.org/licenses/LICENSE-2.0
9 | *
10 | * Unless required by applicable law or agreed to in writing, software
11 | * distributed under the License is distributed on an "AS IS" BASIS,
12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 | * See the License for the specific language governing permissions and
14 | * limitations under the License.
15 | */
16 | package com.example.chenqiuyang.nfcread.read;
17 |
18 | import java.nio.charset.Charset;
19 | import java.util.Arrays;
20 | import android.net.Uri;
21 | import android.nfc.NdefRecord;
22 | import com.google.common.base.Preconditions;
23 | import com.google.common.collect.BiMap;
24 | import com.google.common.collect.ImmutableBiMap;
25 | import com.google.common.primitives.Bytes;
26 |
27 | /**
28 | * A parsed record containing a Uri.
29 | */
30 | public class UriRecord implements ParsedNdefRecord {
31 |
32 | private static final String TAG = "UriRecord";
33 |
34 | public static final String RECORD_TYPE = "UriRecord";
35 |
36 | /**
37 | * NFC Forum "URI Record Type Definition"
38 | *
39 | * This is a mapping of "URI Identifier Codes" to URI string prefixes,
40 | * per section 3.2.2 of the NFC Forum URI Record Type Definition document.
41 | */
42 | private static final BiMap URI_PREFIX_MAP = ImmutableBiMap.builder()
43 | .put((byte) 0x00, "")
44 | .put((byte) 0x01, "http://www.")
45 | .put((byte) 0x02, "https://www.")
46 | .put((byte) 0x03, "http://")
47 | .put((byte) 0x04, "https://")
48 | .put((byte) 0x05, "tel:")
49 | .put((byte) 0x06, "mailto:")
50 | .put((byte) 0x07, "ftp://anonymous:anonymous@")
51 | .put((byte) 0x08, "ftp://ftp.")
52 | .put((byte) 0x09, "ftps://")
53 | .put((byte) 0x0A, "sftp://")
54 | .put((byte) 0x0B, "smb://")
55 | .put((byte) 0x0C, "nfs://")
56 | .put((byte) 0x0D, "ftp://")
57 | .put((byte) 0x0E, "dav://")
58 | .put((byte) 0x0F, "news:")
59 | .put((byte) 0x10, "telnet://")
60 | .put((byte) 0x11, "imap:")
61 | .put((byte) 0x12, "rtsp://")
62 | .put((byte) 0x13, "urn:")
63 | .put((byte) 0x14, "pop:")
64 | .put((byte) 0x15, "sip:")
65 | .put((byte) 0x16, "sips:")
66 | .put((byte) 0x17, "tftp:")
67 | .put((byte) 0x18, "btspp://")
68 | .put((byte) 0x19, "btl2cap://")
69 | .put((byte) 0x1A, "btgoep://")
70 | .put((byte) 0x1B, "tcpobex://")
71 | .put((byte) 0x1C, "irdaobex://")
72 | .put((byte) 0x1D, "file://")
73 | .put((byte) 0x1E, "urn:epc:id:")
74 | .put((byte) 0x1F, "urn:epc:tag:")
75 | .put((byte) 0x20, "urn:epc:pat:")
76 | .put((byte) 0x21, "urn:epc:raw:")
77 | .put((byte) 0x22, "urn:epc:")
78 | .put((byte) 0x23, "urn:nfc:")
79 | .build();
80 |
81 | private final Uri mUri;
82 |
83 | private UriRecord(Uri uri) {
84 | this.mUri = Preconditions.checkNotNull(uri);
85 | }
86 |
87 | public String getViewText(){
88 | return mUri.toString();
89 | }
90 |
91 | public Uri getUri() {
92 | return mUri;
93 | }
94 |
95 | /**
96 | * Convert {@link NdefRecord} into a {@link Uri}.
97 | * This will handle both TNF_WELL_KNOWN / RTD_URI and TNF_ABSOLUTE_URI.
98 | *
99 | * @throws IllegalArgumentException if the NdefRecord is not a record
100 | * containing a URI.
101 | */
102 | public static UriRecord parse(NdefRecord record) {
103 | short tnf = record.getTnf();
104 | if (tnf == NdefRecord.TNF_WELL_KNOWN) {
105 | return parseWellKnown(record);
106 | } else if (tnf == NdefRecord.TNF_ABSOLUTE_URI) {
107 | return parseAbsolute(record);
108 | }
109 | throw new IllegalArgumentException("Unknown TNF " + tnf);
110 | }
111 |
112 | /** Parse and absolute URI record */
113 | private static UriRecord parseAbsolute(NdefRecord record) {
114 | byte[] payload = record.getPayload();
115 | Uri uri = Uri.parse(new String(payload, Charset.forName("UTF-8")));
116 | return new UriRecord(uri);
117 | }
118 |
119 | /** Parse an well known URI record */
120 | private static UriRecord parseWellKnown(NdefRecord record) {
121 | Preconditions.checkArgument(Arrays.equals(record.getType(), NdefRecord.RTD_URI));
122 | byte[] payload = record.getPayload();
123 | /*
124 | * payload[0] contains the URI Identifier Code, per the
125 | * NFC Forum "URI Record Type Definition" section 3.2.2.
126 | *
127 | * payload[1]...payload[payload.length - 1] contains the rest of
128 | * the URI.
129 | */
130 | String prefix = URI_PREFIX_MAP.get(payload[0]);
131 | byte[] fullUri =
132 | Bytes.concat(prefix.getBytes(Charset.forName("UTF-8")), Arrays.copyOfRange(payload, 1,
133 | payload.length));
134 | Uri uri = Uri.parse(new String(fullUri, Charset.forName("UTF-8")));
135 | return new UriRecord(uri);
136 | }
137 |
138 | public static boolean isUri(NdefRecord record) {
139 | try {
140 | parse(record);
141 | return true;
142 | } catch (IllegalArgumentException e) {
143 | return false;
144 | }
145 | }
146 |
147 | private static final byte[] EMPTY = new byte[0];
148 | }
149 |
--------------------------------------------------------------------------------
/gradlew:
--------------------------------------------------------------------------------
1 | #!/usr/bin/env sh
2 |
3 | ##############################################################################
4 | ##
5 | ## Gradle start up script for UN*X
6 | ##
7 | ##############################################################################
8 |
9 | # Attempt to set APP_HOME
10 | # Resolve links: $0 may be a link
11 | PRG="$0"
12 | # Need this for relative symlinks.
13 | while [ -h "$PRG" ] ; do
14 | ls=`ls -ld "$PRG"`
15 | link=`expr "$ls" : '.*-> \(.*\)$'`
16 | if expr "$link" : '/.*' > /dev/null; then
17 | PRG="$link"
18 | else
19 | PRG=`dirname "$PRG"`"/$link"
20 | fi
21 | done
22 | SAVED="`pwd`"
23 | cd "`dirname \"$PRG\"`/" >/dev/null
24 | APP_HOME="`pwd -P`"
25 | cd "$SAVED" >/dev/null
26 |
27 | APP_NAME="Gradle"
28 | APP_BASE_NAME=`basename "$0"`
29 |
30 | # Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script.
31 | DEFAULT_JVM_OPTS=""
32 |
33 | # Use the maximum available, or set MAX_FD != -1 to use that value.
34 | MAX_FD="maximum"
35 |
36 | warn () {
37 | echo "$*"
38 | }
39 |
40 | die () {
41 | echo
42 | echo "$*"
43 | echo
44 | exit 1
45 | }
46 |
47 | # OS specific support (must be 'true' or 'false').
48 | cygwin=false
49 | msys=false
50 | darwin=false
51 | nonstop=false
52 | case "`uname`" in
53 | CYGWIN* )
54 | cygwin=true
55 | ;;
56 | Darwin* )
57 | darwin=true
58 | ;;
59 | MINGW* )
60 | msys=true
61 | ;;
62 | NONSTOP* )
63 | nonstop=true
64 | ;;
65 | esac
66 |
67 | CLASSPATH=$APP_HOME/gradle/wrapper/gradle-wrapper.jar
68 |
69 | # Determine the Java command to use to start the JVM.
70 | if [ -n "$JAVA_HOME" ] ; then
71 | if [ -x "$JAVA_HOME/jre/sh/java" ] ; then
72 | # IBM's JDK on AIX uses strange locations for the executables
73 | JAVACMD="$JAVA_HOME/jre/sh/java"
74 | else
75 | JAVACMD="$JAVA_HOME/bin/java"
76 | fi
77 | if [ ! -x "$JAVACMD" ] ; then
78 | die "ERROR: JAVA_HOME is set to an invalid directory: $JAVA_HOME
79 |
80 | Please set the JAVA_HOME variable in your environment to match the
81 | location of your Java installation."
82 | fi
83 | else
84 | JAVACMD="java"
85 | which java >/dev/null 2>&1 || die "ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH.
86 |
87 | Please set the JAVA_HOME variable in your environment to match the
88 | location of your Java installation."
89 | fi
90 |
91 | # Increase the maximum file descriptors if we can.
92 | if [ "$cygwin" = "false" -a "$darwin" = "false" -a "$nonstop" = "false" ] ; then
93 | MAX_FD_LIMIT=`ulimit -H -n`
94 | if [ $? -eq 0 ] ; then
95 | if [ "$MAX_FD" = "maximum" -o "$MAX_FD" = "max" ] ; then
96 | MAX_FD="$MAX_FD_LIMIT"
97 | fi
98 | ulimit -n $MAX_FD
99 | if [ $? -ne 0 ] ; then
100 | warn "Could not set maximum file descriptor limit: $MAX_FD"
101 | fi
102 | else
103 | warn "Could not query maximum file descriptor limit: $MAX_FD_LIMIT"
104 | fi
105 | fi
106 |
107 | # For Darwin, add options to specify how the application appears in the dock
108 | if $darwin; then
109 | GRADLE_OPTS="$GRADLE_OPTS \"-Xdock:name=$APP_NAME\" \"-Xdock:icon=$APP_HOME/media/gradle.icns\""
110 | fi
111 |
112 | # For Cygwin, switch paths to Windows format before running java
113 | if $cygwin ; then
114 | APP_HOME=`cygpath --path --mixed "$APP_HOME"`
115 | CLASSPATH=`cygpath --path --mixed "$CLASSPATH"`
116 | JAVACMD=`cygpath --unix "$JAVACMD"`
117 |
118 | # We build the pattern for arguments to be converted via cygpath
119 | ROOTDIRSRAW=`find -L / -maxdepth 1 -mindepth 1 -type d 2>/dev/null`
120 | SEP=""
121 | for dir in $ROOTDIRSRAW ; do
122 | ROOTDIRS="$ROOTDIRS$SEP$dir"
123 | SEP="|"
124 | done
125 | OURCYGPATTERN="(^($ROOTDIRS))"
126 | # Add a user-defined pattern to the cygpath arguments
127 | if [ "$GRADLE_CYGPATTERN" != "" ] ; then
128 | OURCYGPATTERN="$OURCYGPATTERN|($GRADLE_CYGPATTERN)"
129 | fi
130 | # Now convert the arguments - kludge to limit ourselves to /bin/sh
131 | i=0
132 | for arg in "$@" ; do
133 | CHECK=`echo "$arg"|egrep -c "$OURCYGPATTERN" -`
134 | CHECK2=`echo "$arg"|egrep -c "^-"` ### Determine if an option
135 |
136 | if [ $CHECK -ne 0 ] && [ $CHECK2 -eq 0 ] ; then ### Added a condition
137 | eval `echo args$i`=`cygpath --path --ignore --mixed "$arg"`
138 | else
139 | eval `echo args$i`="\"$arg\""
140 | fi
141 | i=$((i+1))
142 | done
143 | case $i in
144 | (0) set -- ;;
145 | (1) set -- "$args0" ;;
146 | (2) set -- "$args0" "$args1" ;;
147 | (3) set -- "$args0" "$args1" "$args2" ;;
148 | (4) set -- "$args0" "$args1" "$args2" "$args3" ;;
149 | (5) set -- "$args0" "$args1" "$args2" "$args3" "$args4" ;;
150 | (6) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" ;;
151 | (7) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" ;;
152 | (8) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" "$args7" ;;
153 | (9) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" "$args7" "$args8" ;;
154 | esac
155 | fi
156 |
157 | # Escape application args
158 | save () {
159 | for i do printf %s\\n "$i" | sed "s/'/'\\\\''/g;1s/^/'/;\$s/\$/' \\\\/" ; done
160 | echo " "
161 | }
162 | APP_ARGS=$(save "$@")
163 |
164 | # Collect all arguments for the java command, following the shell quoting and substitution rules
165 | eval set -- $DEFAULT_JVM_OPTS $JAVA_OPTS $GRADLE_OPTS "\"-Dorg.gradle.appname=$APP_BASE_NAME\"" -classpath "\"$CLASSPATH\"" org.gradle.wrapper.GradleWrapperMain "$APP_ARGS"
166 |
167 | # by default we should be in the correct project dir, but when run from Finder on Mac, the cwd is wrong
168 | if [ "$(uname)" = "Darwin" ] && [ "$HOME" = "$PWD" ]; then
169 | cd "$(dirname "$0")"
170 | fi
171 |
172 | exec "$JAVACMD" "$@"
173 |
--------------------------------------------------------------------------------
/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/java/com/example/chenqiuyang/nfcread/NfcUtil.java:
--------------------------------------------------------------------------------
1 | package com.example.chenqiuyang.nfcread;
2 |
3 | import android.content.Intent;
4 | import android.nfc.NdefMessage;
5 | import android.nfc.NdefRecord;
6 | import android.nfc.NfcAdapter;
7 | import android.nfc.Tag;
8 | import android.nfc.tech.MifareClassic;
9 | import android.nfc.tech.MifareUltralight;
10 | import android.os.Parcelable;
11 | import android.util.Log;
12 | import android.widget.Toast;
13 |
14 | import java.util.Arrays;
15 |
16 | /**
17 | * TODO:功能说明 Nfc工具类
18 | *
19 | * @author: chenqiuyang
20 | * @date: 2018-07-12 11:33
21 | */
22 | public class NfcUtil {
23 | private static final String TAG = "NfcUtil";
24 |
25 | /**
26 | * 解析 ndefRecord 文本数据
27 | * @param ndefRecord
28 | * @return
29 | */
30 | public static String parse(NdefRecord ndefRecord) {
31 | // verify tnf 得到TNF的值
32 | if (ndefRecord.getTnf() != NdefRecord.TNF_WELL_KNOWN) {
33 | return null;
34 | }
35 |
36 | // 得到字节数组进行判断
37 | if (!Arrays.equals(ndefRecord.getType(), NdefRecord.RTD_TEXT)) {
38 | return null;
39 | }
40 |
41 | try {
42 | // 获得一个字节流
43 | byte[] payload = ndefRecord.getPayload();
44 | // payload[0]取第一个字节。 0x80:十六进制(最高位是1剩下全是0)
45 | String textEncoding = ((payload[0] & 0x80) == 0) ? "UTF-8"
46 | : "UTF-16";
47 | // 获得语言编码长度
48 | int languageCodeLength = payload[0] & 0x3f;
49 | // 获得语言编码
50 | String languageCode = new String(payload, 1, languageCodeLength,
51 | "US-ASCII");
52 | //
53 | String text = new String(payload, languageCodeLength + 1,
54 | payload.length - languageCodeLength - 1, textEncoding);
55 |
56 | return text;
57 | } catch (Exception e) {
58 | throw new IllegalArgumentException();
59 | }
60 | }
61 |
62 |
63 | //初次判断是什么类型的NFC卡
64 | public static NdefMessage[] getNdefMsg(Intent intent) {
65 | if (intent == null)
66 | return null;
67 |
68 | //nfc卡支持的格式
69 | Tag tag = intent.getParcelableExtra(NfcAdapter.EXTRA_TAG);
70 | String[] temp = tag.getTechList();
71 | for (String s : temp) {
72 | Log.i(TAG, "resolveIntent tag: " + s);
73 | }
74 |
75 |
76 | String action = intent.getAction();
77 |
78 | if (NfcAdapter.ACTION_NDEF_DISCOVERED.equals(action) ||
79 | NfcAdapter.ACTION_TECH_DISCOVERED.equals(action) ||
80 | NfcAdapter.ACTION_TAG_DISCOVERED.equals(action)) {
81 | Parcelable[] rawMessage = intent.getParcelableArrayExtra(NfcAdapter.EXTRA_NDEF_MESSAGES);
82 | NdefMessage[] ndefMessages;
83 |
84 | // 判断是哪种类型的数据 默认为NDEF格式
85 | if (rawMessage != null) {
86 | Log.i(TAG, "getNdefMsg: ndef格式 ");
87 | ndefMessages = new NdefMessage[rawMessage.length];
88 | for (int i = 0; i < rawMessage.length; i++) {
89 | ndefMessages[i] = (NdefMessage) rawMessage[i];
90 | }
91 | } else {
92 | //未知类型
93 | Log.i(TAG, "getNdefMsg: 未知类型");
94 | byte[] empty = new byte[0];
95 | byte[] id = intent.getByteArrayExtra(NfcAdapter.EXTRA_ID);
96 | Parcelable parcelable = intent
97 | .getParcelableExtra(NfcAdapter.EXTRA_TAG);
98 | byte[] payload = dumpTagData(parcelable).getBytes();
99 | NdefRecord record = new NdefRecord(NdefRecord.TNF_UNKNOWN,
100 | empty, id, payload);
101 | NdefMessage msg = new NdefMessage(new NdefRecord[]{record});
102 | ndefMessages = new NdefMessage[]{msg};
103 | }
104 |
105 |
106 | return ndefMessages;
107 | }
108 |
109 | return null;
110 | }
111 |
112 |
113 |
114 | //一般公家卡,扫描的信息
115 | private static String dumpTagData(Parcelable p) {
116 | StringBuilder sb = new StringBuilder();
117 | Tag tag = (Tag) p;
118 | byte[] id = tag.getId();
119 | sb.append("Tag ID (hex): ").append(getHex(id)).append("\n");
120 | sb.append("Tag ID (dec): ").append(getDec(id)).append("\n");
121 | sb.append("ID (reversed): ").append(getReversed(id)).append("\n");
122 |
123 | String prefix = "android.nfc.tech.";
124 | sb.append("Technologies: ");
125 | for (String tech : tag.getTechList()) {
126 | sb.append(tech.substring(prefix.length()));
127 | sb.append(", ");
128 | }
129 | sb.delete(sb.length() - 2, sb.length());
130 | for (String tech : tag.getTechList()) {
131 | if (tech.equals(MifareClassic.class.getName())) {
132 | sb.append('\n');
133 | MifareClassic mifareTag = MifareClassic.get(tag);
134 | String type = "Unknown";
135 | switch (mifareTag.getType()) {
136 | case MifareClassic.TYPE_CLASSIC:
137 | type = "Classic";
138 | break;
139 | case MifareClassic.TYPE_PLUS:
140 | type = "Plus";
141 | break;
142 | case MifareClassic.TYPE_PRO:
143 | type = "Pro";
144 | break;
145 | }
146 | sb.append("Mifare Classic type: ");
147 | sb.append(type);
148 | sb.append('\n');
149 |
150 | sb.append("Mifare size: ");
151 | sb.append(mifareTag.getSize() + " bytes");
152 | sb.append('\n');
153 |
154 | sb.append("Mifare sectors: ");
155 | sb.append(mifareTag.getSectorCount());
156 | sb.append('\n');
157 |
158 | sb.append("Mifare blocks: ");
159 | sb.append(mifareTag.getBlockCount());
160 | }
161 |
162 | if (tech.equals(MifareUltralight.class.getName())) {
163 | sb.append('\n');
164 | MifareUltralight mifareUlTag = MifareUltralight.get(tag);
165 | String type = "Unknown";
166 | switch (mifareUlTag.getType()) {
167 | case MifareUltralight.TYPE_ULTRALIGHT:
168 | type = "Ultralight";
169 | break;
170 | case MifareUltralight.TYPE_ULTRALIGHT_C:
171 | type = "Ultralight C";
172 | break;
173 | }
174 | sb.append("Mifare Ultralight type: ");
175 | sb.append(type);
176 | }
177 | }
178 | return sb.toString();
179 | }
180 |
181 |
182 |
183 | private static String getHex(byte[] bytes) {
184 | StringBuilder sb = new StringBuilder();
185 | for (int i = bytes.length - 1; i >= 0; --i) {
186 | int b = bytes[i] & 0xff;
187 | if (b < 0x10)
188 | sb.append('0');
189 | sb.append(Integer.toHexString(b));
190 | if (i > 0) {
191 | sb.append(" ");
192 | }
193 | }
194 | return sb.toString();
195 | }
196 |
197 | private static long getDec(byte[] bytes) {
198 | long result = 0;
199 | long factor = 1;
200 | for (int i = 0; i < bytes.length; ++i) {
201 | long value = bytes[i] & 0xffl;
202 | result += value * factor;
203 | factor *= 256l;
204 | }
205 | return result;
206 | }
207 |
208 | private static long getReversed(byte[] bytes) {
209 | long result = 0;
210 | long factor = 1;
211 | for (int i = bytes.length - 1; i >= 0; --i) {
212 | long value = bytes[i] & 0xffl;
213 | result += value * factor;
214 | factor *= 256l;
215 | }
216 | return result;
217 | }
218 |
219 | }
220 |
--------------------------------------------------------------------------------
/app/src/main/java/com/example/chenqiuyang/nfcread/read/SmartPoster.java:
--------------------------------------------------------------------------------
1 | /*
2 | * Copyright (C) 2010 The Android Open Source Project
3 | *
4 | * Licensed under the Apache License, Version 2.0 (the "License");
5 | * you may not use this file except in compliance with the License.
6 | * You may obtain a copy of the License at
7 | *
8 | * http://www.apache.org/licenses/LICENSE-2.0
9 | *
10 | * Unless required by applicable law or agreed to in writing, software
11 | * distributed under the License is distributed on an "AS IS" BASIS,
12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 | * See the License for the specific language governing permissions and
14 | * limitations under the License.
15 | */
16 | package com.example.chenqiuyang.nfcread.read;
17 |
18 | import java.util.Arrays;
19 | import java.util.NoSuchElementException;
20 |
21 |
22 | import android.nfc.FormatException;
23 | import android.nfc.NdefMessage;
24 | import android.nfc.NdefRecord;
25 |
26 | import com.example.chenqiuyang.nfcread.NdefMessageParser;
27 | import com.google.common.base.Charsets;
28 | import com.google.common.base.Preconditions;
29 | import com.google.common.collect.ImmutableMap;
30 | import com.google.common.collect.Iterables;
31 |
32 | /**
33 | * A representation of an NFC Forum "Smart Poster".
34 | */
35 | public class SmartPoster implements ParsedNdefRecord {
36 |
37 | /**
38 | * NFC Forum Smart Poster Record Type Definition section 3.2.1.
39 | *
40 | * "The Title record for the service (there can be many of these in
41 | * different languages, but a language MUST NOT be repeated). This record is
42 | * optional."
43 | */
44 | private final TextRecord mTitleRecord;
45 |
46 | /**
47 | * NFC Forum Smart Poster Record Type Definition section 3.2.1.
48 | *
49 | * "The URI record. This is the core of the Smart Poster, and all other
50 | * records are just metadata about this record. There MUST be one URI record
51 | * and there MUST NOT be more than one."
52 | */
53 | private final UriRecord mUriRecord;
54 |
55 | /**
56 | * NFC Forum Smart Poster Record Type Definition section 3.2.1.
57 | *
58 | * "The Action record. This record describes how the service should be
59 | * treated. For example, the action may indicate that the device should save
60 | * the URI as a bookmark or open a browser. The Action record is optional.
61 | * If it does not exist, the device may decide what to do with the service.
62 | * If the action record exists, it should be treated as a strong suggestion;
63 | * the UI designer may ignore it, but doing so will induce a different user
64 | * experience from device to device."
65 | */
66 | private final RecommendedAction mAction;
67 |
68 | /**
69 | * NFC Forum Smart Poster Record Type Definition section 3.2.1.
70 | *
71 | * "The Type record. If the URI references an external entity (e.g., via a
72 | * URL), the Type record may be used to declare the MIME type of the entity.
73 | * This can be used to tell the mobile device what kind of an object it can
74 | * expect before it opens the connection. The Type record is optional."
75 | */
76 | private final String mType;
77 |
78 | private SmartPoster(UriRecord uri, TextRecord title, RecommendedAction action, String type) {
79 | mUriRecord = Preconditions.checkNotNull(uri);
80 | mTitleRecord = title;
81 | mAction = Preconditions.checkNotNull(action);
82 | mType = type;
83 | }
84 |
85 | public UriRecord getUriRecord() {
86 | return mUriRecord;
87 | }
88 |
89 | /**
90 | * Returns the title of the smart poster. This may be {@code null}.
91 | */
92 | public TextRecord getTitle() {
93 | return mTitleRecord;
94 | }
95 |
96 | public static SmartPoster parse(NdefRecord record) {
97 | Preconditions.checkArgument(record.getTnf() == NdefRecord.TNF_WELL_KNOWN);
98 | Preconditions.checkArgument(Arrays.equals(record.getType(), NdefRecord.RTD_SMART_POSTER));
99 | try {
100 | NdefMessage subRecords = new NdefMessage(record.getPayload());
101 | return parse(subRecords.getRecords());
102 | } catch (FormatException e) {
103 | throw new IllegalArgumentException(e);
104 | }
105 | }
106 |
107 | public static SmartPoster parse(NdefRecord[] recordsRaw) {
108 | try {
109 | Iterable records = NdefMessageParser.getRecords(recordsRaw);
110 | UriRecord uri = Iterables.getOnlyElement(Iterables.filter(records, UriRecord.class));
111 | TextRecord title = getFirstIfExists(records, TextRecord.class);
112 | RecommendedAction action = parseRecommendedAction(recordsRaw);
113 | String type = parseType(recordsRaw);
114 | return new SmartPoster(uri, title, action, type);
115 | } catch (NoSuchElementException e) {
116 | throw new IllegalArgumentException(e);
117 | }
118 | }
119 |
120 | public static boolean isPoster(NdefRecord record) {
121 | try {
122 | parse(record);
123 | return true;
124 | } catch (IllegalArgumentException e) {
125 | return false;
126 | }
127 | }
128 |
129 |
130 | /**
131 | * Returns the first element of {@code elements} which is an instance of
132 | * {@code type}, or {@code null} if no such element exists.
133 | */
134 | private static T getFirstIfExists(Iterable> elements, Class type) {
135 | Iterable filtered = Iterables.filter(elements, type);
136 | T instance = null;
137 | if (!Iterables.isEmpty(filtered)) {
138 | instance = Iterables.get(filtered, 0);
139 | }
140 | return instance;
141 | }
142 |
143 | private enum RecommendedAction {
144 | UNKNOWN((byte) -1), DO_ACTION((byte) 0), SAVE_FOR_LATER((byte) 1), OPEN_FOR_EDITING(
145 | (byte) 2);
146 |
147 | private static final ImmutableMap LOOKUP;
148 | static {
149 | ImmutableMap.Builder builder = ImmutableMap.builder();
150 | for (RecommendedAction action : RecommendedAction.values()) {
151 | builder.put(action.getByte(), action);
152 | }
153 | LOOKUP = builder.build();
154 | }
155 |
156 | private final byte mAction;
157 |
158 | private RecommendedAction(byte val) {
159 | this.mAction = val;
160 | }
161 |
162 | private byte getByte() {
163 | return mAction;
164 | }
165 | }
166 |
167 | private static NdefRecord getByType(byte[] type, NdefRecord[] records) {
168 | for (NdefRecord record : records) {
169 | if (Arrays.equals(type, record.getType())) {
170 | return record;
171 | }
172 | }
173 | return null;
174 | }
175 |
176 | private static final byte[] ACTION_RECORD_TYPE = new byte[] {'a', 'c', 't'};
177 |
178 | private static RecommendedAction parseRecommendedAction(NdefRecord[] records) {
179 | NdefRecord record = getByType(ACTION_RECORD_TYPE, records);
180 | if (record == null) {
181 | return RecommendedAction.UNKNOWN;
182 | }
183 | byte action = record.getPayload()[0];
184 | if (RecommendedAction.LOOKUP.containsKey(action)) {
185 | return RecommendedAction.LOOKUP.get(action);
186 | }
187 | return RecommendedAction.UNKNOWN;
188 | }
189 |
190 | private static final byte[] TYPE_TYPE = new byte[] {'t'};
191 |
192 | private static String parseType(NdefRecord[] records) {
193 | NdefRecord type = getByType(TYPE_TYPE, records);
194 | if (type == null) {
195 | return null;
196 | }
197 | return new String(type.getPayload(), Charsets.UTF_8);
198 | }
199 |
200 | @Override
201 | public String getViewText() {
202 | if (mTitleRecord != null) {
203 | return mTitleRecord.getText();
204 | }
205 | return mTitleRecord.getText();
206 | }
207 | }
208 |
--------------------------------------------------------------------------------