Rewrite of Remote Smart Card Reader

- use material design
- use AsyncTask instead of Runnable for VPCDWorker to integrate with the
  App's lifecycle
- use a dedicated Preference Activity
- integrated zxing's QR code scanner
- use Snackbar instead of Toast
- capture debug messages in log instead of explicitly passing messages
- use reader mode only, breaks support of Android before kitkat
This commit is contained in:
Frank Morgner
2016-04-01 02:27:37 +02:00
parent aa82e78ce7
commit 1d3e5fe4fd
51 changed files with 1624 additions and 717 deletions

8
remote-reader/.gitignore vendored Normal file
View File

@@ -0,0 +1,8 @@
*.iml
.gradle
/local.properties
/.idea/workspace.xml
/.idea/libraries
.DS_Store
/build
/captures

View File

@@ -65,33 +65,37 @@
<sourceFolder url="file://$MODULE_DIR$/src/androidTest/jni" isTestSource="true" />
<sourceFolder url="file://$MODULE_DIR$/src/androidTest/rs" isTestSource="true" />
<excludeFolder url="file://$MODULE_DIR$/build/intermediates/assets" />
<excludeFolder url="file://$MODULE_DIR$/build/intermediates/bundles" />
<excludeFolder url="file://$MODULE_DIR$/build/intermediates/blame" />
<excludeFolder url="file://$MODULE_DIR$/build/intermediates/classes" />
<excludeFolder url="file://$MODULE_DIR$/build/intermediates/coverage-instrumented-classes" />
<excludeFolder url="file://$MODULE_DIR$/build/intermediates/dependency-cache" />
<excludeFolder url="file://$MODULE_DIR$/build/intermediates/dex" />
<excludeFolder url="file://$MODULE_DIR$/build/intermediates/dex-cache" />
<excludeFolder url="file://$MODULE_DIR$/build/intermediates/exploded-aar/com.android.support/appcompat-v7/23.0.1/jars" />
<excludeFolder url="file://$MODULE_DIR$/build/intermediates/exploded-aar/com.android.support/support-v4/23.0.1/jars" />
<excludeFolder url="file://$MODULE_DIR$/build/intermediates/exploded-aar/com.android.support/animated-vector-drawable/23.2.1/jars" />
<excludeFolder url="file://$MODULE_DIR$/build/intermediates/exploded-aar/com.android.support/appcompat-v7/23.2.1/jars" />
<excludeFolder url="file://$MODULE_DIR$/build/intermediates/exploded-aar/com.android.support/design/23.2.1/jars" />
<excludeFolder url="file://$MODULE_DIR$/build/intermediates/exploded-aar/com.android.support/recyclerview-v7/23.2.1/jars" />
<excludeFolder url="file://$MODULE_DIR$/build/intermediates/exploded-aar/com.android.support/support-v4/23.2.1/jars" />
<excludeFolder url="file://$MODULE_DIR$/build/intermediates/exploded-aar/com.android.support/support-vector-drawable/23.2.1/jars" />
<excludeFolder url="file://$MODULE_DIR$/build/intermediates/exploded-aar/com.journeyapps/zxing-android-embedded/3.2.0/jars" />
<excludeFolder url="file://$MODULE_DIR$/build/intermediates/incremental" />
<excludeFolder url="file://$MODULE_DIR$/build/intermediates/jacoco" />
<excludeFolder url="file://$MODULE_DIR$/build/intermediates/javaResources" />
<excludeFolder url="file://$MODULE_DIR$/build/intermediates/libs" />
<excludeFolder url="file://$MODULE_DIR$/build/intermediates/lint" />
<excludeFolder url="file://$MODULE_DIR$/build/intermediates/jniLibs" />
<excludeFolder url="file://$MODULE_DIR$/build/intermediates/manifests" />
<excludeFolder url="file://$MODULE_DIR$/build/intermediates/ndk" />
<excludeFolder url="file://$MODULE_DIR$/build/intermediates/pre-dexed" />
<excludeFolder url="file://$MODULE_DIR$/build/intermediates/proguard" />
<excludeFolder url="file://$MODULE_DIR$/build/intermediates/res" />
<excludeFolder url="file://$MODULE_DIR$/build/intermediates/rs" />
<excludeFolder url="file://$MODULE_DIR$/build/intermediates/symbols" />
<excludeFolder url="file://$MODULE_DIR$/build/intermediates/transforms" />
<excludeFolder url="file://$MODULE_DIR$/build/outputs" />
<excludeFolder url="file://$MODULE_DIR$/build/tmp" />
</content>
<orderEntry type="jdk" jdkName="Android API 23 Platform" jdkType="Android SDK" />
<orderEntry type="sourceFolder" forTests="false" />
<orderEntry type="library" exported="" name="appcompat-v7-23.0.1" level="project" />
<orderEntry type="library" exported="" name="support-v4-23.0.1" level="project" />
<orderEntry type="library" exported="" name="support-annotations-23.0.1" level="project" />
<orderEntry type="library" exported="" name="animated-vector-drawable-23.2.1" level="project" />
<orderEntry type="library" exported="" name="support-v4-23.2.1" level="project" />
<orderEntry type="library" exported="" name="recyclerview-v7-23.2.1" level="project" />
<orderEntry type="library" exported="" name="core-3.2.1" level="project" />
<orderEntry type="library" exported="" name="support-annotations-23.2.1" level="project" />
<orderEntry type="library" exported="" name="support-vector-drawable-23.2.1" level="project" />
<orderEntry type="library" exported="" name="zxing-android-embedded-3.2.0" level="project" />
<orderEntry type="library" exported="" name="design-23.2.1" level="project" />
<orderEntry type="library" exported="" name="appcompat-v7-23.2.1" level="project" />
</component>
</module>

View File

@@ -5,22 +5,33 @@ android {
buildToolsVersion "23.0.1"
defaultConfig {
applicationId "com.vsmartcard.remotesmartcardreader"
minSdkVersion 10
applicationId "com.vsmartcard.remotesmartcardreader.app"
// NFC reader mode was added in KitKat
minSdkVersion 19
targetSdkVersion 23
versionCode 3
versionName "1.2"
versionCode 4
versionName "2.0"
}
buildTypes {
release {
minifyEnabled false
proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.txt'
minifyEnabled true
proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
}
}
}
repositories {
mavenCentral()
}
dependencies {
compile fileTree(dir: 'libs', include: ['*.jar'])
compile 'com.android.support:appcompat-v7:23.0.1'
compile 'com.android.support:support-v4:23.0.1'
testCompile 'junit:junit:4.12'
compile 'com.android.support:appcompat-v7:23.2.1'
compile 'com.android.support:design:23.2.1'
compile 'com.android.support:support-v4:23.2.1'
compile 'com.journeyapps:zxing-android-embedded:3.2.0@aar'
compile 'com.google.zxing:core:3.2.1'
}

View File

@@ -1,8 +1,8 @@
# Add project specific ProGuard rules here.
# By default, the flags in this file are appended to flags specified
# in /home/fm/.local/opt/android-studio/sdk/tools/proguard/proguard-android.txt
# You can edit the include path and order by changing the ProGuard
# include property in project.properties.
# in /home/fm/.local/opt/Android/tools/proguard/proguard-android.txt
# You can edit the include path and order by changing the proguardFiles
# directive in build.gradle.
#
# For more details, see
# http://developer.android.com/guide/developing/tools/proguard.html

View File

@@ -0,0 +1,13 @@
package com.vsmartcard.remotesmartcardreader.app;
import android.app.Application;
import android.test.ApplicationTestCase;
/**
* <a href="http://d.android.com/tools/testing/testing_android.html">Testing Fundamentals</a>
*/
public class ApplicationTest extends ApplicationTestCase<Application> {
public ApplicationTest() {
super(Application.class);
}
}

View File

@@ -5,22 +5,23 @@
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.NFC" />
<uses-feature android:name="android.hardware.nfc" android:required="true" />
<uses-feature
android:name="android.hardware.nfc"
android:required="true" />
<application
android:allowBackup="true"
android:icon="@mipmap/ic_launcher"
android:label="@string/app_name"
android:supportsRtl="true"
android:theme="@style/AppTheme" >
<activity
android:name="com.vsmartcard.remotesmartcardreader.app.MainActivity"
android:launchMode="singleTask"
android:label="@string/app_name"
android:exported="true"
android:launchMode="singleTask" >
android:theme="@style/AppTheme.NoActionBar" >
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
@@ -30,30 +31,18 @@
<meta-data
android:name="android.nfc.action.TECH_DISCOVERED"
android:resource="@xml/nfc_tech_filter" />
</activity>
<activity
android:name="com.vsmartcard.remotesmartcardreader.app.SettingsActivity"
android:label="@string/title_activity_settings" >
<intent-filter>
<action android:name="android.intent.action.VIEW" />
<category android:name="android.intent.category.BROWSABLE" />
<category android:name="android.intent.category.DEFAULT" />
<data android:scheme="@string/scheme_vpcd" />
<data
android:scheme="@string/scheme_vpcd" />
</intent-filter>
<intent-filter>
<action android:name="android.intent.action.VIEW" />
<category android:name="android.intent.category.DEFAULT" />
<category android:name="android.intent.category.BROWSABLE" />
<data android:scheme="@string/scheme_http"
android:host="frankmorgner.github.io"
android:pathPattern="/vsmartcard/remote-reader/README.html" />
</intent-filter>
<intent-filter>
<action android:name="android.intent.action.VIEW" />
<category android:name="android.intent.category.DEFAULT" />
<category android:name="android.intent.category.BROWSABLE" />
<data android:scheme="@string/scheme_https"
android:host="frankmorgner.github.io"
android:pathPattern="/vsmartcard/remote-reader/README.html" />
</intent-filter>
</activity>
</application>

View File

