I'm trying to implement an Android Activity that detects the IDTech card reader accepts a simple card swipe.
Below is the bare bones structure to my implementation for which I took help from here as well
The code:
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import IDTech.MSR.XMLManager.StructConfigParameters;
import IDTech.MSR.uniMag.uniMagReader;
import IDTech.MSR.uniMag.uniMagReaderMsg;
import android.app.Activity;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.TextView;
public class MainActivity extends Activity implements uniMagReaderMsg {
private uniMagReader myUniMagReader = null;
private Button btnSwipe;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
if(myUniMagReader == null) {
myUniMagReader = new uniMagReader(this,this);
myUniMagReader.setSaveLogEnable(false);
myUniMagReader.setXMLFileNameWithPath(null);
myUniMagReader.loadingConfigurationXMLFile(true);
//myUniMagReader.setVerboseLoggingEnable(true);
myUniMagReader.registerListen();
}
btnSwipe = (Button) findViewById(R.id.button1);
btnSwipe.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
myUniMagReader.startSwipeCard();
}
});
}
#Override
public void onDestroy() {
myUniMagReader.stopSwipeCard();
myUniMagReader.unregisterListen();
myUniMagReader.release();
super.onDestroy();
}
#Override
public boolean getUserGrant(int arg0, String arg1) {
Log.d("UniMag", "getUserGrant -- " + arg1);
return true;
}
#Override
public void onReceiveMsgAutoConfigProgress(int arg0) {
// TODO Auto-generated method stub
Log.d("UniMag", "onReceiveMsgAutoConfigProgress");
}
#Override
public void onReceiveMsgCardData(byte arg0, byte[] arg1) {
Log.d("UniMag", "onReceiveMsgCardData");
Log.d("UniMag", "Successful swipe!");
}
final Handler swipeHandler = new Handler() {
#Override
public void handleMessage(Message msg) {
String text = (String)msg.obj;
TextView dataView = (TextView) findViewById(R.id.text_view);
dataView.setText(text);
}
};
#Override
public void onReceiveMsgCommandResult(int arg0, byte[] arg1) {
Log.d("UniMag", "onReceiveMsgCommandResult");
}
#Override
public void onReceiveMsgConnected() {
Log.d("UniMag", "onReceiveMsgConnected");
Log.d("UniMag", "Card reader is connected.");
}
#Override
public void onReceiveMsgDisconnected() {
Log.d("UniMag", "onReceiveMsgDisconnected");
if(myUniMagReader.isSwipeCardRunning()) {
myUniMagReader.stopSwipeCard();
}
myUniMagReader.release();
}
#Override
public void onReceiveMsgFailureInfo(int arg0, String arg1) {
Log.d("UniMag","onReceiveMsgFailureInfo -- " + arg1);
}
#Override
public void onReceiveMsgSDCardDFailed(String arg0) {
Log.d("UniMag", "onReceiveMsgSDCardDFailed -- " + arg0);
}
#Override
public void onReceiveMsgTimeout(String arg0) {
Log.d("UniMag", "onReceiveMsgTimeout -- " + arg0);
Log.d("UniMag","Timed out!");
}
#Override
public void onReceiveMsgToConnect() {
Log.d("UniMag","Swiper Powered Up");
}
#Override
public void onReceiveMsgToSwipeCard() {
Log.d("UniMag","onReceiveMsgToSwipeCard");
}
#Override
public void onReceiveMsgAutoConfigCompleted(StructConfigParameters arg0) {
Log.d("UniMag", "onReceiveMsgAutoConfigCompleted");
}
}
The issue here is that I only get these two messages in the Logcat
"Swiper is powered up" from onReceiveMsgToConnect()
And After a few seconds (maybe 20 sec)
"Timed out!" from onReceiveMsgTimeout() that sends back a string saying unable to connect to device. I have multiple IDTech devices and this happens the same on every device. Also, sometimes if I am lucky enough I do get:
"Card reader is connected." from onReceiveMsgConnected() that means it is connected. But this happens very rarely.
Any help would be very appreciated.
Thanks!
Okay so I got it working.
I was using an older version of the sdk (unimag.reader.android-1.0.0.jar) and the configuration xml file (idt_unimagcfg_default.xml). I simply updated them to the most recent version of the sdk and the xml.
New versions (as of December 2014)
SDK: IDT_UniMagSDKAndroid_v4.4.jar - xml: umcfg.4.4.1.xml
And the timeout problem is solved.
P.S: just as a side note, please also do visit their website for any device specific details you might need for the specific card swiper you are using.
For example: I was using a "Shuttle, Two-Track Secure Mobile MagStripe Reader" with a "HTC ONE" phone. After going on to this page here I figured that for HTC ONE I need to turn off my "Beats audio" to appropriately use this device.
I hope this helps.
Related
I have a simple app for voice recognition that prints all the possible string ArrayList decoded. The problem is that it only works if I don't stop/pause between words. If I have a slight pause (very short as if I was speking normally) the app stops. I looked at the parameter SPEECH_INPUT_COMPLETE_SILENCE_LENGTH_MILLIS but it didn't change anything.
Any clue from a voice recognition specialist?
Here is my code:
package com.bernard.vtt;
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.speech.RecognitionListener;
import android.speech.RecognizerIntent;
import android.speech.SpeechRecognizer;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
import java.util.ArrayList;
public class MainActivity extends Activity implements RecognitionListener {
private TextView mText;
SpeechRecognizer speech = null;
private Intent recognizerIntent;
#Override
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Button speakButton = (Button) findViewById(R.id.btn);
mText = (TextView) findViewById(R.id.textView1);
speech = SpeechRecognizer.createSpeechRecognizer(this);
speech.setRecognitionListener(this);
recognizerIntent = new Intent(RecognizerIntent.ACTION_RECOGNIZE_SPEECH);
recognizerIntent.putExtra(RecognizerIntent.EXTRA_LANGUAGE_PREFERENCE,
"en");
recognizerIntent.putExtra(RecognizerIntent.EXTRA_CALLING_PACKAGE,
this.getPackageName());
recognizerIntent.putExtra(RecognizerIntent.EXTRA_LANGUAGE_MODEL,
RecognizerIntent.LANGUAGE_MODEL_WEB_SEARCH);
recognizerIntent.putExtra(RecognizerIntent.EXTRA_MAX_RESULTS, 3);
speakButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
speech.startListening(recognizerIntent);
}
});
}
#Override
public void onResults(Bundle results) {
ArrayList<String> matches = results
.getStringArrayList(SpeechRecognizer.RESULTS_RECOGNITION);
String text = "";
assert matches != null;
for (String result : matches)
text += result + "\n";
mText.setText(text);
speech.stopListening();
}
#Override
public void onReadyForSpeech(Bundle params) {
}
#Override
public void onBeginningOfSpeech() {
}
#Override
public void onRmsChanged(float rmsdB) {
}
#Override
public void onBufferReceived(byte[] buffer) {
}
#Override
public void onEndOfSpeech() {
}
#Override
public void onError(int error) {
}
#Override
public void onPartialResults(Bundle partialResults) {
}
#Override
public void onEvent(int eventType, Bundle params) {
}
I believe the built-in speech recognition does not continually run. It is designed to hear one voice input and give results. If you want to continually listen, you need to restart recognition on each onResults callback. I also believe SPEECH_INPUT_COMPLETE_SILENCE_LENGTH_MILLIS has a max value, which is why changing it has little effect.
I am working on an app that implements a Web Socket server. I am referring this library - https://github.com/TooTallNate/Java-WebSocket
The problem is that the thread holds up the entire UI. Here is the code -
package com.example.websocket;
import java.net.InetSocketAddress;
import java.net.UnknownHostException;
import java.util.Collections;
import java.nio.ByteBuffer;
import org.java_websocket.WebSocket;
import org.java_websocket.drafts.Draft;
import org.java_websocket.drafts.Draft_17;
import org.java_websocket.framing.FrameBuilder;
import org.java_websocket.framing.Framedata;
import org.java_websocket.handshake.ClientHandshake;
import org.java_websocket.server.WebSocketServer;
import android.os.Bundle;
import android.provider.Settings.Global;
import android.app.Activity;
import android.content.Context;
import android.view.Menu;
import android.view.View;
import android.view.inputmethod.InputMethodManager;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;
public class MainActivity extends Activity {
EditText port, msg;
Button listener, send;
TextView status;
int p;
int count = 0;
boolean connect = false;
boolean listen = false;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
msg = (EditText)findViewById(R.id.editText2);
listener = (Button)findViewById(R.id.button1);
send = (Button)findViewById(R.id.button2);
status = (TextView)findViewById(R.id.textView1);
listener.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Thread t = new Thread(new Runnable() {
#Override
public void run() {
try {
SimpleServer server = new SimpleServer();
server.start();
status.setText("Working inside Thread");
} catch (UnknownHostException e) {
e.printStackTrace();
}
}
});
t.start();
}
});
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
public class SimpleServer extends WebSocketServer {
public SimpleServer() throws UnknownHostException {
super(new InetSocketAddress(9998));
// TODO Auto-generated constructor stub
}
#Override
public void onClose(WebSocket arg0, int arg1, String arg2, boolean arg3) {
// TODO Auto-generated method stub
}
#Override
public void onError(WebSocket arg0, Exception arg1) {
// TODO Auto-generated method stub
}
#Override
public void onMessage(WebSocket arg0, String arg1) {
// TODO Auto-generated method stub
}
#Override
public void onOpen(WebSocket arg0, ClientHandshake arg1) {
status.setText("Working");
}
}
}
You cannot update ui from other threads:
status.setText("Working inside Thread");
use runOnUiThread method of activity
runOnUiThread(new Runnable() {
#Override
public void run() {
status.setText("Working inside Thread");
}
});
By the way youre code cause memory leack and crashes. You cannot start long living operations in activity context. You should run service ,or make this thread in application context, results to ui you can pass by using EventBus.
Is it possible to integrate video ads from Flurry in an android app? I tried some things, but it didn't work. The Flurry Android SDK has the onVideoCompleted function, and in the Android Flurry SDK Release Notes, the following can be found: verified support for clips in AdUnity (http://support.flurry.com/index.php?title=Analytics/Code/ReleaseNotes/Android).
I tried this code, but it didn't work for me:
package com.test.flurrytest;
import android.os.Bundle;
import android.app.Activity;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.FrameLayout;
import com.flurry.android.FlurryAdType;
import com.flurry.android.FlurryAds;
import com.flurry.android.FlurryAdSize;
import com.flurry.android.FlurryAgent;
import com.flurry.android.FlurryAdListener;
public class MainActivity extends Activity implements AdCallbackListener, FlurryAdListener {
FrameLayout mBanner;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
mBanner = new FrameLayout(this);
FlurryAds.setAdListener(this);
FlurryAds.enableTestAds(true);
Button watchvideo = (Button) findViewById(R.id.watchvideo);
watchvideo.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
FlurryAds.fetchAd(MainActivity.this, "TestAdspace", mBanner, FlurryAdSize.FULLSCREEN);
FlurryAds.displayAd(MainActivity.this, "TestAdspace", mBanner);
}
});
}
// Flurry
#Override
public void onStart() {
super.onStart();
FlurryAgent.onStartSession(this, "****");
}
public void spaceDidReceiveAd(String adSpace) {
FlurryAds.displayAd(this, adSpace, mBanner);
}
public void onVideoCompleted(String adSpace) {
// The user get some points now
}
public boolean shouldDisplayAd(String adSpaceName, FlurryAdType type) {
return true;
}
public void onAdClosed(String adSpaceName) {
}
public void onRenderFailed(String adSpaceName) {
Toast.makeText(getApplicationContext(), "The video has failed to render. Try again.", Toast.LENGTH_LONG).show();
}
public void onApplicationExit(String adSpaceName) {
}
public void spaceDidFailToReceiveAd(String adSpaceName) {
Toast.makeText(getApplicationContext(), "Failed to receive ad. Try again.", Toast.LENGTH_LONG).show();
}
public void onAdClicked(String adSpaceName) {
}
public void onAdOpened(String adSpaceName) {
}
#Override
public void onStop() {
super.onStop();
FlurryAds.removeAd(this, "TestAdspace", mBanner);
FlurryAgent.onEndSession(this);
}
}
Is it possible with Android, and if so, how to integrate it?
Thanks!
Sorry for my english.
I want to program a native app in Android to connect with a server for interactive comunications. Websocket tegnology is perfect fothis. I have installed and working Tomcat 7.0.39 in my laptop with IP 192.168.1.250. I have tryed the examples echo, snake, etc and it works fine using ws://localhost:8080/.... and using ws://192.168.1.250:8080/...
I'm using autobahn with eclipse to connect to my server. I have installed apk in my Android mobile with autobahn client websocket sample and it connects perfectly withn ws://echo.websocket.org.
The problem is that from android to my server (in my laptop) not work. From android to ws://echo.websocket.org works fine (I supose that autobahn example works well), my server works fine because de examples comes with tomcat work fine.
Because I have to make intesive work with information that travel between server and clients, I can't use javascript on server side, I need java servlets or others to work with databases, files ando so on.
What is wrong? Firewall is off, and wireshark show me how android client try to connect to my laptop server ( I don't anderstand wireshark info well ) but the connection loses.
This my android code:
package com.example.autobahnandroiddemo;
import de.tavendo.autobahn.WebSocketConnection;
import de.tavendo.autobahn.WebSocketException;
import de.tavendo.autobahn.WebSocketHandler;
import android.app.Activity;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.util.Log;
import android.view.Gravity;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;
public class MainActivity extends Activity {
static final String TAG = "de.tavendo.autobahn.echo";
private static final String PREFS_NAME = "AutobahnAndroidEcho";
static EditText mHostname;
static EditText mPort;
static TextView mStatusline;
static Button mStart;
static EditText mMessage;
static Button mSendMessage;
private SharedPreferences mSettings;
private void alert(String message) {
Toast toast = Toast.makeText(getApplicationContext(), message, Toast.LENGTH_SHORT);
toast.setGravity(Gravity.CENTER_VERTICAL | Gravity.CENTER_HORIZONTAL, 0, 0);
toast.show();
}
private void loadPrefs() {
mHostname.setText(mSettings.getString("hostname", ""));
mPort.setText(mSettings.getString("port", "9000"));
}
private void savePrefs() {
SharedPreferences.Editor editor = mSettings.edit();
editor.putString("hostname", mHostname.getText().toString());
editor.putString("port", mPort.getText().toString());
editor.commit();
}
private void setButtonConnect() {
mHostname.setEnabled(true);
mPort.setEnabled(true);
mStart.setText("Connect");
mStart.setOnClickListener(new Button.OnClickListener() {
public void onClick(View v) {
start();
}
});
}
private void setButtonDisconnect() {
mHostname.setEnabled(false);
mPort.setEnabled(false);
mStart.setText("Disconnect");
mStart.setOnClickListener(new Button.OnClickListener() {
public void onClick(View v) {
mConnection.disconnect();
}
});
}
private final WebSocketConnection mConnection = new WebSocketConnection();
private void start() {
final String wsuri = mHostname.getText() + ":" + mPort.getText();
mStatusline.setText("Status: Connecting to " + wsuri + " ..");
setButtonDisconnect();
try {
mConnection.connect(wsuri, new WebSocketHandler() {
#Override
public void onOpen() {
mStatusline.setText("Status: Connected to " + wsuri);
savePrefs();
mSendMessage.setEnabled(true);
mMessage.setEnabled(true);
}
#Override
public void onTextMessage(String payload) {
alert("Got echo: " + payload);
}
#Override
public void onClose(int code, String reason) {
alert("Connection lost.");
mStatusline.setText("Status: Ready.");
setButtonConnect();
mSendMessage.setEnabled(false);
mMessage.setEnabled(false);
}
});
} catch (WebSocketException e) {
Log.d(TAG, e.toString());
}
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mHostname = (EditText) findViewById(R.id.hostname);
mPort = (EditText) findViewById(R.id.port);
mStatusline = (TextView) findViewById(R.id.statusline);
mStart = (Button) findViewById(R.id.start);
mMessage = (EditText) findViewById(R.id.msg);
mSendMessage = (Button) findViewById(R.id.sendMsg);
mSettings = getSharedPreferences(PREFS_NAME, 0);
loadPrefs();
setButtonConnect();
mSendMessage.setEnabled(false);
mMessage.setEnabled(false);
mSendMessage.setOnClickListener(new Button.OnClickListener() {
public void onClick(View v) {
mConnection.sendTextMessage(mMessage.getText().toString());
}
});
}
#Override
protected void onDestroy() {
super.onDestroy();
if (mConnection.isConnected()) {
mConnection.disconnect();
}
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
MenuInflater inflater = getMenuInflater();
inflater.inflate(R.menu.main_menu, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case R.id.quit:
finish();
break;
default:
return super.onOptionsItemSelected(item);
}
return true;
}
}
AND THIS IS MY SERVLET TOMCAT CODE:
package servlets;
import org.apache.catalina.websocket.MessageInbound;
import org.apache.catalina.websocket.StreamInbound;
import org.apache.catalina.websocket.WebSocketServlet;
import org.apache.catalina.websocket.WsOutbound;
import javax.servlet.http.HttpServletRequest;
import java.io.IOException;
import java.nio.ByteBuffer;
import java.nio.CharBuffer;
public class SimpleWebSocketServlet extends WebSocketServlet {
private static final long serialVersionUID = 1L;
#Override
protected StreamInbound createWebSocketInbound(String string, HttpServletRequest hsr) {
return new MessageInbound() {
#Override
protected void onBinaryMessage(ByteBuffer bb) throws IOException {
}
#Override
protected void onTextMessage(CharBuffer cb) throws IOException {
System.out.println(cb.toString());
WsOutbound outbound = getWsOutbound();
outbound.writeTextMessage(cb);
}
};
}
}
I don't know what's wrong. Have another solution to use android client in conjuntion with server (java servlets on similar tecnology) through websockets?
Thanks
I think you should have put the code of connecting into onCreate.
I'm trying to start a very simple jWebSocket Client on Android and connect it to my local server. I'm using the JWC class from the demo together with jWebSocket 1.0 beta 8 and Android 4.0.3, my code looks like this:
import org.jwebsocket.api.WebSocketClientEvent;
import org.jwebsocket.api.WebSocketClientTokenListener;
import org.jwebsocket.api.WebSocketPacket;
import org.jwebsocket.client.token.BaseTokenClient;
import org.jwebsocket.kit.WebSocketException;
import org.jwebsocket.token.Token;
import android.app.Activity;
import android.content.Context;
import android.content.IntentFilter;
import android.os.Bundle;
import android.view.View;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.Spinner;
import cased.smids.communication.JWC;
public class TasksActivity extends Activity implements WebSocketClientTokenListener {
Spinner spinner;
Button btn_Start;
/** Called when the activity is first created. */
#Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
this.setContentView(R.layout.main);
JWC.init();
spinner = (Spinner)findViewById(R.id.sp_Task);
btn_Start = (Button)findViewById(R.id.btn_Start);
ArrayAdapter<CharSequence> adapter =
ArrayAdapter.createFromResource(
this,
R.array.Tasks,
android.R.layout.simple_spinner_item
);
adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
spinner.setAdapter(adapter);
btn_Start.setOnClickListener(new View.OnClickListener() {
public void onClick(View src) {
switch (src.getId()) {
case R.id.btn_Start:
if (spinner.getSelectedItem().toString().equals("Connect")) {
try {
System.out.println("connecting manually...");
JWC.open();
} catch (WebSocketException e) {
e.printStackTrace();
}
}
default:
break;
}
}
});
}
#Override
protected void onResume() {
super.onResume();
System.out.println("* opening... ");
try {
JWC.addListener(this);
JWC.open();
} catch (WebSocketException ex) {
System.out.println("* exception: " + ex.getMessage());
}
}
#Override
protected void onPause() {
System.out.println("* closing... ");
try {
JWC.close();
JWC.removeListener(this);
} catch (WebSocketException ex) {
System.out.println("* exception: " + ex.getMessage());
}
super.onPause();
}
public void processClosed(WebSocketClientEvent arg0) {
System.out.println("closed");
}
public void processOpened(WebSocketClientEvent arg0) {
System.out.println("opened");
}
public void processOpening(WebSocketClientEvent arg0) {
System.out.println("opening");
}
public void processPacket(WebSocketClientEvent arg0, WebSocketPacket arg1) {
System.out.println("packet");
}
public void processReconnecting(WebSocketClientEvent arg0) {
System.out.println("reconnecting");
}
public void processToken(WebSocketClientEvent arg0, Token arg1) {
System.out.println("token");
}
}
so basically it's just a spinner and a button. For now, all I want to do is connect to my local jWebSocketServer. The demo-app (the .apk package from the website, if I import the code eclipse tells me to remove many "#Overwrite" before it compiles the code - after that same "bug" occurs) works with my server so it has to be the code. Right now all I get is "connecting..." and about 0.1s later "closed". Every time.
btw. the app has the right INTERNET and ACCESS_NETWORK_STATE so that shouldn't be a problem.
i will be grateful for any help.
Cheers
Turns out, BaseTokenClient.open() is catching all exceptions and doing nothing about it (silent fail). In my case - NetworkOnMainThreadException. Mystery solved.