@@ -0,0 +1,236 @@
/*
* Copyright (C) 2013 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.example.android.common.logger;
/**
* Helper class for a list (or tree) of LoggerNodes.
*
* <p>When this is set as the head of the list,
* an instance of it can function as a drop-in replacement for {@link android.util.Log}.
* Most of the methods in this class server only to map a method call in Log to its equivalent
* in LogNode.</p>
*/
public class Log {
// Grabbing the native values from Android's native logging facilities,
// to make for easy migration and interop.
public static final int NONE = -1;
public static final int VERBOSE = android.util.Log.VERBOSE;
public static final int DEBUG = android.util.Log.DEBUG;
public static final int INFO = android.util.Log.INFO;
public static final int WARN = android.util.Log.WARN;
public static final int ERROR = android.util.Log.ERROR;
public static final int ASSERT = android.util.Log.ASSERT;
// Stores the beginning of the LogNode topology.
private static LogNode mLogNode;
/**
* Returns the next LogNode in the linked list.
*/
public static LogNode getLogNode() {
return mLogNode;
}
/**
* Sets the LogNode data will be sent to.
*/
public static void setLogNode(LogNode node) {
mLogNode = node;
}
/**
* Instructs the LogNode to print the log data provided. Other LogNodes can
* be chained to the end of the LogNode as desired.
*
* @param priority Log level of the data being logged. Verbose, Error, etc.
* @param tag Tag for for the log data. Can be used to organize log statements.
* @param msg The actual message to be logged.
* @param tr If an exception was thrown, this can be sent along for the logging facilities
* to extract and print useful information.
*/
public static void println(int priority, String tag, String msg, Throwable tr) {
if (mLogNode != null) {
mLogNode.println(priority, tag, msg, tr);
}
}
/**
* Instructs the LogNode to print the log data provided. Other LogNodes can
* be chained to the end of the LogNode as desired.
*
* @param priority Log level of the data being logged. Verbose, Error, etc.
* @param tag Tag for for the log data. Can be used to organize log statements.
* @param msg The actual message to be logged. The actual message to be logged.
*/
public static void println(int priority, String tag, String msg) {
println(priority, tag, msg, null);
}
/**
* Prints a message at VERBOSE priority.
*
* @param tag Tag for for the log data. Can be used to organize log statements.
* @param msg The actual message to be logged.
* @param tr If an exception was thrown, this can be sent along for the logging facilities
* to extract and print useful information.
*/
public static void v(String tag, String msg, Throwable tr) {
println(VERBOSE, tag, msg, tr);
}
/**
* Prints a message at VERBOSE priority.
*
* @param tag Tag for for the log data. Can be used to organize log statements.
* @param msg The actual message to be logged.
*/
public static void v(String tag, String msg) {
v(tag, msg, null);
}
/**
* Prints a message at DEBUG priority.
*
* @param tag Tag for for the log data. Can be used to organize log statements.
* @param msg The actual message to be logged.
* @param tr If an exception was thrown, this can be sent along for the logging facilities
* to extract and print useful information.
*/
public static void d(String tag, String msg, Throwable tr) {
println(DEBUG, tag, msg, tr);
}
/**
* Prints a message at DEBUG priority.
*
* @param tag Tag for for the log data. Can be used to organize log statements.
* @param msg The actual message to be logged.
*/
public static void d(String tag, String msg) {
d(tag, msg, null);
}
/**
* Prints a message at INFO priority.
*
* @param tag Tag for for the log data. Can be used to organize log statements.
* @param msg The actual message to be logged.
* @param tr If an exception was thrown, this can be sent along for the logging facilities
* to extract and print useful information.
*/
public static void i(String tag, String msg, Throwable tr) {
println(INFO, tag, msg, tr);
}
/**
* Prints a message at INFO priority.
*
* @param tag Tag for for the log data. Can be used to organize log statements.
* @param msg The actual message to be logged.
*/
public static void i(String tag, String msg) {
i(tag, msg, null);
}
/**
* Prints a message at WARN priority.
*
* @param tag Tag for for the log data. Can be used to organize log statements.
* @param msg The actual message to be logged.
* @param tr If an exception was thrown, this can be sent along for the logging facilities
* to extract and print useful information.
*/
public static void w(String tag, String msg, Throwable tr) {
println(WARN, tag, msg, tr);
}
/**
* Prints a message at WARN priority.
*
* @param tag Tag for for the log data. Can be used to organize log statements.
* @param msg The actual message to be logged.
*/
public static void w(String tag, String msg) {
w(tag, msg, null);
}
/**
* Prints a message at WARN priority.
*
* @param tag Tag for for the log data. Can be used to organize log statements.
* @param tr If an exception was thrown, this can be sent along for the logging facilities
* to extract and print useful information.
*/
public static void w(String tag, Throwable tr) {
w(tag, null, tr);
}
/**
* Prints a message at ERROR priority.
*
* @param tag Tag for for the log data. Can be used to organize log statements.
* @param msg The actual message to be logged.
* @param tr If an exception was thrown, this can be sent along for the logging facilities
* to extract and print useful information.
*/
public static void e(String tag, String msg, Throwable tr) {
println(ERROR, tag, msg, tr);
}
/**
* Prints a message at ERROR priority.
*
* @param tag Tag for for the log data. Can be used to organize log statements.
* @param msg The actual message to be logged.
*/
public static void e(String tag, String msg) {
e(tag, msg, null);
}
/**
* Prints a message at ASSERT priority.
*
* @param tag Tag for for the log data. Can be used to organize log statements.
* @param msg The actual message to be logged.
* @param tr If an exception was thrown, this can be sent along for the logging facilities
* to extract and print useful information.
*/
public static void wtf(String tag, String msg, Throwable tr) {
println(ASSERT, tag, msg, tr);
}
/**
* Prints a message at ASSERT priority.
*
* @param tag Tag for for the log data. Can be used to organize log statements.
* @param msg The actual message to be logged.
*/
public static void wtf(String tag, String msg) {
wtf(tag, msg, null);
}
/**
* Prints a message at ASSERT priority.
*
* @param tag Tag for for the log data. Can be used to organize log statements.
* @param tr If an exception was thrown, this can be sent along for the logging facilities
* to extract and print useful information.
*/
public static void wtf(String tag, Throwable tr) {
wtf(tag, null, tr);
}
}

View File

@@ -0,0 +1,109 @@
/*
* Copyright 2013 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
/*
* Copyright 2013 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.example.android.common.logger;
import android.graphics.Typeface;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.text.Editable;
import android.text.TextWatcher;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ScrollView;
/**
* Simple fraggment which contains a LogView and uses is to output log data it receives
* through the LogNode interface.
*/
public class LogFragment extends Fragment {
private LogView mLogView;
private ScrollView mScrollView;
public LogFragment() {}
public View inflateViews() {
mScrollView = new ScrollView(getActivity());
ViewGroup.LayoutParams scrollParams = new ViewGroup.LayoutParams(
ViewGroup.LayoutParams.MATCH_PARENT,
ViewGroup.LayoutParams.MATCH_PARENT);
mScrollView.setLayoutParams(scrollParams);
mLogView = new LogView(getActivity());
ViewGroup.LayoutParams logParams = new ViewGroup.LayoutParams(scrollParams);
logParams.height = ViewGroup.LayoutParams.WRAP_CONTENT;
mLogView.setLayoutParams(logParams);
mLogView.setClickable(true);
mLogView.setFocusable(true);
mLogView.setTypeface(Typeface.MONOSPACE);
// Want to set padding as 16 dips, setPadding takes pixels. Hooray math!
int paddingDips = 16;
double scale = getResources().getDisplayMetrics().density;
int paddingPixels = (int) ((paddingDips * (scale)) + .5);
mLogView.setPadding(paddingPixels, paddingPixels, paddingPixels, paddingPixels);
mLogView.setCompoundDrawablePadding(paddingPixels);
mLogView.setGravity(Gravity.BOTTOM);
mLogView.setTextAppearance(getActivity(), android.R.style.TextAppearance_Holo_Medium);
mScrollView.addView(mLogView);
return mScrollView;
}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View result = inflateViews();
mLogView.addTextChangedListener(new TextWatcher() {
@Override
public void beforeTextChanged(CharSequence s, int start, int count, int after) {}
@Override
public void onTextChanged(CharSequence s, int start, int before, int count) {}
@Override
public void afterTextChanged(Editable s) {
mScrollView.fullScroll(ScrollView.FOCUS_DOWN);
}
});
return result;
}
public LogView getLogView() {
return mLogView;
}
}

View File

@@ -0,0 +1,39 @@
/*
* Copyright (C) 2012 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.example.android.common.logger;
/**
* Basic interface for a logging system that can output to one or more targets.
* Note that in addition to classes that will output these logs in some format,
* one can also implement this interface over a filter and insert that in the chain,
* such that no targets further down see certain data, or see manipulated forms of the data.
* You could, for instance, write a "ToHtmlLoggerNode" that just converted all the log data
* it received to HTML and sent it along to the next node in the chain, without printing it
* anywhere.
*/
public interface LogNode {
/**
* Instructs first LogNode in the list to print the log data provided.
* @param priority Log level of the data being logged. Verbose, Error, etc.
* @param tag Tag for for the log data. Can be used to organize log statements.
* @param msg The actual message to be logged. The actual message to be logged.
* @param tr If an exception was thrown, this can be sent along for the logging facilities
* to extract and print useful information.
*/
void println(int priority, String tag, String msg, Throwable tr);
}

View File

@@ -0,0 +1,145 @@
/*
* Copyright (C) 2013 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.example.android.common.logger;
import android.app.Activity;
import android.content.Context;
import android.util.*;
import android.widget.TextView;
/** Simple TextView which is used to output log data received through the LogNode interface.
*/
public class LogView extends TextView implements LogNode {
public LogView(Context context) {
super(context);
}
public LogView(Context context, AttributeSet attrs) {
super(context, attrs);
}
public LogView(Context context, AttributeSet attrs, int defStyle) {
super(context, attrs, defStyle);
}
/**
* Formats the log data and prints it out to the LogView.
* @param priority Log level of the data being logged. Verbose, Error, etc.
* @param tag Tag for for the log data. Can be used to organize log statements.
* @param msg The actual message to be logged. The actual message to be logged.
* @param tr If an exception was thrown, this can be sent along for the logging facilities
* to extract and print useful information.
*/
@Override
public void println(int priority, String tag, String msg, Throwable tr) {
String priorityStr = null;
// For the purposes of this View, we want to print the priority as readable text.
switch(priority) {
case android.util.Log.VERBOSE:
priorityStr = "VERBOSE";
break;
case android.util.Log.DEBUG:
priorityStr = "DEBUG";
break;
case android.util.Log.INFO:
priorityStr = "INFO";
break;
case android.util.Log.WARN:
priorityStr = "WARN";
break;
case android.util.Log.ERROR:
priorityStr = "ERROR";
break;
case android.util.Log.ASSERT:
priorityStr = "ASSERT";
break;
default:
break;
}
// Handily, the Log class has a facility for converting a stack trace into a usable string.
String exceptionStr = null;
if (tr != null) {
exceptionStr = android.util.Log.getStackTraceString(tr);
}
// Take the priority, tag, message, and exception, and concatenate as necessary
// into one usable line of text.
final StringBuilder outputBuilder = new StringBuilder();
String delimiter = "\t";
appendIfNotNull(outputBuilder, priorityStr, delimiter);
appendIfNotNull(outputBuilder, tag, delimiter);
appendIfNotNull(outputBuilder, msg, delimiter);
appendIfNotNull(outputBuilder, exceptionStr, delimiter);
// In case this was originally called from an AsyncTask or some other off-UI thread,
// make sure the update occurs within the UI thread.
((Activity) getContext()).runOnUiThread( (new Thread(new Runnable() {
@Override
public void run() {
// Display the text we just generated within the LogView.
appendToLog(outputBuilder.toString());
}
})));
if (mNext != null) {
mNext.println(priority, tag, msg, tr);
}
}
public LogNode getNext() {
return mNext;
}
public void setNext(LogNode node) {
mNext = node;
}
/** Takes a string and adds to it, with a separator, if the bit to be added isn't null. Since
* the logger takes so many arguments that might be null, this method helps cut out some of the
* agonizing tedium of writing the same 3 lines over and over.
* @param source StringBuilder containing the text to append to.
* @param addStr The String to append
* @param delimiter The String to separate the source and appended strings. A tab or comma,
* for instance.
* @return The fully concatenated String as a StringBuilder
*/
private StringBuilder appendIfNotNull(StringBuilder source, String addStr, String delimiter) {
if (addStr != null) {
if (addStr.length() == 0) {
delimiter = "";
}
return source.append(addStr).append(delimiter);
}
return source;
}
// The next LogNode in the chain.
LogNode mNext;
/** Outputs the string as a new line of log data in the LogView. */
public void appendToLog(String s) {
append("\n" + s);
}
}

View File

@@ -0,0 +1,75 @@
/*
* Copyright (C) 2012 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.example.android.common.logger;
import android.util.Log;
/**
* Helper class which wraps Android's native Log utility in the Logger interface. This way
* normal DDMS output can be one of the many targets receiving and outputting logs simultaneously.
*/
public class LogWrapper implements LogNode {
// For piping: The next node to receive Log data after this one has done its work.
private LogNode mNext;
/**
* Returns the next LogNode in the linked list.
*/
public LogNode getNext() {
return mNext;
}
/**
* Sets the LogNode data will be sent to..
*/
public void setNext(LogNode node) {
mNext = node;
}
/**
* Prints data out to the console using Android's native log mechanism.
* @param priority Log level of the data being logged. Verbose, Error, etc.
* @param tag Tag for for the log data. Can be used to organize log statements.
* @param msg The actual message to be logged. The actual message to be logged.
* @param tr If an exception was thrown, this can be sent along for the logging facilities
* to extract and print useful information.
*/
@Override
public void println(int priority, String tag, String msg, Throwable tr) {
// There actually are log methods that don't take a msg parameter. For now,
// if that's the case, just convert null to the empty string and move on.
String useMsg = msg;
if (useMsg == null) {
useMsg = "";
}
// If an exeption was provided, convert that exception to a usable string and attach
// it to the end of the msg method.
if (tr != null) {
msg += "\n" + Log.getStackTraceString(tr);
}
// This is functionally identical to Log.x(tag, useMsg);
// For instance, if priority were Log.VERBOSE, this would be the same as Log.v(tag, useMsg)
Log.println(priority, tag, useMsg);
// If this isn't the last node in the chain, move things along.
if (mNext != null) {
mNext.println(priority, tag, msg, tr);
}
}
}

View File

@@ -0,0 +1,60 @@
/*
* Copyright (C) 2013 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.example.android.common.logger;
/**
* Simple {@link LogNode} filter, removes everything except the message.
* Useful for situations like on-screen log output where you don't want a lot of metadata displayed,
* just easy-to-read message updates as they're happening.
*/
public class MessageOnlyLogFilter implements LogNode {
LogNode mNext;
/**
* Takes the "next" LogNode as a parameter, to simplify chaining.
*
* @param next The next LogNode in the pipeline.
*/
public MessageOnlyLogFilter(LogNode next) {
mNext = next;
}
public MessageOnlyLogFilter() {
}
@Override
public void println(int priority, String tag, String msg, Throwable tr) {
if (mNext != null) {
getNext().println(Log.NONE, null, msg, null);
}
}
/**
* Returns the next LogNode in the chain.
*/
public LogNode getNext() {
return mNext;
}
/**
* Sets the LogNode data will be sent to..
*/
public void setNext(LogNode node) {
mNext = node;
}
}

View File

@@ -0,0 +1,109 @@
package com.vsmartcard.remotesmartcardreader.app;
import android.content.res.Configuration;
import android.os.Bundle;
import android.preference.PreferenceActivity;
import android.support.annotation.LayoutRes;
import android.support.annotation.Nullable;
import android.support.v7.app.ActionBar;
import android.support.v7.app.AppCompatDelegate;
import android.support.v7.widget.Toolbar;
import android.view.MenuInflater;
import android.view.View;
import android.view.ViewGroup;
/**
* A {@link android.preference.PreferenceActivity} which implements and proxies the necessary calls
* to be used with AppCompat.
*/
public abstract class AppCompatPreferenceActivity extends PreferenceActivity {
private AppCompatDelegate mDelegate;
@Override
protected void onCreate(Bundle savedInstanceState) {
getDelegate().installViewFactory();
getDelegate().onCreate(savedInstanceState);
super.onCreate(savedInstanceState);
}
@Override
protected void onPostCreate(Bundle savedInstanceState) {
super.onPostCreate(savedInstanceState);
getDelegate().onPostCreate(savedInstanceState);
}
public ActionBar getSupportActionBar() {
return getDelegate().getSupportActionBar();
}
public void setSupportActionBar(@Nullable Toolbar toolbar) {
getDelegate().setSupportActionBar(toolbar);
}
@Override
public MenuInflater getMenuInflater() {
return getDelegate().getMenuInflater();
}
@Override
public void setContentView(@LayoutRes int layoutResID) {
getDelegate().setContentView(layoutResID);
}
@Override
public void setContentView(View view) {
getDelegate().setContentView(view);
}
@Override
public void setContentView(View view, ViewGroup.LayoutParams params) {
getDelegate().setContentView(view, params);
}
@Override
public void addContentView(View view, ViewGroup.LayoutParams params) {
getDelegate().addContentView(view, params);
}
@Override
protected void onPostResume() {
super.onPostResume();
getDelegate().onPostResume();
}
@Override
protected void onTitleChanged(CharSequence title, int color) {
super.onTitleChanged(title, color);
getDelegate().setTitle(title);
}
@Override
public void onConfigurationChanged(Configuration newConfig) {
super.onConfigurationChanged(newConfig);
getDelegate().onConfigurationChanged(newConfig);
}
@Override
protected void onStop() {
super.onStop();
getDelegate().onStop();
}
@Override
protected void onDestroy() {
super.onDestroy();
getDelegate().onDestroy();
}
public void invalidateOptionsMenu() {
getDelegate().invalidateOptionsMenu();
}
private AppCompatDelegate getDelegate() {
if (mDelegate == null) {
mDelegate = AppCompatDelegate.create(this, null);
}
return mDelegate;
}
}

View File

@@ -20,339 +20,210 @@
package com.vsmartcard.remotesmartcardreader.app;
import android.annotation.TargetApi;
import android.app.Activity;
import android.app.PendingIntent;
import android.content.ClipData;
import android.content.ClipboardManager;
import android.content.DialogInterface;
import android.content.Intent;
import android.net.Uri;
import android.content.SharedPreferences;
import android.content.pm.ActivityInfo;
import android.nfc.NfcAdapter;
import android.nfc.Tag;
import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import android.os.Looper;
import android.os.Message;
import android.support.annotation.NonNull;
import android.text.Editable;
import android.text.Layout;
import android.text.method.ScrollingMovementMethod;
import android.view.KeyEvent;
import android.preference.PreferenceManager;
import android.provider.Settings;
import android.support.design.widget.FloatingActionButton;
import android.support.design.widget.Snackbar;
import android.support.v7.app.AlertDialog;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.inputmethod.EditorInfo;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ProgressBar;
import android.widget.TextView;
import android.widget.Toast;
import com.vsmartcard.remotesmartcardreader.app.screaders.DummyReader;
import com.vsmartcard.remotesmartcardreader.app.screaders.NFCReader;
import com.vsmartcard.remotesmartcardreader.app.screaders.SCReader;
import com.example.android.common.logger.Log;
import com.example.android.common.logger.LogFragment;
import com.example.android.common.logger.LogWrapper;
import com.example.android.common.logger.MessageOnlyLogFilter;
import com.vsmartcard.remotesmartcardreader.app.screaders.*;
@TargetApi(Build.VERSION_CODES.KITKAT)
public class MainActivity extends Activity implements NfcAdapter.ReaderCallback {
public class MainActivity extends AppCompatActivity implements NfcAdapter.ReaderCallback {
class VPCDHandler extends Handler {
VPCDHandler(Looper looper) {
super(looper);
}
@Override
public void handleMessage(Message message) {
switch (message.what) {
case MessageSender.MESSAGE_CONNECTED:
textViewVPCDStatus.append(getResources().getString(R.string.status_connected_to)+" "+message.obj+"\n");
spinner.setVisibility(View.INVISIBLE);
updateLabels();
break;
case MessageSender.MESSAGE_DISCONNECTED:
textViewVPCDStatus.append(getResources().getString(R.string.status_disconnected)+"\n");
testing = false;
updateLabels();
break;
case MessageSender.MESSAGE_ATR:
textViewVPCDStatus.append(getResources().getString(R.string.status_atr)+": "+message.obj+"\n");
break;
case MessageSender.MESSAGE_ON:
textViewVPCDStatus.append(getResources().getString(R.string.status_on)+"\n");
break;
case MessageSender.MESSAGE_OFF:
textViewVPCDStatus.append(getResources().getString(R.string.status_off)+"\n");
break;
case MessageSender.MESSAGE_RESET:
textViewVPCDStatus.append(getResources().getString(R.string.status_reset)+"\n");
break;
case MessageSender.MESSAGE_CAPDU:
textViewVPCDStatus.append(getResources().getString(R.string.status_capdu)+": "+message.obj+"\n");
break;
case MessageSender.MESSAGE_RAPDU:
textViewVPCDStatus.append(getResources().getString(R.string.status_rapdu)+": "+message.obj+"\n");
break;
case MessageSender.MESSAGE_ERROR:
if (testing) {
textViewVPCDStatus.append(getResources().getString(R.string.status_error)+": "+message.obj+"\n");
testing = false;
vpcdDisconnect();
updateLabels();
}
break;
default:
textViewVPCDStatus.append(getResources().getString(R.string.status_unknown)+" "+Integer.toString(message.what)+"\n");
break;
}
Layout layout = textViewVPCDStatus.getLayout();
if (layout != null) {
int scrollAmount = layout.getLineTop(textViewVPCDStatus.getLineCount()) - textViewVPCDStatus.getHeight();
if (scrollAmount > 0)
textViewVPCDStatus.scrollTo(0, scrollAmount);
else
textViewVPCDStatus.scrollTo(0, 0);
}
}
}
private EditText editTextVPCDHost;
private EditText editTextVPCDPort;
private TextView textViewVPCDStatus;
private Button button;
private ProgressBar spinner;
private VPCDHandler handler;
private VPCDWorker vpcdTest;
private boolean testing;
private String hostname;
private String port;
private AlertDialog dialog;
private int oldOrientation;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
editTextVPCDHost = (EditText) findViewById(R.id.editTextHostname);
editTextVPCDPort = (EditText) findViewById(R.id.editTextPort);
textViewVPCDStatus = (TextView) findViewById(R.id.textViewLog);
textViewVPCDStatus.setMovementMethod(new ScrollingMovementMethod());
spinner = (ProgressBar) findViewById(R.id.progressBar);
button = (Button) findViewById(R.id.buttonDisConnect);
EditText.OnEditorActionListener vpcdWatcher = new EditText.OnEditorActionListener() {
FloatingActionButton fab = (FloatingActionButton) findViewById(R.id.fab);
assert fab != null;
fab.setOnClickListener(new View.OnClickListener() {
@Override
public boolean onEditorAction(TextView textView, int i, KeyEvent keyEvent) {
if (i == EditorInfo.IME_ACTION_DONE) {
editTextOnEditorDone();
return true;
public void onClick(View view) {
if (vpcdTest != null && !vpcdTest.isCancelled()) {
Snackbar.make(view, "Disconnecting from VPCD...", Snackbar.LENGTH_LONG)
.setAction("Action", null).show();
vpcdDisconnect();
} else {
Snackbar.make(view, "Testing with dummy card...", Snackbar.LENGTH_LONG)
.setAction("Action", null).show();
vpcdConnect(new DummyReader());
}
return false;
}
};
editTextVPCDHost.setOnEditorActionListener(vpcdWatcher);
editTextVPCDPort.setOnEditorActionListener(vpcdWatcher);
handler = new VPCDHandler(Looper.getMainLooper());
});
PendingIntent.getActivity(this, 0, new Intent(this, this.getClass()).addFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP), 0);
loadSettings();
updateLabels();
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
MenuInflater inflater = getMenuInflater();
inflater.inflate(R.menu.main, menu);
return super.onCreateOptionsMenu(menu);
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.menu_main, menu);
return true;
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle presses on the action bar items
switch (item.getItemId()) {
case R.id.action_copy:
// Code to Copy the content of Text View to the Clip board.
ClipboardManager clipboard = (ClipboardManager) getSystemService(CLIPBOARD_SERVICE);
ClipData clip = ClipData.newPlainText("simple text", textViewVPCDStatus.getText());
clipboard.setPrimaryClip(clip);
Toast.makeText(getApplicationContext(), "Log copied to clipboard.",
Toast.LENGTH_LONG).show();
return true;
case R.id.action_delete:
textViewVPCDStatus.setText("");
return true;
default:
return super.onOptionsItemSelected(item);
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
//noinspection SimplifiableIfStatement
if (id == R.id.action_settings) {
startActivity(new Intent(this, SettingsActivity.class));
return true;
}
return super.onOptionsItemSelected(item);
}
@Override
protected void onStart() {
super.onStart();
initializeLogging();
}
/** Create a chain of targets that will receive log data */
private void initializeLogging() {
// Wraps Android's native log framework.
LogWrapper logWrapper = new LogWrapper();
// Using Log, front-end to the logging chain, emulates android.util.log method signatures.
Log.setLogNode(logWrapper);
// Filter strips out everything except the message text.
MessageOnlyLogFilter msgFilter = new MessageOnlyLogFilter();
logWrapper.setNext(msgFilter);
// On screen logging via a fragment with a TextView.
LogFragment logFragment = (LogFragment) getSupportFragmentManager()
.findFragmentById(R.id.log_fragment);
msgFilter.setNext(logFragment.getLogView());
}
@Override
public void onPause() {
super.onPause();
vpcdDisconnect();
disableReaderMode();
}
private void enableReaderMode() {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
Bundle bundle = new Bundle();
bundle.putInt(NfcAdapter.EXTRA_READER_PRESENCE_CHECK_DELAY, NFCReader.TIMEOUT*10);
NfcAdapter.getDefaultAdapter(this).enableReaderMode(this, this,
NfcAdapter.FLAG_READER_NFC_A | NfcAdapter.FLAG_READER_NFC_B | NfcAdapter.FLAG_READER_SKIP_NDEF_CHECK,
bundle);
} else {
//NfcAdapter.enableForegroundDispatch(this, mPendingIntent, mFilters, mTechLists);
NfcAdapter adapter = NfcAdapter.getDefaultAdapter(this);
if (!adapter.isEnabled()) {
if (dialog == null) {
dialog = new AlertDialog.Builder(this)
.setMessage("NFC is required to communicate with a contactless smart card. Do you want to enable NFC now?")
.setTitle("Enable NFC")
.setPositiveButton(android.R.string.yes, new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
startActivity(new Intent(Settings.ACTION_NFC_SETTINGS));
}
})
.setNegativeButton(android.R.string.no, new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
}
}).create();
}
dialog.show();
}
// avoid re-starting the App and loosing the tag by rotating screen
oldOrientation = getRequestedOrientation();
setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_NOSENSOR);
SharedPreferences SP = PreferenceManager.getDefaultSharedPreferences(this);
int timeout = Integer.parseInt(SP.getString("delay", Integer.toString(NFCReader.TIMEOUT)));
Bundle bundle = new Bundle();
bundle.putInt(NfcAdapter.EXTRA_READER_PRESENCE_CHECK_DELAY, timeout * 10);
adapter.enableReaderMode(this, this,
NfcAdapter.FLAG_READER_NFC_A | NfcAdapter.FLAG_READER_NFC_B | NfcAdapter.FLAG_READER_SKIP_NDEF_CHECK,
bundle);
}
private void disableReaderMode() {
if (dialog != null) {
dialog.dismiss();
}
setRequestedOrientation(oldOrientation);
NfcAdapter nfc = NfcAdapter.getDefaultAdapter(this);
if (nfc != null) {
nfc.disableReaderMode(this);
}
}
@Override
public void onTagDiscovered(Tag tag) {
NFCReader nfcReader = NFCReader.get(tag);
vpcdDisconnect();
String[] techList = tag.getTechList();
for (String aTechList : techList) {
if (aTechList.equals("android.nfc.tech.NfcA")) {
Log.i(getClass().getName(), "Discovered ISO/IEC 14443-A tag");
} else if (aTechList.equals("android.nfc.tech.NfcB")) {
Log.i(getClass().getName(), "Discovered ISO/IEC 14443-B tag");
}
}
NFCReader nfcReader = NFCReader.get(tag, this);
if (nfcReader != null) {
/* avoid updating UI components since this may end up on a non ui thread */
vpcdDisconnect();
testing = true;
vpcdConnect(nfcReader);
}
}
private void disableReaderMode() {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
NfcAdapter nfc = NfcAdapter.getDefaultAdapter(this);
if (nfc != null) {
nfc.disableReaderMode(this);
}
}
}
private static final String saved_status_key = "textViewVPCDStatus";
@Override
public void onRestoreInstanceState(@NonNull Bundle savedInstanceState) {
super.onRestoreInstanceState(savedInstanceState);
textViewVPCDStatus.setText(savedInstanceState.getCharSequence(saved_status_key));
}
@Override
public void onSaveInstanceState(Bundle savedInstanceState) {
savedInstanceState.putCharSequence(saved_status_key, textViewVPCDStatus.getText());
super.onSaveInstanceState(savedInstanceState);
}
@Override
public void onPause() {
super.onPause();
testing = false;
vpcdDisconnect();
disableReaderMode();
}
public void buttonOnClickDisConnect(View view) {
if (testing) {
testing = false;
vpcdDisconnect();
} else {
saveSettings();
testing = true;
spinner.setVisibility(View.VISIBLE);
textViewVPCDStatus.append(getResources().getString(R.string.status_dummy_start)+"\n");
vpcdConnect(new DummyReader());
}
updateLabels();
}
private void editTextOnEditorDone() {
textViewVPCDStatus.append(getResources().getString(R.string.status_dummy_start)+"\n");
forceConnect(new DummyReader());
}
private void vpcdConnect(SCReader scReader) {
int p = VPCDWorker.DEFAULT_PORT;
try {
p = Integer.parseInt(port);
} catch (NumberFormatException e) {
textViewVPCDStatus.append(getResources().getString(R.string.status_default_port)+"\n");
}
vpcdTest = new VPCDWorker(hostname, p, scReader, handler);
new Thread(vpcdTest).start();
SharedPreferences SP = PreferenceManager.getDefaultSharedPreferences(this);
int port = Integer.parseInt(SP.getString("port", Integer.toString(VPCDWorker.DEFAULT_PORT)));
String hostname = SP.getString("hostname", VPCDWorker.DEFAULT_HOSTNAME);
vpcdTest = new VPCDWorker();
vpcdTest.execute(new VPCDWorker.VPCDWorkerParams(hostname, port, scReader));
}
private void vpcdDisconnect() {
if (vpcdTest != null) {
vpcdTest.close();
vpcdTest.cancel(true);
vpcdTest = null;
}
}
private void updateLabels() {
if (testing) {
button.setText(getResources().getString(R.string.button_stop_testing));
} else {
button.setText(getResources().getString(R.string.button_test_configuration));
spinner.setVisibility(View.INVISIBLE);
}
}
private void loadSettings() {
Settings settings = new Settings(this);
hostname = settings.getVPCDHost();
port = settings.getVPCDPort();
editTextVPCDHost.setText(hostname);
editTextVPCDPort.setText(port);
}
private void saveSettings() {
Editable textHostname = editTextVPCDHost.getText();
Editable textPort = editTextVPCDPort.getText();
if (textHostname != null) {
hostname = textHostname.toString();
}
if (textPort != null) {
port = textPort.toString();
}
Settings settings = new Settings(this);
settings.setVPCDSettings(hostname, port);
}
private void forceConnect(SCReader scReader) {
if (testing) {
testing = false;
vpcdDisconnect();
}
saveSettings();
testing = true;
spinner.setVisibility(View.VISIBLE);
vpcdConnect(scReader);
updateLabels();
}
@Override
public void onResume() {
super.onResume();
Intent intent = getIntent();
// Check to see that the Activity started due to a discovered tag
if (NfcAdapter.ACTION_TECH_DISCOVERED.equals(intent.getAction())) {
NFCReader nfcReader = NFCReader.get(intent);
vpcdDisconnect();
NFCReader nfcReader = NFCReader.get(intent, this);
if (nfcReader != null) {
forceConnect(nfcReader);
vpcdConnect(nfcReader);
} else {
super.onNewIntent(intent);
}
} else {
// Check to see that the Activity started due to a configuration URI
if (Intent.ACTION_VIEW.equals(intent.getAction())) {
testing = false;
vpcdDisconnect();
Uri uri = intent.getData();
String h = "";
String p = "";
if (uri.getScheme().equals(getResources().getString(R.string.scheme_vpcd))) {
h = uri.getHost();
int _p = uri.getPort();
if (_p > 0) {
p = Integer.toString(_p);
}
} else {
h = uri.getQueryParameter("host");
p = uri.getQueryParameter("port");
}
editTextVPCDHost.setText(h);
editTextVPCDPort.setText(p);
super.onNewIntent(intent);
}
}
enableReaderMode();
}
@@ -362,4 +233,5 @@ public class MainActivity extends Activity implements NfcAdapter.ReaderCallback
// onResume gets called after this to handle the intent
setIntent(intent);
}
}

View File

@@ -1,81 +0,0 @@
/*
* Copyright (C) 2014 Frank Morgner
*
* This file is part of RemoteSmartCardReader.
*
* RemoteSmartCardReader is free software: you can redistribute it and/or
* modify it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or (at your
* option) any later version.
*
* RemoteSmartCardReader is distributed in the hope that it will be useful, but
* WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY
* or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for
* more details.
*
* You should have received a copy of the GNU General Public License along with
* RemoteSmartCardReader. If not, see <http://www.gnu.org/licenses/>.
*/
package com.vsmartcard.remotesmartcardreader.app;
import android.os.Handler;
import android.os.Message;
class MessageSender {
public static final int MESSAGE_CONNECTED = 0;
public static final int MESSAGE_DISCONNECTED = 1;
public static final int MESSAGE_ERROR = 2;
public static final int MESSAGE_ATR = 3;
public static final int MESSAGE_ON = 4;
public static final int MESSAGE_OFF = 5;
public static final int MESSAGE_RESET = 6;
public static final int MESSAGE_CAPDU = 7;
public static final int MESSAGE_RAPDU = 8;
private final Handler handler;
public MessageSender(Handler handler) {
this.handler = handler;
}
private void sendMessage(int messageCode, Object object) {
Message message = handler.obtainMessage(messageCode, object);
handler.sendMessage(message);
}
public void sendConnected(String details) {
sendMessage(MESSAGE_CONNECTED, details);
}
public void sendATR(String details) {
sendMessage(MESSAGE_ATR, details);
}
public void sendCAPDU(String details) {
sendMessage(MESSAGE_CAPDU, details);
}
public void sendDisconnected(String details) {
sendMessage(MESSAGE_DISCONNECTED, "");
}
public void sendError(String details) {
sendMessage(MESSAGE_ERROR, details);
}
public void sendOff() {
sendMessage(MESSAGE_OFF, "");
}
public void sendOn() {
sendMessage(MESSAGE_ON, "");
}
public void sendRAPDU(String details) {
sendMessage(MESSAGE_RAPDU, details);
}
public void sendReset() {
sendMessage(MESSAGE_RESET, "");
}
}

View File

@@ -0,0 +1,80 @@
/*
* Copyright (C) 2014 Frank Morgner
*
* This file is part of RemoteSmartCardReader.
*
* RemoteSmartCardReader is free software: you can redistribute it and/or
* modify it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or (at your
* option) any later version.
*
* RemoteSmartCardReader is distributed in the hope that it will be useful, but
* WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY
* or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for
* more details.
*
* You should have received a copy of the GNU General Public License along with
* RemoteSmartCardReader. If not, see <http://www.gnu.org/licenses/>.
*/
package com.vsmartcard.remotesmartcardreader.app;
import android.content.ClipData;
import android.content.ClipboardManager;
import android.content.Context;
import android.os.Bundle;
import android.support.design.widget.Snackbar;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import com.example.android.common.logger.LogFragment;
public class MyLogFragment extends LogFragment {
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setHasOptionsMenu(true);
}
@Override
public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) {
// TODO Add your menu entries here
getActivity().getMenuInflater().inflate(R.menu.menu_log, menu);
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle presses on the action bar items
switch (item.getItemId()) {
case R.id.action_copy:
// Code to Copy the content of Text View to the Clip board.
ClipboardManager clipboard = (ClipboardManager) getActivity().getSystemService(Context.CLIPBOARD_SERVICE);
ClipData clip = ClipData.newPlainText("simple text", getLogView().getText());
clipboard.setPrimaryClip(clip);
Snackbar.make(getView(), "Log copied to clipboard.", Snackbar.LENGTH_LONG)
.setAction("Action", null).show();
return true;
case R.id.action_delete:
getLogView().setText("");
return true;
default:
return super.onOptionsItemSelected(item);
}
}
@Override
public void onActivityCreated(Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
if (savedInstanceState != null) {
getLogView().setText(savedInstanceState.getCharSequence("logView"));
}
}
@Override
public void onSaveInstanceState(Bundle savedInstanceState) {
savedInstanceState.putCharSequence("logView", getLogView().getText());
super.onSaveInstanceState(savedInstanceState);
}
}

View File

@@ -1,67 +0,0 @@
/*
* Copyright (C) 2014 Frank Morgner
*
* This file is part of RemoteSmartCardReader.
*
* RemoteSmartCardReader is free software: you can redistribute it and/or
* modify it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or (at your
* option) any later version.
*
* RemoteSmartCardReader is distributed in the hope that it will be useful, but
* WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY
* or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for
* more details.
*
* You should have received a copy of the GNU General Public License along with
* RemoteSmartCardReader. If not, see <http://www.gnu.org/licenses/>.
*/
package com.vsmartcard.remotesmartcardreader.app;
import android.content.Context;
import android.content.SharedPreferences;
import android.content.SharedPreferences.Editor;
import android.preference.PreferenceManager;
class Settings {
private static final String KEY_VPCD_HOST = "hostname";
private static final String KEY_VPCD_PORT = "port";
private static final String DEFAULT_VPCD_HOST = "10.0.2.2";
private static final String DEFAULT_VPCD_PORT = "35963";
private final SharedPreferences settings;
public Settings (Context activity) {
settings = PreferenceManager.getDefaultSharedPreferences(activity);
}
private void setString(String key, String value) {
Editor editor = settings.edit();
editor.putString(key, value);
editor.apply();
}
// private void setBoolean(String key, boolean value) {
// Editor editor = settings.edit();
// editor.putBoolean(key, value);
// editor.apply();
// }
public void setVPCDSettings(String hostname, String port) {
Editor editor = settings.edit();
editor.putString(KEY_VPCD_HOST, hostname);
editor.putString(KEY_VPCD_PORT, port);
editor.apply();
}
public String getVPCDHost() {
return settings.getString(KEY_VPCD_HOST, DEFAULT_VPCD_HOST);
}
public String getVPCDPort() {
return settings.getString(KEY_VPCD_PORT, DEFAULT_VPCD_PORT);
}
}

View File

@@ -0,0 +1,247 @@
/*
* Copyright (C) 2014 Frank Morgner
*
* This file is part of RemoteSmartCardReader.
*
* RemoteSmartCardReader is free software: you can redistribute it and/or
* modify it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or (at your
* option) any later version.
*
* RemoteSmartCardReader is distributed in the hope that it will be useful, but
* WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY
* or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for
* more details.
*
* You should have received a copy of the GNU General Public License along with
* RemoteSmartCardReader. If not, see <http://www.gnu.org/licenses/>.
*/
package com.vsmartcard.remotesmartcardreader.app;
import android.annotation.TargetApi;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.res.Configuration;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.preference.ListPreference;
import android.preference.Preference;
import android.preference.PreferenceActivity;
import android.provider.Settings;
import android.support.design.widget.Snackbar;
import android.support.v7.app.ActionBar;
import android.preference.PreferenceFragment;
import android.preference.PreferenceManager;
import android.view.MenuItem;
import com.google.zxing.integration.android.IntentIntegrator;
import com.google.zxing.integration.android.IntentResult;
/**
* A {@link PreferenceActivity} that presents a set of application settings. On
* handset devices, settings are presented as a single list. On tablets,
* settings are split by category, with category headers shown to the left of
* the list of settings.
* <p>
* See <a href="http://developer.android.com/design/patterns/settings.html">
* Android Design: Settings</a> for design guidelines and the <a
* href="http://developer.android.com/guide/topics/ui/settings.html">Settings
* API Guide</a> for more information on developing a Settings UI.
*/
public class SettingsActivity extends AppCompatPreferenceActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setupActionBar();
// Display the fragment as the main content.
getFragmentManager().beginTransaction().replace(android.R.id.content,
new VPCDPreferenceFragment()).commit();
}
/**
* Set up the {@link android.app.ActionBar}, if the API is available.
*/
private void setupActionBar() {
ActionBar actionBar = getSupportActionBar();
if (actionBar != null) {
// Show the Up button in the action bar.
actionBar.setDisplayHomeAsUpEnabled(true);
}
}
/** {@inheritDoc} */
@Override
public boolean onIsMultiPane() {
return isXLargeTablet(this);
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
int id = item.getItemId();
if (id == android.R.id.home) {
finish();
return true;
}
return super.onOptionsItemSelected(item);
}
/**
* Helper method to determine if the device has an extra-large screen. For
* example, 10" tablets are extra-large.
*/
private static boolean isXLargeTablet(Context context) {
return (context.getResources().getConfiguration().screenLayout
& Configuration.SCREENLAYOUT_SIZE_MASK) >= Configuration.SCREENLAYOUT_SIZE_XLARGE;
}
/**
* A settings value change listener that updates the settings's summary
* to reflect its new value.
*/
private static final Preference.OnPreferenceChangeListener sBindPreferenceSummaryToValueListener = new Preference.OnPreferenceChangeListener() {
@Override
public boolean onPreferenceChange(Preference preference, Object value) {
String stringValue = value.toString();
if (preference instanceof ListPreference) {
// For list preferences, look up the correct display value in
// the settings's 'entries' list.
ListPreference listPreference = (ListPreference) preference;
int index = listPreference.findIndexOfValue(stringValue);
// Set the summary to reflect the new value.
preference.setSummary(
index >= 0
? listPreference.getEntries()[index]
: null);
} else {
// For all other preferences, set the summary to the value's
// simple string representation.
preference.setSummary(stringValue);
}
return true;
}
};
/**
* Binds a settings's summary to its value. More specifically, when the
* settings's value is changed, its summary (line of text below the
* settings title) is updated to reflect the value. The summary is also
* immediately updated upon calling this method. The exact display format is
* dependent on the type of settings.
*
* @see #sBindPreferenceSummaryToValueListener
*/
private static void bindPreferenceSummaryToValue(Preference preference) {
// Set the listener to watch for value changes.
preference.setOnPreferenceChangeListener(sBindPreferenceSummaryToValueListener);
// Trigger the listener immediately with the settings's
// current value.
sBindPreferenceSummaryToValueListener.onPreferenceChange(preference,
PreferenceManager
.getDefaultSharedPreferences(preference.getContext())
.getString(preference.getKey(), ""));
}
/**
* This fragment shows data and sync preferences only. It is used when the
* activity is showing a two-pane settings UI.
*/
@TargetApi(Build.VERSION_CODES.HONEYCOMB)
public static class VPCDPreferenceFragment extends PreferenceFragment {
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
addPreferencesFromResource(R.xml.settings);
setHasOptionsMenu(true);
// Bind the summaries of EditText/List/Dialog/Ringtone preferences
// to their values. When their values change, their summaries are
// updated to reflect the new value, per the Android Design
// guidelines.
bindPreferenceSummaryToValue(findPreference("hostname"));
bindPreferenceSummaryToValue(findPreference("port"));
bindPreferenceSummaryToValue(findPreference("delay"));
Preference nfcSettings = findPreference("nfcSettings");
nfcSettings.setOnPreferenceClickListener(new Preference.OnPreferenceClickListener() {
public boolean onPreferenceClick(Preference preference) {
Intent viewIntent = new Intent(Settings.ACTION_NFC_SETTINGS);
startActivity(viewIntent);
return true;
}
});
Preference scan = findPreference("scan");
scan.setOnPreferenceClickListener(new Preference.OnPreferenceClickListener() {
public boolean onPreferenceClick(Preference preference) {
new IntentIntegrator(getActivity()).initiateScan();
return true;
}
});
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
int id = item.getItemId();
if (id == android.R.id.home) {
startActivity(new Intent(getActivity(), SettingsActivity.class));
return true;
}
return super.onOptionsItemSelected(item);
}
}
public void onActivityResult(int requestCode, int resultCode, Intent intent) {
IntentResult scanResult = IntentIntegrator.parseActivityResult(requestCode, resultCode, intent);
switch(requestCode) {
case IntentIntegrator.REQUEST_CODE:
if (resultCode != RESULT_CANCELED) {
handleScannedURI(Uri.parse(scanResult.getContents()));
}
break;
}
}
private void handleScannedURI(Uri uri) {
try {
String h, p;
h = uri.getHost();
int _p = uri.getPort();
if (_p < 0) {
_p = VPCDWorker.DEFAULT_PORT;
}
p = Integer.toString(_p);
SharedPreferences SP = PreferenceManager.getDefaultSharedPreferences(this);
SP.edit().putString("hostname", h).apply();
SP.edit().putString("port", p).apply();
} catch (Exception e) {
Snackbar.make(this.getCurrentFocus(), "Could not import configuration", Snackbar.LENGTH_LONG)
.setAction("Action", null).show();
}
}
@Override
public void onResume() {
super.onResume();
Intent intent = getIntent();
// Check to see that the Activity started due to a configuration URI
if (Intent.ACTION_VIEW.equals(intent.getAction())) {
Uri uri = intent.getData();
handleScannedURI(uri);
super.onNewIntent(intent);
}
}
@Override
public void onNewIntent(Intent intent) {
// onResume gets called after this to handle the intent
setIntent(intent);
}
}

View File

@@ -19,39 +19,46 @@
package com.vsmartcard.remotesmartcardreader.app;
import android.os.Handler;
import android.os.AsyncTask;
import android.support.annotation.Nullable;
import com.example.android.common.logger.Log;
import com.vsmartcard.remotesmartcardreader.app.screaders.SCReader;
import java.io.Closeable;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.InetAddress;
import java.net.Socket;
class VPCDWorker implements Runnable, Closeable {
class VPCDWorker extends AsyncTask<VPCDWorker.VPCDWorkerParams, Void, Void> {
public static class VPCDWorkerParams {
final String hostname;
final int port;
final SCReader reader;
VPCDWorkerParams(String hostname, int port, SCReader reader) {
this.hostname = hostname;
this.port = port;
this.reader = reader;
}
}
public static final int DEFAULT_PORT = 35963;
private final int port;
private final String hostname;
private final SCReader reader;
// default URI when used in emulator
public static final String DEFAULT_HOSTNAME = "10.0.2.2";
private SCReader reader;
private Socket socket;
private InputStream inputStream;
private OutputStream outputStream;
private boolean doRun;
private final MessageSender messageSender;
public VPCDWorker(String hostname, int port, SCReader reader, Handler handler) {
this.hostname = hostname;
this.port = port;
this.reader = reader;
this.messageSender = new MessageSender(handler);
}
public void close() {
doRun = false;
@Override
protected void onCancelled () {
try {
vpcdDisconnect();
if (socket != null)
// interrupt all blocking socket communication
socket.close();
} catch (IOException e) {
e.printStackTrace();
}
@@ -64,36 +71,32 @@ class VPCDWorker implements Runnable, Closeable {
private static final byte VPCD_CTRL_ATR = 4;
@Override
public void run() {
android.os.Process.setThreadPriority(android.os.Process.THREAD_PRIORITY_BACKGROUND);
doRun = true;
public Void doInBackground(VPCDWorkerParams... params) {
try {
vpcdConnect();
messageSender.sendConnected(hostname+":"+Integer.toString(port));
reader = params[0].reader;
Log.i(this.getClass().getName(), "Connecting to " + params[0].hostname + ":" + Integer.toString(params[0].port) + "...");
vpcdConnect(params[0].hostname, params[0].port);
Log.i(this.getClass().getName(), "Connected to VPCD");
while (doRun) {
byte[] in = receiveFromVPCD();
if (in == null) {
doRun = false;
break;
}
while (!isCancelled()) {
byte[] out = null;
byte[] in = receiveFromVPCD();
if (in == null)
break;
if (in.length == VPCD_CTRL_LEN) {
switch (in[0]) {
case VPCD_CTRL_OFF:
reader.powerOff();
messageSender.sendOff();
Log.i(this.getClass().getName(), "Powered down the card (cold reset)");
break;
case VPCD_CTRL_ON:
reader.powerOn();
messageSender.sendOn();
messageSender.sendATR(Hex.getHexString(reader.getATR()));
Log.i(this.getClass().getName(), "Powered up the card with ATR " + Hex.getHexString(reader.getATR()));
break;
case VPCD_CTRL_RESET:
reader.reset();
messageSender.sendReset();
Log.i(this.getClass().getName(), "Resetted the card (warm reset)");
break;
case VPCD_CTRL_ATR:
out = reader.getATR();
@@ -102,22 +105,29 @@ class VPCDWorker implements Runnable, Closeable {
throw new IOException("Unhandled command from VPCD.");
}
} else {
messageSender.sendCAPDU(Hex.getHexString(in));
Log.i(this.getClass().getName(), "C-APDU: " + Hex.getHexString(in));
out = reader.transmit(in);
messageSender.sendRAPDU(Hex.getHexString(out));
Log.i(this.getClass().getName(), "R-APDU: " + Hex.getHexString(out));
}
if (out != null) {
sendToVPCD(out);
}
}
} catch (Exception e) {
if (doRun) {
if (!isCancelled()) {
e.printStackTrace();
messageSender.sendError(e.getMessage());
Log.i(this.getClass().getName(), "ERROR: " + e.getMessage());
}
}
try {
vpcdDisconnect();
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
@Nullable
private byte[] receiveFromVPCD() throws IOException {
/* convert length from network byte order.
Note that Java always uses network byte order internally. */
@@ -158,7 +168,7 @@ class VPCDWorker implements Runnable, Closeable {
outputStream.flush();
}
private void vpcdConnect() throws IOException {
private void vpcdConnect(String hostname, int port) throws IOException {
socket = new Socket(InetAddress.getByName(hostname), port);
outputStream = socket.getOutputStream();
inputStream = socket.getInputStream();
@@ -170,7 +180,7 @@ class VPCDWorker implements Runnable, Closeable {
}
if (socket != null) {
socket.close();
messageSender.sendDisconnected("");
Log.i(this.getClass().getName(), "Disconnected from VPCD");
}
}
}

View File

@@ -19,12 +19,16 @@
package com.vsmartcard.remotesmartcardreader.app.screaders;
import android.app.Activity;
import android.content.Intent;
import android.nfc.NfcAdapter;
import android.nfc.Tag;
import android.nfc.tech.IsoDep;
import android.os.Build;
import android.os.Handler;
import android.os.Looper;
import android.util.Log;
import android.view.WindowManager;
import com.vsmartcard.remotesmartcardreader.app.Hex;
@@ -33,19 +37,51 @@ import java.io.IOException;
public class NFCReader implements SCReader {
private final IsoDep card;
private Activity activity;
private NFCReader(IsoDep sc) throws IOException {
private NFCReader(IsoDep sc, Activity activity) throws IOException {
this.card = sc;
sc.connect();
card.setTimeout(TIMEOUT);
this.activity = activity;
avoidScreenTimeout();
}
private void avoidScreenTimeout() {
if (activity != null) {
final Runnable run = new Runnable() {
public void run() {
// avoid tag loss due to screen timeout
activity.getWindow().addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);
Log.i(this.getClass().getName(), "Disabled screen timeout");
}
};
final Handler handler = new Handler(Looper.getMainLooper());
handler.post(run);
}
}
private void resetScreenTimeout() {
if (activity != null) {
final Runnable run = new Runnable() {
public void run() {
// reset screen properties
activity.getWindow().clearFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);
Log.i(this.getClass().getName(), "Activated screen timeout");
}
};
final Handler handler = new Handler(Looper.getMainLooper());
handler.post(run);
}
}
@Override
public void eject() throws IOException {
card.close();
resetScreenTimeout();
}
public static final int TIMEOUT = 2500;
public static final int TIMEOUT = 500;
@Override
public void powerOn() {
/* should already be connected... */
@@ -72,7 +108,12 @@ public class NFCReader implements SCReader {
/* calculation based on https://code.google.com/p/ifdnfc/source/browse/src/atr.c */
@Override
public byte[] getATR() {
// get historical bytes for 14443-A
byte[] historicalBytes = card.getHistoricalBytes();
if (historicalBytes == null) {
// get historical bytes for 14443-B
historicalBytes = card.getHiLayerResponse();
}
if (historicalBytes == null) {
historicalBytes = new byte[0];
}
@@ -100,7 +141,7 @@ public class NFCReader implements SCReader {
return card.transceive(apdu);
}
public static NFCReader get(Intent intent) {
public static NFCReader get(Intent intent, Activity activity) {
NFCReader nfcReader = null;
if (intent.getExtras() != null) {
@@ -114,7 +155,7 @@ public class NFCReader implements SCReader {
e.printStackTrace();
}
} else {
nfcReader = NFCReader.get(tag);
nfcReader = NFCReader.get(tag, activity);
}
intent.removeExtra(NfcAdapter.EXTRA_TAG);
}
@@ -123,10 +164,10 @@ public class NFCReader implements SCReader {
return nfcReader;
}
public static NFCReader get(Tag tag) {
public static NFCReader get(Tag tag, Activity activity) {
NFCReader nfcReader = null;
try {
nfcReader = new NFCReader(IsoDep.get(tag));
nfcReader = new NFCReader(IsoDep.get(tag), activity);
} catch (IOException e) {
e.printStackTrace();
}

Binary file not shown.

Before

Width:  |  Height:  |  Size: 375 B

Binary file not shown.

Before

Width:  |  Height:  |  Size: 3.0 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 284 B

Binary file not shown.

Before

Width:  |  Height:  |  Size: 2.9 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 351 B

Binary file not shown.

Before

Width:  |  Height:  |  Size: 3.1 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 464 B

View File

@@ -1,80 +0,0 @@
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:paddingLeft="@dimen/activity_horizontal_margin"
android:paddingRight="@dimen/activity_horizontal_margin"
android:paddingTop="@dimen/activity_vertical_margin"
android:paddingBottom="@dimen/activity_vertical_margin"
android:keepScreenOn="true"
tools:context="com.vsmartcard.remotesmartcardreader.app.MainActivity">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textAppearance="?android:attr/textAppearanceSmall"
android:text="@string/vpcd_config_info"
android:id="@+id/textViewInfo"
android:layout_alignParentLeft="true"
android:layout_alignParentStart="true"
android:layout_alignParentTop="true"
android:layout_toLeftOf="@+id/buttonDisConnect" />
<EditText
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="@+id/editTextHostname"
android:hint="@string/hint_vpcd_hostname"
android:inputType="textUri"
android:layout_below="@+id/textViewInfo"
android:layout_alignParentLeft="true"
android:layout_alignParentStart="true"
android:layout_toLeftOf="@+id/editTextPort" />
<EditText
android:layout_width="100dp"
android:layout_height="wrap_content"
android:inputType="number"
android:ems="10"
android:id="@+id/editTextPort"
android:hint="@string/hint_vpcd_port"
android:layout_below="@+id/textViewInfo"
android:layout_toLeftOf="@+id/buttonDisConnect" />
<Button
android:layout_width="160dp"
android:layout_height="wrap_content"
android:id="@+id/buttonDisConnect"
android:onClick="buttonOnClickDisConnect"
android:layout_alignParentTop="true"
android:layout_alignParentRight="true"
android:layout_alignParentEnd="true" />
<ProgressBar
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="@+id/progressBar"
android:layout_below="@+id/buttonDisConnect"
android:layout_alignRight="@+id/buttonDisConnect"
android:layout_alignEnd="@+id/buttonDisConnect" />
<HorizontalScrollView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentRight="true"
android:layout_alignParentEnd="true"
android:layout_alignParentBottom="true"
android:layout_alignParentLeft="true"
android:layout_alignParentStart="true"
android:layout_below="@+id/editTextHostname" >
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textAppearance="?android:attr/textAppearanceSmall"
android:id="@+id/textViewLog"
android:typeface="monospace" />
</HorizontalScrollView>
</RelativeLayout>

View File

@@ -1,80 +1,46 @@
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
<?xml version="1.0" encoding="utf-8"?>
<android.support.design.widget.CoordinatorLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:paddingLeft="@dimen/activity_horizontal_margin"
android:paddingRight="@dimen/activity_horizontal_margin"
android:paddingTop="@dimen/activity_vertical_margin"
android:paddingBottom="@dimen/activity_vertical_margin"
android:keepScreenOn="true"
android:fitsSystemWindows="true"
tools:context="com.vsmartcard.remotesmartcardreader.app.MainActivity">
<TextView
<android.support.design.widget.AppBarLayout
android:id="@+id/app_bar"
android:layout_width="match_parent"
android:layout_height="@dimen/app_bar_height"
android:fitsSystemWindows="true"
android:theme="@style/AppTheme.AppBarOverlay">
<android.support.design.widget.CollapsingToolbarLayout
android:id="@+id/toolbar_layout"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:fitsSystemWindows="true"
app:contentScrim="?attr/colorPrimary"
app:layout_scrollFlags="scroll|exitUntilCollapsed">
<android.support.v7.widget.Toolbar
android:id="@+id/toolbar"
android:layout_width="match_parent"
android:layout_height="?attr/actionBarSize"
app:layout_collapseMode="pin"
app:popupTheme="@style/AppTheme.PopupOverlay" />
</android.support.design.widget.CollapsingToolbarLayout>
</android.support.design.widget.AppBarLayout>
<include layout="@layout/content_main" />
<android.support.design.widget.FloatingActionButton
android:id="@+id/fab"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textAppearance="?android:attr/textAppearanceSmall"
android:scrollHorizontally="true"
android:text="@string/vpcd_config_info"
android:id="@+id/textViewInfo"
android:layout_alignParentTop="true"
android:layout_alignParentLeft="true"
android:layout_alignParentStart="true" />
android:layout_margin="@dimen/fab_margin"
android:src="@mipmap/ic_connect"
app:layout_anchor="@id/app_bar"
app:layout_anchorGravity="bottom|end" />
<EditText
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="@+id/editTextHostname"
android:layout_below="@+id/textViewInfo"
android:layout_alignParentLeft="true"
android:layout_alignParentStart="true"
android:hint="@string/hint_vpcd_hostname"
android:inputType="textUri"
android:layout_toLeftOf="@+id/editTextPort" />
<EditText
android:layout_width="80dp"
android:layout_height="wrap_content"
android:inputType="number"
android:ems="10"
android:id="@+id/editTextPort"
android:hint="@string/hint_vpcd_port"
android:layout_below="@+id/textViewInfo"
android:layout_alignRight="@+id/textViewInfo"
android:layout_alignEnd="@+id/textViewInfo" />
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="@+id/buttonDisConnect"
android:onClick="buttonOnClickDisConnect"
android:layout_below="@+id/editTextPort"
android:layout_alignParentLeft="true"
android:layout_alignParentStart="true"
android:layout_toLeftOf="@+id/progressBar" />
<ProgressBar
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="@+id/progressBar"
android:layout_alignParentRight="true"
android:layout_alignParentEnd="true"
android:layout_alignTop="@+id/buttonDisConnect" />
<HorizontalScrollView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentBottom="true"
android:layout_alignParentRight="true"
android:layout_alignParentEnd="true"
android:layout_alignParentLeft="true"
android:layout_alignParentStart="true"
android:layout_below="@+id/buttonDisConnect" >
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textAppearance="?android:attr/textAppearanceSmall"
android:id="@+id/textViewLog"
android:typeface="monospace" />
</HorizontalScrollView>
</RelativeLayout>
</android.support.design.widget.CoordinatorLayout>

View File

@@ -0,0 +1,19 @@
<?xml version="1.0" encoding="utf-8"?>
<android.support.v4.widget.NestedScrollView xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
app:layout_behavior="@string/appbar_scrolling_view_behavior"
tools:context="com.vsmartcard.remotesmartcardreader.app.MainActivity"
tools:showIn="@layout/activity_main">
<fragment
xmlns:android="http://schemas.android.com/apk/res/android"
android:name="com.vsmartcard.remotesmartcardreader.app.remotesmartcardreader.MyLogFragment"
android:id="@+id/log_fragment"
android:layout_margin="@dimen/text_margin"
android:layout_width="match_parent"
android:layout_height="match_parent" />
</android.support.v4.widget.NestedScrollView>

View File

@@ -1,16 +1,13 @@
<menu xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
tools:context="com.vsmartcard.remotesmartcardreader.app.MainActivity" >
tools:context="com.vsmartcard.remotesmartcardreader.app.MainActivity">
<item android:id="@+id/action_copy"
android:title="@string/action_copy"
android:icon="@drawable/ic_action_copy"
app:showAsAction="ifRoom" />
app:showAsAction="never" />
<item android:id="@+id/action_delete"
android:title="@string/action_delete"
android:icon="@drawable/ic_action_delete"
app:showAsAction="ifRoom" />
app:showAsAction="never" />
</menu>

View File

@@ -0,0 +1,11 @@
<menu xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
tools:context="com.vsmartcard.remotesmartcardreader.app.MainActivity">
<item
android:id="@+id/action_settings"
android:orderInCategory="100"
android:title="@string/action_settings"
app:showAsAction="never" />
</menu>

Binary file not shown.

After

Width:  |  Height:  |  Size: 1.1 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 703 B

Binary file not shown.

After

Width:  |  Height:  |  Size: 1.5 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 2.3 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 3.3 KiB

View File

@@ -0,0 +1,9 @@
<resources>>
<style name="AppTheme.NoActionBar">
<item name="windowActionBar">false</item>
<item name="windowNoTitle">true</item>
<item name="android:windowDrawsSystemBarBackgrounds">true</item>
<item name="android:statusBarColor">@android:color/transparent</item>
</style>
</resources>

View File

@@ -0,0 +1,6 @@
<?xml version="1.0" encoding="utf-8"?>
<resources>
<color name="colorPrimary">#3F51B5</color>
<color name="colorPrimaryDark">#303F9F</color>
<color name="colorAccent">#fdd017</color>
</resources>

View File

@@ -1,6 +1,5 @@
<resources>
<!-- Default screen margins, per the Android Design guidelines. -->
<dimen name="activity_horizontal_margin">16dp</dimen>
<dimen name="activity_vertical_margin">16dp</dimen>
</resources>
<dimen name="app_bar_height">180dp</dimen>
<dimen name="fab_margin">16dp</dimen>
<dimen name="text_margin">16dp</dimen>
</resources>

View File

@@ -1,34 +1,31 @@
<?xml version="1.0" encoding="utf-8"?>
<resources>
<string name="app_name">Smart Card Reader</string>
<string name="app_name">Remote Smart Card Reader</string>
<string name="scheme_vpcd">vpcd</string>
<string name="button_test_configuration">Connect</string>
<string name="button_stop_testing">Disconnect</string>
<string name="hint_vpcd_port">VPCD Port</string>
<string name="hint_vpcd_hostname">VPCD Hostname</string>
<string name="hint_vpcd_port">port</string>
<string name="hint_vpcd_hostname">VPCD hostname</string>
<string name="vpcd_config_info">Settings for <a href="http://frankmorgner.github.io/vsmartcard/virtualsmartcard/README.html">remote smart card reader driver (VPCD)</a> of the host computer. Tap a contact-less card when configured.</string>
<string name="status_error">Error</string>
<string name="status_disconnected">Disconnected from VPCD</string>
<string name="status_connected_to">Connected to</string>
<string name="status_atr">ATR</string>
<string name="status_capdu">C-APDU</string>
<string name="status_rapdu">R-APDU</string>
<string name="status_on">Powered up the card</string>
<string name="status_off">Powered down the card (cold reset)</string>
<string name="status_reset">Resetted the card (warm reset)</string>
<string name="status_unknown">Unable to perform unknown Event</string>
<string name="status_dummy_start">Using a dummy card to test the connection</string>
<string name="status_default_port">Using default port</string>
<string name="vpcd_config_info">This app connects to the virtual smart card reader driver (VPCD) via the network. You need to install VPCD on your computer and configure the connection parameters here accordingly.</string>
<string-array name="strDelays">
<item>125 milliseconds</item>
<item>250 milliseconds</item>
<item>500 milliseconds</item>
<item>1 second</item>
<item>2 seconds</item>
</string-array>
<string-array name="intDelays">
<item>125</item>
<item>250</item>
<item>500</item>
<item>1000</item>
<item>2000</item>
</string-array>
<string name="action_settings">Settings</string>
<string name="action_copy">Copy Log</string>
<string name="action_delete">Clear Log</string>
<string name="scheme_http">http</string>
<string name="scheme_https">https</string>
<string name="scheme_vpcd">vpcd</string>
<string name="title_activity_settings">Settings</string>
</resources>

View File

@@ -3,6 +3,18 @@
<!-- Base application theme. -->
<style name="AppTheme" parent="Theme.AppCompat.Light.DarkActionBar">
<!-- Customize your theme here. -->
<item name="colorPrimary">@color/colorPrimary</item>
<item name="colorPrimaryDark">@color/colorPrimaryDark</item>
<item name="colorAccent">@color/colorAccent</item>
</style>
<style name="AppTheme.NoActionBar">
<item name="windowActionBar">false</item>
<item name="windowNoTitle">true</item>
</style>
<style name="AppTheme.AppBarOverlay" parent="ThemeOverlay.AppCompat.Dark.ActionBar" />
<style name="AppTheme.PopupOverlay" parent="ThemeOverlay.AppCompat.Light" />
</resources>

View File

@@ -0,0 +1,55 @@
<?xml version="1.0" encoding="utf-8"?>
<PreferenceScreen xmlns:android="http://schemas.android.com/apk/res/android">
<PreferenceCategory
android:title="Virtual Smart Card Reader Driver">
<Preference
android:title="Reader Driver Available on Github"
android:summary="@string/vpcd_config_info">
<intent android:action="android.intent.action.VIEW"
android:data="https://frankmorgner.github.io/vsmartcard/virtualsmartcard/README.html" />
</Preference>
<Preference
android:title="Scan Configuration"
android:summary="Scan QR code from vpcd-config to import VPCD's hostname and port."
android:key="scan">
</Preference>
<EditTextPreference
android:key="hostname"
android:defaultValue="10.0.2.2"
android:title="@string/hint_vpcd_hostname"
android:hint="URL or IP address"
android:inputType="textUri" />
<EditTextPreference
android:key="port"
android:defaultValue="35963"
android:title="@string/hint_vpcd_port"
android:inputType="number"
android:hint="Default: 35963" />
</PreferenceCategory>
<PreferenceCategory
android:title="Contactless Smart Card Communication">
<Preference
android:title="NFC System Settings"
android:summary="NFC needs to be enabled for contactless communication with the smart card"
android:key="nfcSettings">
</Preference>
<ListPreference
android:key="delay"
android:defaultValue="250"
android:title="Delay for Card Presence Check"
android:entries="@array/strDelays"
android:entryValues="@array/intDelays" />
</PreferenceCategory>
</PreferenceScreen>

View File

@@ -0,0 +1,15 @@
package com.vsmartcard.remotesmartcardreader.app;
import org.junit.Test;
import static org.junit.Assert.*;
/**
* To work on unit tests, switch the Test Artifact in the Build Variants view.
*/
public class ExampleUnitTest {
@Test
public void addition_isCorrect() throws Exception {
assertEquals(4, 2 + 2);
}
}

View File

@@ -5,7 +5,7 @@ buildscript {
jcenter()
}
dependencies {
classpath 'com.android.tools.build:gradle:1.3.0'
classpath 'com.android.tools.build:gradle:1.5.0'
// NOTE: Do not place your application dependencies here; they belong
// in the individual module build.gradle files
@@ -17,3 +17,7 @@ allprojects {
jcenter()
}
}
task clean(type: Delete) {
delete rootProject.buildDir
}

View File

@@ -52,9 +52,10 @@ application, for example OpenSC_.
The Remote Smart Card Reader has the following dependencies:
- NFC hardware built into the smartphone
- Android 3.0 "Honeycomb" (or newer) or CyanogenMod 8 (or newer)
- Android 4.4 "KitKat" (or newer) or CyanogenMod 11 (or newer)
- permissions for a data connection (communication with |vpcd|) and for using
NFC (communication to the card)
NFC (communication to the card); scanning the configuration via QR code
requires permission to access the camera
- |vpcd| :ref:`installed on the host computer<vicc_install>`
For remotely accessing a traditional smart card reader on one computer from an

View File

@@ -1,8 +1,8 @@
# Project-wide Gradle settings.
# IDE (e.g. Android Studio) users:
# Settings specified in this file will override any Gradle settings
# configured through the IDE.
# Gradle settings configured through the IDE *will override*
# any settings specified in this file.
# For more details on how to configure your build environment visit
# http://www.gradle.org/docs/current/userguide/build_environment.html

Binary file not shown.

View File

@@ -1,6 +1,6 @@
#Tue Sep 29 21:49:01 CEST 2015
#Wed Oct 21 11:34:03 PDT 2015
distributionBase=GRADLE_USER_HOME
distributionPath=wrapper/dists
zipStoreBase=GRADLE_USER_HOME
zipStorePath=wrapper/dists
distributionUrl=https\://services.gradle.org/distributions/gradle-2.2.1-all.zip
distributionUrl=https\://services.gradle.org/distributions/gradle-2.8-all.zip

10
remote-reader/gradlew vendored Normal file → Executable file
View File

@@ -42,11 +42,6 @@ case "`uname`" in
;;
esac
# For Cygwin, ensure paths are in UNIX format before anything is touched.
if $cygwin ; then
[ -n "$JAVA_HOME" ] && JAVA_HOME=`cygpath --unix "$JAVA_HOME"`
fi
# Attempt to set APP_HOME
# Resolve links: $0 may be a link
PRG="$0"
@@ -61,9 +56,9 @@ while [ -h "$PRG" ] ; do
fi
done
SAVED="`pwd`"
cd "`dirname \"$PRG\"`/" >&-
cd "`dirname \"$PRG\"`/" >/dev/null
APP_HOME="`pwd -P`"
cd "$SAVED" >&-
cd "$SAVED" >/dev/null
CLASSPATH=$APP_HOME/gradle/wrapper/gradle-wrapper.jar
@@ -114,6 +109,7 @@ fi
if $cygwin ; then
APP_HOME=`cygpath --path --mixed "$APP_HOME"`
CLASSPATH=`cygpath --path --mixed "$CLASSPATH"`
JAVACMD=`cygpath --unix "$JAVACMD"`
# We build the pattern for arguments to be converted via cygpath
ROOTDIRSRAW=`find -L / -maxdepth 1 -mindepth 1 -type d 2>/dev/null`

View File

@@ -13,7 +13,7 @@
<content url="file://$MODULE_DIR$">
<excludeFolder url="file://$MODULE_DIR$/.gradle" />
</content>
<orderEntry type="jdk" jdkName="1.7" jdkType="JavaSDK" />
<orderEntry type="inheritedJdk" />
<orderEntry type="sourceFolder" forTests="false" />
</component>
</module>