How to display a single value in android Threads - android

In android , i create a application based on RFID Card Reader on mobile. While i tapping Card on RFID Reader it generates same value at many times until the card untapped from the reader.
I want to show only one value per tapping card on RFID reader. Here i place my code and Sample snapshot of my application.
Guide me and tell solution for my problem.
public static MediaPlayer mp;
FT_Device ftDev = null;
int DevCount = -1;
int currentIndex = -1;
int openIndex = 0;
/*graphical objects*/
EditText readText;
Button readEnButton;
static int iEnableReadFlag = 1;
/*local variables*/
int baudRate; /*baud rate*/
byte stopBit; /*1:1stop bits, 2:2 stop bits*/
byte dataBit; /*8:8bit, 7: 7bit*/
byte parity; /* 0: none, 1: odd, 2: even, 3: mark, 4: space*/
byte flowControl; /*0:none, 1: flow control(CTS,RTS)*/
int portNumber; /*port number*/
long wait_sec=3000;
byte[] readData; //similar to data.
public static final int readLength = 1024; // changed length from 512
public int iavailable = 0;
char[] readDataToText;
//char readDataToTextSudha;
public boolean bReadThreadGoing = false;
public readThread read_thread;
public static D2xxManager ftD2xx = null;
boolean uart_configured = false;
// Empty Constructor
public MainActivity() {
}
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
readData = new byte[readLength];
readDataToText = new char[readLength];
//readDataToTextSudha = new char;
readText = (EditText) findViewById(R.id.ReadValues);
readText.setInputType(0);
readEnButton = (Button) findViewById(R.id.readEnButton);
baudRate = 9600;
/* default is stop bit 1 */
stopBit = 1;
/* default data bit is 8 bit */
dataBit = 8;
/* default is none */
parity = 0;
/* default flow control is is none */
flowControl = 0;
portNumber = 1;
try {
ftD2xx = D2xxManager.getInstance(this);
} catch (D2xxManager.D2xxException ex) {
ex.printStackTrace();
}
//Opening Coding
if (DevCount <= 0) {
createDeviceList();
} else {
connectFunction();
}
//Configuration coding
if (DevCount <= 0 || ftDev == null) {
Toast.makeText(getApplicationContext(), "Device not open yet...", Toast.LENGTH_SHORT).show();
} else {
SetConfig(baudRate, dataBit, stopBit, parity, flowControl);
}
readEnButton.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
if (DevCount <= 0 || ftDev == null) {
Toast.makeText(getApplicationContext(), "Device not open yet...", Toast.LENGTH_SHORT).show();
} else if (uart_configured == false) {
Toast.makeText(getApplicationContext(), "UART not configure yet...", Toast.LENGTH_SHORT).show();
return;
} else {
EnableRead();
}
}
});
}
public void EnableRead() {
iEnableReadFlag = (iEnableReadFlag + 1) % 2;
if (iEnableReadFlag == 1) {
ftDev.purge((byte) (D2xxManager.FT_PURGE_TX));
ftDev.restartInTask();
readEnButton.setText("Read Enabled");
Toast.makeText(getApplicationContext(),"Read Enabled",Toast.LENGTH_LONG).show();
} else {
ftDev.stopInTask();
readEnButton.setText("Read Disabled");
Toast.makeText(getApplicationContext(),"Read Disabled",Toast.LENGTH_LONG).show();
}
}
public void createDeviceList() {
int tempDevCount = ftD2xx.createDeviceInfoList(getApplicationContext());
if (tempDevCount > 0) {
if (DevCount != tempDevCount) {
DevCount = tempDevCount;
updatePortNumberSelector();
}
} else {
DevCount = -1;
currentIndex = -1;
}
};
public void disconnectFunction() {
DevCount = -1;
currentIndex = -1;
bReadThreadGoing = false;
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
if (ftDev != null) {
synchronized (ftDev) {
if (true == ftDev.isOpen()) {
ftDev.close();
}
}
}
}
public void connectFunction() {
int tmpProtNumber = openIndex + 1;
if (currentIndex != openIndex) {
if (null == ftDev) {
ftDev = ftD2xx.openByIndex(getApplicationContext(), openIndex);
} else {
synchronized (ftDev) {
ftDev = ftD2xx.openByIndex(getApplicationContext(), openIndex);
}
}
uart_configured = false;
} else {
Toast.makeText(getApplicationContext(), "Device port " + tmpProtNumber + " is already opened", Toast.LENGTH_LONG).show();
return;
}
if (ftDev == null) {
Toast.makeText(getApplicationContext(), "open device port(" + tmpProtNumber + ") NG, ftDev == null", Toast.LENGTH_LONG).show();
return;
}
if (true == ftDev.isOpen()) {
currentIndex = openIndex;
Toast.makeText(getApplicationContext(), "open device port(" + tmpProtNumber + ") OK", Toast.LENGTH_SHORT).show();
if (false == bReadThreadGoing) {
read_thread = new readThread(handler);
read_thread.start();
bReadThreadGoing = true;
}
} else {
Toast.makeText(getApplicationContext(), "open device port(" + tmpProtNumber + ") NG", Toast.LENGTH_LONG).show();
}
}
public void updatePortNumberSelector() {
if (DevCount == 2) {
Toast.makeText(getApplicationContext(), "2 port device attached", Toast.LENGTH_SHORT).show();
} else if (DevCount == 4) {
Toast.makeText(getApplicationContext(), "4 port device attached", Toast.LENGTH_SHORT).show();
} else {
Toast.makeText(getApplicationContext(), "1 port device attached", Toast.LENGTH_SHORT).show();
}
}
public void SetConfig(int baud, byte dataBits, byte stopBits, byte parity, byte flowControl) {
if (ftDev.isOpen() == false) {
Log.e("j2xx", "SetConfig: device not open");
return;
}
ftDev.setBitMode((byte) 0, D2xxManager.FT_BITMODE_RESET);
ftDev.setBaudRate(baud);
ftDev.setDataCharacteristics(dataBits, stopBits, parity);
uart_configured = true;
Toast.makeText(getApplicationContext(), "Config done", Toast.LENGTH_SHORT).show();
}
final Handler handler = new Handler() {
#Override
public void handleMessage(Message msg) {
if (iavailable > 0) {
mp = MediaPlayer.create(MainActivity.this, R.raw.beep);
mp.start();
readText.append(String.copyValueOf(readDataToText, 0, iavailable));
}
}
};
private class readThread extends Thread {
Handler mHandler;
readThread(Handler h) {
mHandler = h;
this.setPriority(Thread.MIN_PRIORITY);
}
#Override
public void run() {
int i;
while (true == bReadThreadGoing) {
try {
Thread.sleep(1000); //changed
} catch (InterruptedException e) {
}
synchronized (ftDev) {
iavailable = ftDev.getQueueStatus();
if (iavailable > 0) {
if (iavailable > readLength) {
iavailable = readLength;
}
ftDev.read(readData, iavailable,wait_sec);
for (i = 0; i < iavailable; i++) {
readDataToText[i] = (char) readData[i];
}
Message msg = mHandler.obtainMessage();
mHandler.sendMessage(msg);
}
}
}
}
}
#Override
public void onResume() {
super.onResume();
DevCount = 0;
createDeviceList();
if (DevCount > 0) {
connectFunction();
SetConfig(baudRate, dataBit, stopBit, parity, flowControl);
}
}
}
My problem would snapped here
Getting Value continuously from Reader
I want this type of value when i tap the card
If i tap some other cards, old card value replaces from the new one.
Guide me.
Thanks in Advance

I got the answer by using of Threads. When the card tapping it get some values after sleep of one or two seconds only the next value have to get from the reader.
public void run() {
int i;
while (true == bReadThreadGoing) { // Means Make sure , getting value from Reader
try {
Thread.sleep(1000); // Wait for a second to get another value.
clearText(); //clear the old value and get new value.
} catch (InterruptedException e) {
}
And clearing the edittext by using this command.
public void clearText() {
runOnUiThread(new Runnable() {
public void run() {
readText.setText("");
}
});
}

Related

Port forwarding service

to be able using a remote service through localhost IP (to hide real address from users in other intents) I am using this service to port-forwarding :
public class PortForward extends Service implements Runnable {
private static final String TAG = "Port Forward";
private int localPort;
private int remotePort;
private String remoteHost;
private boolean running = false;
private int lastUp = -1;
private int lastDown = -1;
private int bUp = 0;
private int bDown = 0;
LocalBroadcastManager bm;
private Thread t;
ServerSocketChannel serverSocketChannel = null;
public Handler sendBroadcastHandler = new Handler() {
public void handleMessage(Message msg) {
Intent i = new Intent().setAction(MainActivity.USAGE_UPDATE);
i.putExtra("bUp", bUp);
i.putExtra("bDown", bDown);
bm.sendBroadcast(i);
}
};
public Handler sendDeathHandler = new Handler() {
public void handleMessage(Message msg) {
Bundle b = msg.getData();
String causeOfDeath = b.getString("causeOfDeath", "unknown");
Notification note = new Notification.Builder(PortForward.this)
.setContentTitle("TCP forwarding thread dead")
.setContentText("Cause of death: " + causeOfDeath)
.setSmallIcon(R.drawable.ic_launcher).build();
NotificationManager mNotificationManager = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
mNotificationManager.notify(1338, note);
}
};
private void updateCounts() {
updateCounts(false);
}
private void updateCounts(boolean force) {
if (!force && (bUp - lastUp < 10000 && bDown - lastDown < 10000)) {
return;
}
lastUp = bUp;
lastDown = bDown;
Message msg = sendBroadcastHandler.obtainMessage();
sendBroadcastHandler.sendMessage(msg);
}
#Override
public void onDestroy() {
Log.d(TAG, "Service onDestroy");
if (t != null) {
t.interrupt();
try {
t.join();
} catch (InterruptedException e) {
Log.d(TAG, "couldn't join forwarder-thread");
System.exit(1);
}
}
Log.d(TAG, "Killed it");
}
#Override
public IBinder onBind(Intent intent) {
return null;
}
#Override
public int onStartCommand(Intent intent, int flags, int startId) {
Log.d(TAG, "Service onStart");
if (running){
updateCounts(true);
return START_REDELIVER_INTENT;
}
running = true;
bm = LocalBroadcastManager.getInstance(this);
localPort = intent.getIntExtra("localPort", -1);
remotePort = intent.getIntExtra("remotePort", -1);
remoteHost = intent.getStringExtra("remoteHost");
t = new Thread(this);
t.start();
Log.d(TAG, "launching a thread");
Notification note = new Notification.Builder(this)
.setContentTitle("Forwarding TCP Port")
.setContentText(String.format(
"localhost:%s -> %s:%s", localPort, remoteHost, remotePort))
.setSmallIcon(R.drawable.ic_launcher)
.build();
Intent i = new Intent(this, MainActivity.class);
i.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP | Intent.FLAG_ACTIVITY_SINGLE_TOP);
PendingIntent pi = PendingIntent.getActivity(this, 0, i, 0);
note.contentIntent = pi;
note.flags |= Notification.FLAG_NO_CLEAR;
startForeground(1337, note);
Log.d(TAG, "doing startForeground");
updateCounts(true);
return START_REDELIVER_INTENT;
}
private void reportException(Exception e){
StringWriter sw = new StringWriter();
e.printStackTrace(new PrintWriter(sw));
Message msg = sendDeathHandler.obtainMessage();
Bundle b = msg.getData();
b.putString("causeOfDeath", sw.toString());
sendDeathHandler.sendMessage(msg);
}
private void finish(Selector s){
try {
serverSocketChannel.close();
} catch (IOException e){ }
Set<SelectionKey> selectedKeys = s.keys();
Iterator<SelectionKey> keyIterator = selectedKeys.iterator();
while (keyIterator.hasNext()) {
closeConnectionForKey(keyIterator.next());
}
}
private void closeChannel(SocketChannel c){
if (c != null){
try {
if (c != null){
c.close();
}
} catch (IOException e){ }
}
}
private void closeConnectionForKey(SelectionKey key){
PFGroup g = null;
try {
g = (PFGroup)key.attachment();
} catch (Exception e){
return;
}
if (g == null) {return;}
closeChannel(g.iChannel);
closeChannel(g.oChannel);
}
#Override
public void run() {
String causeOfDeath = null;
System.out.println("Server online");
Selector selector = null;
try {
selector = Selector.open();
serverSocketChannel = ServerSocketChannel.open();
serverSocketChannel.socket().bind(new InetSocketAddress(localPort));
serverSocketChannel.configureBlocking(false);
serverSocketChannel.register(selector, SelectionKey.OP_ACCEPT);
} catch (IOException e) {
reportException(e);
return;
}
System.out.println("Server socket bound.");
while (true) {
System.out.println("Waiting for conn");
updateCounts();
int readyChannels = 0;
try {
readyChannels = selector.select();
} catch (IOException e) {
reportException(e);
continue;
}
if (Thread.currentThread().isInterrupted()) {
finish(selector);
return;
}
if (readyChannels == 0) {
continue;
}
Set<SelectionKey> selectedKeys = selector.selectedKeys();
Iterator<SelectionKey> keyIterator = selectedKeys.iterator();
while (keyIterator.hasNext()) {
//System.out.println("Ready on " + readyChannels);
SelectionKey key = keyIterator.next();
keyIterator.remove();
if (!key.isValid()) {
continue;
} else if (key.isAcceptable()) {
System.out.println("Acceptable!");
PFGroup g = new PFGroup();
// 512KB buffers
g.iBuffer = ByteBuffer.allocate(512000);
g.oBuffer = ByteBuffer.allocate(512000);
boolean iConnected = false;
try {
g.iChannel = serverSocketChannel.accept();
iConnected = g.iChannel.finishConnect();
if (iConnected){
g.sidesOn++;
}
g.iChannel.configureBlocking(false);
g.iKey = g.iChannel.register(selector, 0, g);
g.oChannel = SocketChannel.open();
g.oChannel.configureBlocking(false);
g.oChannel.connect(new InetSocketAddress(remoteHost, remotePort));
g.oKey =g.oChannel.register(selector, SelectionKey.OP_CONNECT, g);
} catch (IOException e) {
continue;
}
} else if (key.isConnectable()) {
System.out.println("connectable!");
try {
SocketChannel c = (SocketChannel) key.channel();
PFGroup g = (PFGroup)key.attachment();
if (!c.finishConnect()) {
System.out.println("couldn't finish conencting");
continue;
}
g.sidesOn++;
System.out.println("Initilized the bidirectional forward");
key.interestOps(SelectionKey.OP_READ);
g.iKey = g.iChannel.register(selector, SelectionKey.OP_READ, g);
} catch (IOException e) {
continue;
}
} else if (key.isReadable()) {
try {
ByteBuffer b = null;
SocketChannel from = null;
SocketChannel to = null;
PFGroup g = (PFGroup)key.attachment();
String label = null;
if (key.channel() == g.iChannel){
from = g.iChannel;
to = g.oChannel;
b = g.iBuffer;
label = "incoming";
} else if (key.channel() == g.oChannel){
from = g.oChannel;
to = g.iChannel;
b = g.oBuffer;
label = "outgoing";
}
int i = from.read(b);
b.flip();
while (b.hasRemaining()) {
int bytes = to.write(b);
if(label.equals("incoming")){
bUp += bytes;
} else {
bDown += bytes;
}
}
b.clear();
if (i == -1) {
key.cancel();
g.sidesOn--;
if (g.sidesOn == 0){
System.out.println("Done, closing keys");
closeConnectionForKey(key);
}
}
} catch (IOException e){
Log.d(TAG, "closing connection for key.");
closeConnectionForKey(key);
}
}
}
}
}
public class PFGroup {
public ByteBuffer iBuffer;
public ByteBuffer oBuffer;
public SocketChannel iChannel;
public SocketChannel oChannel;
public int sidesOn = 0;
SelectionKey iKey;
SelectionKey oKey;
}
}
and in my main activity i used it like this:
Intent i=new Intent(this, PortForward.class)
.putExtra("localPort", 1195)
.putExtra("remotePort", port)
.putExtra("remoteHost", address);
startService(i);
but it does not work. when app is in background i can not use address:port through 127.0.0.1:1195 .
and also no related log appeasers in logcat.

Unable to send ans receive message from android client using xmpp local server?

I want to build XMPP android client for local server connection, which will able to send text along with live video chat. So initially I am trying to make simple chat application. Using this application I am able to see all the available users but when I try to send a message it does not reach to the server or another client. Can anyone help me to figure out where it the problem?
Chat activity:
public class ChatActivity extends Activity {
private static final int REQUEST_CODE_FOR_GALLERY = 1;
private static final int REQUEST_CODE_FOR_FILEMANAGER = 2;
private static String LOG_TAG = "- Chat Activity -";
private Context context;
private ListView chatListView;
private Button attatchmentButton;
private Button sendButton;
private EditText chatMessageEditText;
private ArrayList<ChatEntry> chatEntries;
private ChatAdapter chatAdapter;
private String fJID, fNickName;
private String mJID, mNickName;
private byte[] fAvatarByte, mAvatarByte;
private Bitmap fAvatarBitmap, mAvatarBitmap;
private XMPPConnection xmppConnection;
private FileTransferManager receiveFileManager;
private FileTransferManager sendFileManager;
private FileTransferListener listener;
private File externalStorageDirectory;
private String fileSrc;
private Handler sHandler, rHandler;
private Thread sThread;
private File rfile;
private LinearLayout layoutReceivingFile;
private LinearLayout layoutSendinfFile;
private ProgressBar rProgressBar;
private ProgressBar sProgressBar;
private ChatManager chatManager;
private Chat chat;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.layout_chat);
// Context
context = this;
// View matching
chatListView = (ListView) findViewById(R.id.chat_message_listview);
attatchmentButton = (Button) findViewById(R.id.chat_attatchment_button);
sendButton = (Button) findViewById(R.id.chat_send_button);
chatMessageEditText = (EditText) findViewById(R.id.chat_message_edit_text);
layoutReceivingFile = (LinearLayout) findViewById(R.id.chat_file_transfer_receive_layout);
layoutSendinfFile = (LinearLayout) findViewById(R.id.chat_file_transfer_send_layout);
rProgressBar = (ProgressBar) findViewById(R.id.chat_receive_file_progress_bar);
sProgressBar = (ProgressBar) findViewById(R.id.chat_send_file_progress_bar);
// Event for attachment button
attatchmentButton.setOnClickListener(new OnClickListener() {
public void onClick(View view) {
AlertDialog.Builder builder = new AlertDialog.Builder(context);
builder.setTitle("File attachment");
builder.setMessage("Choose your file type.");
builder.setNegativeButton("Picture", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
Intent photoPickerIntent = new Intent(Intent.ACTION_PICK);
photoPickerIntent.setType("image/*");
startActivityForResult(photoPickerIntent, REQUEST_CODE_FOR_GALLERY);
}
});
builder.setPositiveButton("File", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
Intent intent = new Intent(ChatActivity.this, FilePickerActivity.class);
ArrayList<String> extensions = new ArrayList<String>();
extensions.add(".png");
extensions.add(".jpg");
extensions.add(".gif");
extensions.add(".tif");
extensions.add(".bmp");
extensions.add(".doc");
extensions.add(".docx");
extensions.add(".ppt");
extensions.add(".pptx");
extensions.add(".xls");
extensions.add(".xlsx");
extensions.add(".pdf");
extensions.add(".zip");
extensions.add(".rar");
intent.putExtra(FilePickerActivity.EXTRA_ACCEPTED_FILE_EXTENSIONS, extensions);
startActivityForResult(intent, REQUEST_CODE_FOR_FILEMANAGER);
}
});
builder.setCancelable(true);
AlertDialog alertDialog = builder.create();
alertDialog.show();
}
});
// Event for send message button
sendButton.setOnClickListener(new OnClickListener() {
public void onClick(View view) {
String message = chatMessageEditText.getText().toString();
if ( message.trim().length() == 0 ) {
Toast.makeText(context, "Please fill up some text.", Toast.LENGTH_SHORT).show();
} else {
try {
chat.sendMessage(message);
chatMessageEditText.setText(null);
Log.d(LOG_TAG, "Trying to send message 1");
Toast.makeText(context, "trying to send" +message.toString(), Toast.LENGTH_LONG).show();
ChatEntry chatEntry = new ChatEntry();
chatEntry.setAttachedFile(false);
chatEntry.setFilePath(null);
chatEntry.setSenderJID(mJID);
chatEntry.setReceiverJID(fJID);
chatEntry.setSenderAvatarBitmap(mAvatarBitmap);
chatEntry.setWhen(System.currentTimeMillis());
chatEntry.setMessage(message);
Log.d(LOG_TAG, "Trying to send message 2");
chatEntries.add(chatEntry);
chatAdapter.setData(chatEntries);
chatAdapter.notifyDataSetChanged();
chatListView.setSelection(chatEntries.size()-1);
Log.d(LOG_TAG, "Trying to send message 3");
} catch (XMPPException e) {
Log.e(LOG_TAG, "Unable to send message: "+e.getMessage());
}
}
}
});
// Event for chat list view
chatListView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
public void onItemClick(AdapterView<?> adapterView, View view, int position, long which) {
if ( chatEntries.get(position).isAttachedFile() ) {
File file = new File(chatEntries.get(position).getFilePath());
if ( isImageFile(file) ) {
Intent intent = new Intent();
intent.setAction(android.content.Intent.ACTION_VIEW);
intent.setDataAndType(Uri.fromFile(file), "image/*");
startActivity(intent);
} else {
Intent intent = new Intent(Intent.ACTION_VIEW);
intent.setData(Uri.fromFile(file));
startActivity(intent);
}
}
}
});
// Extras
Bundle bundle = getIntent().getExtras();
if ( bundle == null ) {
ChatActivity.this.finish();
} else {
// Get active connection
xmppConnection = MainActivity.getXMPPConnection();
if ( xmppConnection == null ) {
ChatActivity.this.finish();
} else {
// For BEEM
FileTransferNegotiator.IBB_ONLY = true;
// -- END OF FOR BEEM
// Enable Server Discovery Manager
ServiceDiscoveryManager sdm = new ServiceDiscoveryManager(xmppConnection);
// sdm.addFeature("http://jabber.org/protocol/ibb");
// FOR BEEM
sdm.addFeature("http://jabber.org/protocol/disco#info");
sdm.addFeature("http://jabber.org/protocol/disco#item");
sdm.addFeature("jabber:iq:privacy");
// -- END OF FOR BEEM
// Receive data from extras
fJID = bundle.getString("fJID");
fJID += "/"+ApplicationSetting.SERVER_RESOURCE;
fNickName = bundle.getString("fNickName");
fAvatarByte = bundle.getByteArray("fAvatarByte");
fAvatarBitmap = BitmapUtility.convertByteArrayToBitmap(fAvatarByte);
mJID = bundle.getString("mJID");
mNickName = bundle.getString("mNickName");
mAvatarByte = bundle.getByteArray("mAvatarByte");
mAvatarBitmap = BitmapUtility.convertByteArrayToBitmap(mAvatarByte);
Toast.makeText(context, "fjid is "+fJID + "mjid is "+mJID, Toast.LENGTH_LONG).show();
// Initialize
chatMessageEditText.setSingleLine(true);
chatEntries = new ArrayList<ChatEntry>();
chatAdapter = new ChatAdapter(context, chatEntries, mJID);
chatListView.setAdapter(chatAdapter);
chatListView.setDivider(null);
fileSrc = null;
rProgressBar.setMax(100);
sProgressBar.setMax(100);
sProgressBar.setClickable(false);
rProgressBar.setClickable(false);
layoutReceivingFile.setVisibility(View.GONE);
layoutSendinfFile.setVisibility(View.GONE);
// Set title for this activity
setTitle("Chat with "+fNickName);
Log.i(LOG_TAG, mNickName+" chat with "+fNickName);
// Create Chat Manager
chatManager = xmppConnection.getChatManager();
// Add Chat Listener
chatManager.addChatListener(new ChatManagerListener() {
public void chatCreated(Chat chat, boolean isCreated) {
Toast.makeText(context, "Chat was created.", Toast.LENGTH_LONG).show();
Log.i(LOG_TAG, "Chat was created.");
}
});
// Create chat channel with friend
final Handler chatHandler = new Handler() {
#Override
public void handleMessage(Message msg) {
switch ( msg.what ) {
case 1:
org.jivesoftware.smack.packet.Message chatMessage;
chatMessage = (org.jivesoftware.smack.packet.Message) msg.obj;
Toast.makeText(context, "Chat message." +msg.toString(), Toast.LENGTH_LONG).show();
ChatEntry chatEntry = new ChatEntry();
chatEntry.setAttachedFile(false);
chatEntry.setFilePath(null);
chatEntry.setSenderJID(fJID);
chatEntry.setReceiverJID(mJID);
chatEntry.setSenderAvatarBitmap(fAvatarBitmap);
chatEntry.setWhen(System.currentTimeMillis());
chatEntry.setMessage(chatMessage.getBody());
chatEntries.add(chatEntry);
chatAdapter.setData(chatEntries);
chatAdapter.notifyDataSetChanged();
chatListView.setSelection(chatEntries.size()-1);
break;
}
}
};
chat = chatManager.createChat(fJID, new MessageListener() {
public void processMessage(Chat chat, final org.jivesoftware.smack.packet.Message chatMessage) {
Toast.makeText(context, "chatManager.createChat(fJID, new MessageListener() " , Toast.LENGTH_LONG).show();
if ( chatMessage.getBody() != null ) {
new Thread() {
public void run() {
Message msg = new Message();
msg.what = 1;
msg.obj = chatMessage;
Toast.makeText(context, "Chat message.before chathandler" +msg.toString(), Toast.LENGTH_LONG).show();
chatHandler.sendMessage(msg);
};
}.start();
Log.i(LOG_TAG, "Received message from: "+chatMessage.getFrom()+": "+chatMessage.getBody());
}
}
});
// Setup file transfer manager
receiveFileManager = new FileTransferManager(xmppConnection);
sendFileManager = new FileTransferManager(xmppConnection);
// Setup default saving directory ('mychat' on sd card)
externalStorageDirectory = new File(Environment.getExternalStorageDirectory(), "mychat");
// Setup handler for receive file listener
rHandler = new Handler() {
#Override
public void handleMessage(Message msg) {
switch ( msg.what ) {
case 0:
// Finish with error
layoutReceivingFile.setVisibility(View.GONE);
Toast.makeText(context, "Unable to receive file.", Toast.LENGTH_LONG).show();
break;
case 1:
// Finish with complete
layoutReceivingFile.setVisibility(View.GONE);
Toast.makeText(context, "You have received new file.", Toast.LENGTH_LONG).show();
ChatEntry chatEntry = new ChatEntry();
chatEntry.setAttachedFile(true);
chatEntry.setFilePath(rfile.getAbsolutePath());
chatEntry.setSenderJID(fJID);
chatEntry.setReceiverJID(mJID);
chatEntry.setSenderAvatarBitmap(fAvatarBitmap);
chatEntry.setWhen(System.currentTimeMillis());
chatEntry.setMessage("You just received an attachment.");
chatEntries.add(chatEntry);
chatAdapter.setData(chatEntries);
chatAdapter.notifyDataSetChanged();
chatListView.setSelection(chatEntries.size()-1);
break;
case 2:
// Streaming
layoutReceivingFile.setVisibility(View.VISIBLE);
break;
}
}
};
// Setup receive file listener
listener = new FileTransferListener() {
public void fileTransferRequest(final FileTransferRequest request) {
Log.i(LOG_TAG, "Receive file coming");
new Thread() {
public void run() {
IncomingFileTransfer transfer = request.accept();
rfile = new File(externalStorageDirectory, transfer.getFileName());
try {
transfer.recieveFile(rfile);
Log.i(LOG_TAG, "Start receive file.");
while ( !transfer.isDone() ) {
try {
sleep(1000);
int percent = (int)(transfer.getProgress()*100);
if ( percent == 100 ) {
rProgressBar.setProgress(0);
} else {
rProgressBar.setProgress(percent);
}
Log.i(LOG_TAG, "Receiving file: "+percent+" %");
rHandler.sendEmptyMessage(2);
} catch ( InterruptedException e ) {
e.printStackTrace();
Log.e(LOG_TAG, "Receiving thread was interrupoted: "+e.getMessage());
}
}
if ( transfer.getStatus().equals(Status.complete) ) {
rHandler.sendEmptyMessage(1);
Log.i(LOG_TAG, "Receive file Completed.");
} else if ( transfer.getStatus().equals(Status.cancelled) ) {
rHandler.sendEmptyMessage(0);
Log.e(LOG_TAG, "Receive file Cancelled.");
} else if ( transfer.getStatus().equals(Status.error) ) {
rHandler.sendEmptyMessage(0);
Log.e(LOG_TAG, "Receive file Error.");
} else if ( transfer.getStatus().equals(Status.refused) ) {
rHandler.sendEmptyMessage(0);
Log.e(LOG_TAG, "Receive file Refused.");
}
} catch ( Exception e ) {
Log.e(LOG_TAG, "Unable to receive file: "+e.getMessage());
}
};
}.start();
}
};
// Add receive file listener
receiveFileManager.addFileTransferListener(listener);
}
}
}
// Send file
public void sendFile(final File file) {
sHandler = new Handler() {
#Override
public void handleMessage(Message msg) {
switch ( msg.what ) {
case 0:
// Finish with error
layoutSendinfFile.setVisibility(View.GONE);
Toast.makeText(context, "Unable to send file.", Toast.LENGTH_LONG).show();
break;
case 1:
// Finish with complete
layoutSendinfFile.setVisibility(View.GONE);
Toast.makeText(context, "Your file has been sent.", Toast.LENGTH_LONG).show();
ChatEntry chatEntry = new ChatEntry();
chatEntry.setAttachedFile(true);
chatEntry.setFilePath(fileSrc);
chatEntry.setSenderJID(mJID);
chatEntry.setReceiverJID(fJID);
chatEntry.setSenderAvatarBitmap(mAvatarBitmap);
chatEntry.setWhen(System.currentTimeMillis());
chatEntry.setMessage("Your attachment has been sent.");
chatEntries.add(chatEntry);
chatAdapter.setData(chatEntries);
chatAdapter.notifyDataSetChanged();
chatListView.setSelection(chatEntries.size()-1);
break;
case 2:
// Streaming
layoutSendinfFile.setVisibility(View.VISIBLE);
break;
}
}
};
sThread = new Thread() {
#Override
public void run() {
Log.i(LOG_TAG, "Send file coming");
OutgoingFileTransfer transfer = sendFileManager.createOutgoingFileTransfer(fJID);
try {
transfer.sendFile(file, "iChat-attachment-file");
Log.i(LOG_TAG, "Starting send file");
while ( !transfer.isDone() ) {
try {
sleep(1000);
int percent = (int)(transfer.getProgress()*100);
if ( percent == 100 ) {
sProgressBar.setProgress(0);
} else {
sProgressBar.setProgress(percent);
}
Log.i(LOG_TAG, "Sending file: "+percent+" %");
sHandler.sendEmptyMessage(2);
} catch (InterruptedException e) {
e.printStackTrace();
Log.e(LOG_TAG, "Send file thread was interrupted: "+e.getMessage());
}
}
if ( transfer.getStatus().equals(Status.complete) ) {
sHandler.sendEmptyMessage(1);
Log.i(LOG_TAG, "Send file is completed");
} else {
sHandler.sendEmptyMessage(0);
Log.e(LOG_TAG, "Send file is failed");
}
} catch (XMPPException e) {
Log.e(LOG_TAG, "Unable to send file: "+e.getMessage());
}
}
};
sThread.start();
}
#Override
protected void onActivityResult(int requestCode, int resultcode, Intent intent) {
super.onActivityResult(requestCode, resultcode, intent);
if (requestCode == REQUEST_CODE_FOR_GALLERY) {
if (intent != null) {
Cursor cursor = getContentResolver().query(intent.getData(), null, null, null, null);
cursor.moveToFirst();
int idx = cursor.getColumnIndex(ImageColumns.DATA);
fileSrc = cursor.getString(idx);
File file = new File(fileSrc);
if ( file.exists() ) {
sendFile(file);
} else {
Toast.makeText(context, "Image was not found, please try again.", Toast.LENGTH_LONG).show();
}
} else {
Toast.makeText(context, "Cancelled", Toast.LENGTH_SHORT).show();
}
} else if (requestCode == REQUEST_CODE_FOR_FILEMANAGER) {
if ( resultcode == RESULT_OK ) {
if( intent.hasExtra(FilePickerActivity.EXTRA_FILE_PATH) ) {
File file = new File(intent.getStringExtra(FilePickerActivity.EXTRA_FILE_PATH));
// Set the file path text view
if ( file.exists() && isAllowedFileExtension(file) ) {
sendFile(file);
} else {
Toast.makeText(context, "This file is not allowed, please choose another file.", Toast.LENGTH_LONG).show();
}
}
} else {
Toast.makeText(context, "Cancelled", Toast.LENGTH_SHORT).show();
}
}
}
public boolean isAllowedFileExtension(File file) {
boolean result = false;
String filename = file.getName();
int length = filename.length();
int correctPosition = 0;
String ext = "";
for ( int i = length-1; i > 0; i-- ) {
if ( filename.charAt(i) == '.' ) {
correctPosition = i;
break;
}
}
if ( correctPosition == 0 ) {
Toast.makeText(context, "This file is invalid, please choose another file.", Toast.LENGTH_LONG).show();
} else {
for ( int i = correctPosition+1; i < length; i++ ) {
ext += filename.charAt(i);
}
if ( ext.trim().length() == 0 ) {
Toast.makeText(context, "This file is invalid, please choose another file.", Toast.LENGTH_LONG).show();
} else {
boolean isAllowedExtension = false;
String[] allowedExtension = new String[] { "png", "jpg", "gif", "tif", "bmp", "doc", "docx", "ppt", "pptx", "xls", "xlsx", "pdf", "zip", "rar" };
for ( int i = 0; i < allowedExtension.length; i++ ) {
if ( ext.equalsIgnoreCase(allowedExtension[i]) ) {
isAllowedExtension = true;
}
}
if ( isAllowedExtension ) {
result = true;
}
}
}
return result;
}
public boolean isImageFile(File file) {
boolean result = false;
String filename = file.getName();
int length = filename.length();
int correctPosition = 0;
String ext = "";
for ( int i = length-1; i > 0; i-- ) {
if ( filename.charAt(i) == '.' ) {
correctPosition = i;
break;
}
}
if ( correctPosition == 0 ) {
Toast.makeText(context, "This file is invalid, please choose another file.", Toast.LENGTH_LONG).show();
} else {
for ( int i = correctPosition+1; i < length; i++ ) {
ext += filename.charAt(i);
}
if ( ext.trim().length() == 0 ) {
Toast.makeText(context, "This file is invalid, please choose another file.", Toast.LENGTH_LONG).show();
} else {
boolean isAllowedExtension = false;
String[] allowedExtension = new String[] { "png", "jpg", "gif", "tif", "bmp" };
for ( int i = 0; i < allowedExtension.length; i++ ) {
if ( ext.equalsIgnoreCase(allowedExtension[i]) ) {
isAllowedExtension = true;
}
}
if ( isAllowedExtension ) {
result = true;
}
}
}
return result;
}

delay in receiving data from Android to Arduino

I'm connecting my android device to arduino via USB and I receive data immediately from arduino by using bulkTransfer, but when I'm going to send acknowledge signal back to arduino using the same command, it receives that some seconds later.
My arduino model is DUE, and the arduino side code is:
void setup() {
// put your setup code here, to run once:
Serial.begin(9600);
pinMode(49, OUTPUT);
}
void loop() {
String a;
int sensorValue[64];
for (int i = 0; i <= 63; i++)
{
sensorValue[i] = analogRead(A0) / 4;
a = a + char(sensorValue[i]);
}
char b;
while (1) {
Serial.print(a);
Serial.flush();
delay(2);
b = Serial.read();
if (b == '1')
{
break;
}
}
digitalWrite(49, HIGH);
delay(2000);
digitalWrite(49, LOW);
}
My android side code is:
public void onClick(View v) {
synchronized (this) {
if (usbDeviceConnection != null) {
Thread myThread = new Thread(new Runnable() {
#Override
public void run() {
try {
int chunkCounter = 0;
String strTemp = null;
while (chunkCounter < 1) {
byte[] message = new byte[64];
final int result = usbDeviceConnection.bulkTransfer(endpointIN, message, 64, 10);
if (result == 64) {
for (int intTemp = 0; intTemp < 64; intTemp++) {
strTemp += String.valueOf((char) message[intTemp]);
}
byte[] ack = new byte[1];
ack[0] = 1; //1 means I've got this chunk
synchronized(this) {
int resultAck = 0;
while (resultAck <= 0) {
resultAck = usbDeviceConnection.bulkTransfer(endpointOUT, ack, 1, 10);
}
}
chunkCounter++;
if (chunkCounter == 1) {
final String strTempFinal = strTemp;
tempflag = true;
runOnUiThread(new Runnable() {
#Override
public void run() {
txtGetData.setText(strTempFinal);
}
});
}
}
}
} catch (final Exception e){
runOnUiThread(new Runnable() {
#Override
public void run() {
Toast.makeText(getApplicationContext(), e.getMessage(), Toast.LENGTH_SHORT).show();
}
});
}
}
});
myThread.start();
}
Any help would be appreciated.
thanks in advance.

Chromecast - SIGN_IN_REQUIRED

Only a small portion of my users are getting this error and I can't for the life of me figure it out. I use GooglePlayServicesUtil.isGooglePlayServicesAvailable(downloadService) to test whether or not Play Services is available, and it always returns SUCCESS. I setup the channel to connect to the Chromecast, and everything works fine up until the point where I try to use RemoteMediaPlayer.load. The result is always SIGN_IN_REQUIRED for some users, with resolution: null. The status.toString() is Failed to load: Status{statusCode=SIGN_IN_REQUIRED, resolution=null}. I'm really not sure what I am supposed to with this or how to get rid of the error for my few users who are getting this.
I don't know what portion is related, so I am just posting my entire controller class:
public class ChromeCastController extends RemoteController {
private static final String TAG = ChromeCastController.class.getSimpleName();
private CastDevice castDevice;
private GoogleApiClient apiClient;
private ConnectionCallbacks connectionCallbacks;
private ConnectionFailedListener connectionFailedListener;
private Cast.Listener castClientListener;
private boolean applicationStarted = false;
private boolean waitingForReconnect = false;
private boolean error = false;
private boolean ignoreNextPaused = false;
private String sessionId;
private FileProxy proxy;
private String rootLocation;
private RemoteMediaPlayer mediaPlayer;
private double gain = 0.5;
public ChromeCastController(DownloadService downloadService, CastDevice castDevice) {
this.downloadService = downloadService;
this.castDevice = castDevice;
SharedPreferences prefs = Util.getPreferences(downloadService);
rootLocation = prefs.getString(Constants.PREFERENCES_KEY_CACHE_LOCATION, null);
}
#Override
public void create(boolean playing, int seconds) {
downloadService.setPlayerState(PlayerState.PREPARING);
connectionCallbacks = new ConnectionCallbacks(playing, seconds);
connectionFailedListener = new ConnectionFailedListener();
castClientListener = new Cast.Listener() {
#Override
public void onApplicationStatusChanged() {
if (apiClient != null && apiClient.isConnected()) {
Log.i(TAG, "onApplicationStatusChanged: " + Cast.CastApi.getApplicationStatus(apiClient));
}
}
#Override
public void onVolumeChanged() {
if (apiClient != null && applicationStarted) {
try {
gain = Cast.CastApi.getVolume(apiClient);
} catch(Exception e) {
Log.w(TAG, "Failed to get volume");
}
}
}
#Override
public void onApplicationDisconnected(int errorCode) {
shutdownInternal();
}
};
Cast.CastOptions.Builder apiOptionsBuilder = Cast.CastOptions.builder(castDevice, castClientListener);
apiClient = new GoogleApiClient.Builder(downloadService)
.addApi(Cast.API, apiOptionsBuilder.build())
.addConnectionCallbacks(connectionCallbacks)
.addOnConnectionFailedListener(connectionFailedListener)
.build();
apiClient.connect();
}
#Override
public void start() {
if(error) {
error = false;
Log.w(TAG, "Attempting to restart song");
startSong(downloadService.getCurrentPlaying(), true, 0);
return;
}
try {
mediaPlayer.play(apiClient);
} catch(Exception e) {
Log.e(TAG, "Failed to start");
}
}
#Override
public void stop() {
try {
mediaPlayer.pause(apiClient);
} catch(Exception e) {
Log.e(TAG, "Failed to pause");
}
}
#Override
public void shutdown() {
try {
if(mediaPlayer != null && !error) {
mediaPlayer.stop(apiClient);
}
} catch(Exception e) {
Log.e(TAG, "Failed to stop mediaPlayer", e);
}
try {
if(apiClient != null) {
Cast.CastApi.stopApplication(apiClient);
Cast.CastApi.removeMessageReceivedCallbacks(apiClient, mediaPlayer.getNamespace());
mediaPlayer = null;
applicationStarted = false;
}
} catch(Exception e) {
Log.e(TAG, "Failed to shutdown application", e);
}
if(apiClient != null && apiClient.isConnected()) {
apiClient.disconnect();
}
apiClient = null;
if(proxy != null) {
proxy.stop();
proxy = null;
}
}
private void shutdownInternal() {
// This will call this.shutdown() indirectly
downloadService.setRemoteEnabled(RemoteControlState.LOCAL, null);
}
#Override
public void updatePlaylist() {
if(downloadService.getCurrentPlaying() == null) {
startSong(null, false, 0);
}
}
#Override
public void changePosition(int seconds) {
try {
mediaPlayer.seek(apiClient, seconds * 1000L);
} catch(Exception e) {
Log.e(TAG, "FAiled to seek to " + seconds);
}
}
#Override
public void changeTrack(int index, DownloadFile song) {
startSong(song, true, 0);
}
#Override
public void setVolume(boolean up) {
double delta = up ? 0.1 : -0.1;
gain += delta;
gain = Math.max(gain, 0.0);
gain = Math.min(gain, 1.0);
getVolumeToast().setVolume((float) gain);
try {
Cast.CastApi.setVolume(apiClient, gain);
} catch(Exception e) {
Log.e(TAG, "Failed to the volume");
}
}
#Override
public int getRemotePosition() {
if(mediaPlayer != null) {
return (int) (mediaPlayer.getApproximateStreamPosition() / 1000L);
} else {
return 0;
}
}
#Override
public int getRemoteDuration() {
if(mediaPlayer != null) {
return (int) (mediaPlayer.getStreamDuration() / 1000L);
} else {
return 0;
}
}
void startSong(DownloadFile currentPlaying, boolean autoStart, int position) {
if(currentPlaying == null) {
try {
if (mediaPlayer != null && !error) {
mediaPlayer.stop(apiClient);
}
} catch(Exception e) {
// Just means it didn't need to be stopped
}
downloadService.setPlayerState(PlayerState.IDLE);
return;
}
downloadService.setPlayerState(PlayerState.PREPARING);
MusicDirectory.Entry song = currentPlaying.getSong();
try {
MusicService musicService = MusicServiceFactory.getMusicService(downloadService);
String url;
// Offline, use file proxy
if(Util.isOffline(downloadService) || song.getId().indexOf(rootLocation) != -1) {
if(proxy == null) {
proxy = new FileProxy(downloadService);
proxy.start();
}
url = proxy.getPublicAddress(song.getId());
} else {
if(proxy != null) {
proxy.stop();
proxy = null;
}
if(song.isVideo()) {
url = musicService.getHlsUrl(song.getId(), currentPlaying.getBitRate(), downloadService);
} else {
url = musicService.getMusicUrl(downloadService, song, currentPlaying.getBitRate());
}
url = fixURLs(url);
}
// Setup song/video information
MediaMetadata meta = new MediaMetadata(song.isVideo() ? MediaMetadata.MEDIA_TYPE_MOVIE : MediaMetadata.MEDIA_TYPE_MUSIC_TRACK);
meta.putString(MediaMetadata.KEY_TITLE, song.getTitle());
if(song.getTrack() != null) {
meta.putInt(MediaMetadata.KEY_TRACK_NUMBER, song.getTrack());
}
if(!song.isVideo()) {
meta.putString(MediaMetadata.KEY_ARTIST, song.getArtist());
meta.putString(MediaMetadata.KEY_ALBUM_ARTIST, song.getArtist());
meta.putString(MediaMetadata.KEY_ALBUM_TITLE, song.getAlbum());
String coverArt = "";
if(proxy == null) {
coverArt = musicService.getCoverArtUrl(downloadService, song);
coverArt = fixURLs(coverArt);
meta.addImage(new WebImage(Uri.parse(coverArt)));
} else {
File coverArtFile = FileUtil.getAlbumArtFile(downloadService, song);
if(coverArtFile != null && coverArtFile.exists()) {
coverArt = proxy.getPublicAddress(coverArtFile.getPath());
meta.addImage(new WebImage(Uri.parse(coverArt)));
}
}
}
String contentType;
if(song.isVideo()) {
contentType = "application/x-mpegURL";
}
else if(song.getTranscodedContentType() != null) {
contentType = song.getTranscodedContentType();
} else if(song.getContentType() != null) {
contentType = song.getContentType();
} else {
contentType = "audio/mpeg";
}
// Load it into a MediaInfo wrapper
MediaInfo mediaInfo = new MediaInfo.Builder(url)
.setContentType(contentType)
.setStreamType(MediaInfo.STREAM_TYPE_BUFFERED)
.setMetadata(meta)
.build();
if(autoStart) {
ignoreNextPaused = true;
}
mediaPlayer.load(apiClient, mediaInfo, autoStart, position * 1000L).setResultCallback(new ResultCallback<RemoteMediaPlayer.MediaChannelResult>() {
#Override
public void onResult(RemoteMediaPlayer.MediaChannelResult result) {
if (result.getStatus().isSuccess()) {
// Handled in other handler
} else if(result.getStatus().getStatusCode() != ConnectionResult.SIGN_IN_REQUIRED) {
Log.e(TAG, "Failed to load: " + result.getStatus().toString());
failedLoad();
}
}
});
} catch (IllegalStateException e) {
Log.e(TAG, "Problem occurred with media during loading", e);
failedLoad();
} catch (Exception e) {
Log.e(TAG, "Problem opening media during loading", e);
failedLoad();
}
}
private String fixURLs(String url) {
// Only change to internal when using https
if(url.indexOf("https") != -1) {
SharedPreferences prefs = Util.getPreferences(downloadService);
int instance = prefs.getInt(Constants.PREFERENCES_KEY_SERVER_INSTANCE, 1);
String externalUrl = prefs.getString(Constants.PREFERENCES_KEY_SERVER_URL + instance, null);
String internalUrl = prefs.getString(Constants.PREFERENCES_KEY_SERVER_INTERNAL_URL + instance, null);
url = url.replace(internalUrl, externalUrl);
}
// Use separate profile for Chromecast so users can do ogg on phone, mp3 for CC
return url.replace(Constants.REST_CLIENT_ID, Constants.CHROMECAST_CLIENT_ID);
}
private void failedLoad() {
Util.toast(downloadService, downloadService.getResources().getString(R.string.download_failed_to_load));
downloadService.setPlayerState(PlayerState.STOPPED);
error = true;
}
private class ConnectionCallbacks implements GoogleApiClient.ConnectionCallbacks {
private boolean isPlaying;
private int position;
private ResultCallback<Cast.ApplicationConnectionResult> resultCallback;
ConnectionCallbacks(boolean isPlaying, int position) {
this.isPlaying = isPlaying;
this.position = position;
resultCallback = new ResultCallback<Cast.ApplicationConnectionResult>() {
#Override
public void onResult(Cast.ApplicationConnectionResult result) {
Status status = result.getStatus();
if (status.isSuccess()) {
ApplicationMetadata applicationMetadata = result.getApplicationMetadata();
sessionId = result.getSessionId();
String applicationStatus = result.getApplicationStatus();
boolean wasLaunched = result.getWasLaunched();
applicationStarted = true;
setupChannel();
} else {
shutdownInternal();
}
}
};
}
#Override
public void onConnected(Bundle connectionHint) {
if (waitingForReconnect) {
Log.i(TAG, "Reconnecting");
reconnectApplication();
} else {
launchApplication();
}
}
#Override
public void onConnectionSuspended(int cause) {
Log.w(TAG, "Connection suspended");
isPlaying = downloadService.getPlayerState() == PlayerState.STARTED;
position = getRemotePosition();
waitingForReconnect = true;
}
void launchApplication() {
try {
Cast.CastApi.launchApplication(apiClient, CastCompat.APPLICATION_ID, false).setResultCallback(resultCallback);
} catch (Exception e) {
Log.e(TAG, "Failed to launch application", e);
}
}
void reconnectApplication() {
try {
Cast.CastApi.joinApplication(apiClient, CastCompat.APPLICATION_ID, sessionId).setResultCallback(resultCallback);
} catch (Exception e) {
Log.e(TAG, "Failed to reconnect application", e);
}
}
void setupChannel() {
if(!waitingForReconnect) {
mediaPlayer = new RemoteMediaPlayer();
mediaPlayer.setOnStatusUpdatedListener(new RemoteMediaPlayer.OnStatusUpdatedListener() {
#Override
public void onStatusUpdated() {
MediaStatus mediaStatus = mediaPlayer.getMediaStatus();
if (mediaStatus == null) {
return;
}
switch (mediaStatus.getPlayerState()) {
case MediaStatus.PLAYER_STATE_PLAYING:
if (ignoreNextPaused) {
ignoreNextPaused = false;
}
downloadService.setPlayerState(PlayerState.STARTED);
break;
case MediaStatus.PLAYER_STATE_PAUSED:
if (!ignoreNextPaused) {
downloadService.setPlayerState(PlayerState.PAUSED);
}
break;
case MediaStatus.PLAYER_STATE_BUFFERING:
downloadService.setPlayerState(PlayerState.PREPARING);
break;
case MediaStatus.PLAYER_STATE_IDLE:
if (mediaStatus.getIdleReason() == MediaStatus.IDLE_REASON_FINISHED) {
downloadService.setPlayerState(PlayerState.COMPLETED);
downloadService.onSongCompleted();
} else if (mediaStatus.getIdleReason() == MediaStatus.IDLE_REASON_INTERRUPTED) {
if (downloadService.getPlayerState() != PlayerState.PREPARING) {
downloadService.setPlayerState(PlayerState.PREPARING);
}
} else if (mediaStatus.getIdleReason() == MediaStatus.IDLE_REASON_ERROR) {
Log.e(TAG, "Idle due to unknown error");
downloadService.setPlayerState(PlayerState.COMPLETED);
downloadService.next();
} else {
Log.w(TAG, "Idle reason: " + mediaStatus.getIdleReason());
downloadService.setPlayerState(PlayerState.IDLE);
}
break;
}
}
});
}
try {
Cast.CastApi.setMessageReceivedCallbacks(apiClient, mediaPlayer.getNamespace(), mediaPlayer);
} catch (IOException e) {
Log.e(TAG, "Exception while creating channel", e);
}
if(!waitingForReconnect) {
DownloadFile currentPlaying = downloadService.getCurrentPlaying();
startSong(currentPlaying, isPlaying, position);
}
if(waitingForReconnect) {
waitingForReconnect = false;
}
}
}
private class ConnectionFailedListener implements GoogleApiClient.OnConnectionFailedListener {
#Override
public void onConnectionFailed(ConnectionResult result) {
shutdownInternal();
}
}
}
Edit for logs:
03-28 19:04:49.757 6305-6305/github.daneren2005.dsub I/ChromeCastController﹕ onApplicationStatusChanged: Chromecast Home Screen
03-28 19:04:52.280 6305-6305/github.daneren2005.dsub I/ChromeCastController﹕ onApplicationStatusChanged: null
03-28 19:04:54.162 6305-6305/github.daneren2005.dsub I/ChromeCastController﹕ onApplicationStatusChanged: Ready To Cast
03-28 19:05:05.194 6305-6305/github.daneren2005.dsub E/ChromeCastController﹕ Failed to load: Status{statusCode=SIGN_IN_REQUIRED, resolution=null}
It is strange that you are getting such status code at that time. What comes to mind is that the user may have not logged into his/her gmail account or something along those lines. Do you have the log file for us to take a look at to see if we can get more from the context? Also, to be sure, such user sees the application launched on the TV and only when it comes to loading a media that error is thrown?
The issue is due to using a Self Signed Certificate. I didn't realize the issue on my old phone because I had changed hosts and bought a normal certificate after switching phones. It would be nice if the SDK would through a useful error though. The one thrown makes you think that it is a problem with connecting to the Play Services SDK, and not a problem with the actual URL being used.

Window type error

I'm creating a audio swipe card reader but I'm getting an error with windows. I can't trace what causing the error in my codes. Can anyone hel me to point what causing the error in my codes? any thought will be highly appreciated.
Here is my codes:
public class SReaderActivity extends Activity {
public final String TAG = "SReaderActivity";
Button swipe, get;// detect, stop
TextView result_text, mTitle;
private TimeCount time = null;
private AudioManager am = null;
int maxVol;
private ProgressDialog progressDialog;
private boolean mHeadsetPlugged = false;
private BroadcastReceiver mHeadsetReceiver = new BroadcastReceiver() {
#Override
public void onReceive(Context context, Intent intent) {
String action = intent.getAction();
if (action.equals(Intent.ACTION_HEADSET_PLUG)) {
boolean hasHeadset = (intent.getIntExtra("state", 0) == 1);
boolean hasMicroPhone = (intent.getIntExtra("microphone", 0) == 1);
if (hasHeadset && hasMicroPhone) {
mHeadsetPlugged = true;
} else {
mHeadsetPlugged = false;
if (sreader != null)
sreader.Stop();
handler.post(disable_button);
}
handler.post(mHeadsetPluginHandler);
}
}
};
private Handler handler = new Handler();
SReaderApi sreader = null;
private String version = null;
private String ksn = null;
private String random = null;
private String workingkey = null;
private String encryption_data = null;
private String decryption_data = null;
private String T1PAN_data = null;
private String T1Name_Exd = null;
private String T2PAN_data = null;
private String T2Exd_data = null;
private Runnable mHeadsetPluginHandler = new Runnable() {
public void run() {
String plug_str = mHeadsetPlugged ? "plugin" : "unplugin";
Toast.makeText(SReaderActivity.this, "Headset " + plug_str, Toast.LENGTH_SHORT).show();
if (sreader != null && mHeadsetPlugged == false) { // Device unplug APP close
CloseSinWave();
finish();
} else {
onDetect();
}
}
};
private Runnable disable_button = new Runnable() {
public void run() {
swipe.setEnabled(false);
get.setEnabled(false);
}
};
private Runnable enable_button = new Runnable() {
public void run() {
get.setText(R.string.get);
swipe.setClickable(true);
swipe.setEnabled(true);
swipe.setText(R.string.swipe);
}
};
private Runnable enable_get = new Runnable() {
public void run() {
get.setEnabled(true);
get.setClickable(true);
}
};
private Runnable timeout_ack = new Runnable() {
public void run() {
Toast.makeText(SReaderActivity.this, "Timeout!!!", Toast.LENGTH_SHORT).show();
}
};
private Runnable unknown_err = new Runnable() {
public void run() {
result_text.setText(R.string.unknown_error);
}
};
private Runnable detcet = new Runnable() {
public void run() {
String txt = "Detect OK\n";
result_text.setText(txt);
}
};
private Runnable display_encryptiondata = new Runnable() {
public void run() {
String txt = "Encryption data\n";
txt += encryption_data + "\n\n\n";
result_text.setText(txt);
}
};
private Runnable display_decryptiondata = new Runnable() {
public void run() {
String txt = "Encryption data\n";
txt += encryption_data + "\n\n\nDecryption data\n";
txt += decryption_data + "\n";
result_text.setText(txt);
}
};
private Runnable display_get_data = new Runnable() {
public void run() {
String txt = "Decryption data\n";
txt += decryption_data + "\n\n\n\n";
txt += "T1PAN:" + T1PAN_data + "\n";
txt += "T1Name_Exd:" + T1Name_Exd + "\n";
txt += "T2PAN:" + T2PAN_data + "\n";
txt += "T2Exd:" + T2Exd_data + "\n";
result_text.setText(txt);
}
};
private Runnable clear_all = new Runnable() {
public void run() {
encryption_data = "";
decryption_data = "";
T1PAN_data = "";
T1Name_Exd = "";
T2PAN_data = "";
T2Exd_data = "";
result_text.setText("");
}
};
private Runnable clear_encryption = new Runnable() {
public void run() {
encryption_data = "";
decryption_data = "";
T1PAN_data = "";
T1Name_Exd = "";
T2PAN_data = "";
T2Exd_data = "";
result_text.setText("");
}
};
private Runnable clear_carddata = new Runnable() {
public void run() {
encryption_data = "";
T1PAN_data = "";
T1Name_Exd = "";
T2PAN_data = "";
T2Exd_data = "";
result_text.setText("");
}
};
private Runnable settext_swpie = new Runnable() {
public void run() {
swipe.setClickable(true);
swipe.setText(R.string.swipe);
}
};
private Runnable begin_get = new Runnable() {
public void run() {
myToast = new MyToast(SReaderActivity.this, "get T1&T2 Data...");
myToast.show();
}
};
private Runnable settext_get = new Runnable() {
public void run() {
get.setClickable(true);
get.setText(R.string.get);
}
};
public class MyToast {
private Context mContext = null;
private Toast mToast = null;
private Handler mHandler = null;
private Runnable mToastThread = new Runnable() {
public void run() {
mToast.show();
mHandler.postDelayed(mToastThread, 3000);
}
};
public MyToast(Context context, String txt) {
mContext = context;
mHandler = new Handler(mContext.getMainLooper());
mToast = Toast.makeText(mContext, txt, Toast.LENGTH_LONG);
}
public void setText(String text) {
mToast.setText(text);
}
public void show() {
mHandler.post(mToastThread);
}
public void cancel() {
mHandler.removeCallbacks(mToastThread);
mToast.cancel();
}
}
private MyToast myToast = null;
class TimeCount extends CountDownTimer {
int id;
public TimeCount(int id, long millisInFuture, long countDownInterval) {
super(millisInFuture, countDownInterval);// ²ÎÊýÒÀ´ÎΪ×Üʱ³¤,ºÍ¼ÆʱµÄʱ¼ä¼ä¸ô
this.id = id;
}
#Override
public void onFinish() {// ¼ÆʱÍê±Ïʱ´¥·¢
if (id == R.id.swipe) {
swipe.setText(R.string.reswipe);
swipe.setClickable(true);
}
else if (id == R.id.get) {
get.setText(R.string.get);
get.setClickable(true);
}
}
#Override
public void onTick(long millisUntilFinished) {// ¼Æʱ¹ý³ÌÏÔʾ
CharSequence str = getString(R.string.second);
if (id == R.id.swipe) {
swipe.setClickable(false);
}
else if (id == R.id.get) {
get.setClickable(false);
}
}
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
requestWindowFeature(Window.FEATURE_CUSTOM_TITLE);
setContentView(R.layout.swipe);
getWindow().setFeatureInt(Window.FEATURE_CUSTOM_TITLE, R.layout.title);
mTitle = (TextView) findViewById(R.id.title_left_text);
mTitle.setText(R.string.version_name);
am = (AudioManager) getSystemService(Context.AUDIO_SERVICE);
IntentFilter iFilter = new IntentFilter();
iFilter.addAction(Intent.ACTION_HEADSET_PLUG);
iFilter.addCategory(Intent.CATEGORY_DEFAULT);
registerReceiver(mHeadsetReceiver, iFilter);
swipe = (Button) this.findViewById(R.id.swipe);
swipe.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
onSwipe();
}
});
get = (Button) this.findViewById(R.id.get);
get.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
onGet();
}
});
result_text = (TextView) this.findViewById(R.id.result);
swipe.setEnabled(false);
get.setEnabled(false);
setVolumeControlStream(AudioManager.STREAM_MUSIC);
maxVol = am.getStreamMaxVolume(AudioManager.STREAM_MUSIC);
am.setStreamVolume(AudioManager.STREAM_MUSIC, maxVol, 0);
}
public void onDestroy() {
unregisterReceiver(mHeadsetReceiver);
super.onDestroy();
}
public boolean onKeyDown(int keyCode, KeyEvent event) {
switch (keyCode) {
case KeyEvent.KEYCODE_MENU: {
openOptionsDialog();
return true;
}
case KeyEvent.KEYCODE_BACK: { // Log.WritetoFile();
if (sreader != null) {
sreader.Stop();
sreader = null;
if (myToast != null)
myToast.cancel();
finish();
System.exit(0);
return true;
}
}
}
return super.onKeyDown(keyCode, event);
}
public void onUserLeaveHint() { // this only executes when Home is selected.
// do stuff
super.onUserLeaveHint();
if (sreader != null) {
sreader.Stop();
sreader = null;
if (myToast != null)
myToast.cancel();
finish();
System.exit(0);
}
}
public void onAttachedToWindow() {
super.onAttachedToWindow();
this.getWindow().setType(WindowManager.LayoutParams.TYPE_KEYGUARD);
}
private void openOptionsDialog() {
AlertDialog.Builder dialog = new AlertDialog.Builder(SReaderActivity.this);
dialog.setTitle("SS505 sReader");
dialog.setMessage("Magnetic Card Reader APP");
dialog.setNegativeButton("OK", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
dialog.dismiss();
}
});
dialog.show();
}
private void onSwipe() {
if (sreader == null)
return;
progressDialog = ProgressDialog.show(this, "Loadding Key", "Please wait swipe card ...", true, false);
time = new TimeCount(R.id.swipe, 15000, 1000);
time.start();// ¿ªÊ¼¼Æʱ
swipe.setEnabled(false);
get.setEnabled(false);
new Thread() {
public void run() {
String data = null;
decryption_data = null;
encryption_data = null;
handler.post(clear_encryption);
try {
random = sreader.GetRandom(10000);
if (random == null) {
progressDialog.dismiss();
String err = sreader.GetErrorString();
if (err.equalsIgnoreCase("cancel all"))
return;
}
workingkey = sreader.GenerateWorkingKey(random, ksn);
progressDialog.dismiss();
data = sreader.ReadCard(15000);
} catch (Exception ex) {
progressDialog.dismiss();
if (ex instanceof TimeoutException) {
time.cancel();
sreader.Cancel();
handler.post(enable_button);
handler.post(timeout_ack);
return;
} else
handler.post(unknown_err);
CloseSinWave();
}
time.cancel();
if (data == null) {
encryption_data = sreader.GetErrorString();
if (encryption_data.equalsIgnoreCase("cancel all"))
return;
handler.post(display_encryptiondata);
} else {
encryption_data = "\n" + data;
handler.post(display_encryptiondata);
String d_str = sreader.TriDesDecryption(workingkey, data);
if (d_str != null) {
if (false == d_str.startsWith("A1")) {
return;
}
int index2 = FindSplitCharIndex(d_str, "A2", 2);
int index3 = FindSplitCharIndex(d_str, "A3", index2 + 2);
if (index2 < 0 || index3 < 0) {
return;
}
String t1 = d_str.substring(2, index2);
String t2 = d_str.substring(index2 + 2, index3);
String t3 = d_str.substring(index3 + 2);
String ex_msg = "";
if (t1.equals(""))
decryption_data = "\nT1=" + "T1 Empty";
else
decryption_data = "\nT1=" + changeHexString2CharString(t1);
if (t2.equals(""))
decryption_data += "\nT2=" + "T2 Empty";
else {
String e2 = changeHexString2CharString(t2);
if (e2.length() < 24 || e2.length() > 40)
ex_msg = "\nTrack2 " + getResources().getText(R.string.de_len) + e2.length() + "byte";
decryption_data += "\nT2=" + e2;
}
if (t3.equals(""))
decryption_data += "\nT3=" + "T3 Empty";
else
decryption_data += "\nT3=" + changeHexString2CharString(t3) + ex_msg;
handler.post(display_decryptiondata);
}
}
handler.post(enable_button);
handler.post(settext_swpie);
handler.post(enable_get);
}
}.start();
}
private int FindSplitCharIndex(String str, String split, int start) {
int i = start;
while (i < str.length() && i + 1 < str.length()) {
String e = str.substring(i, i + 2);
if (e.equals(split)) {
return i;
}
i += 2;
}
return -1;
}
private String changeHexString2CharString(String e) {
String char_txt = "";
for (int i = 0; i < e.length(); i = i + 2) {
String c = e.substring(i, i + 2);
char j = (char) Integer.parseInt(c, 16);
char_txt += j;
}
return char_txt;
}
private boolean Detect_sReader() {
mHeadsetPlugged = HeadSetUtils.checkHeadset();
if (!mHeadsetPlugged) {
result_text.setText(R.string.nodevice);
}
return mHeadsetPlugged;
}
private boolean GenerateSinWave() {
sreader = SReaderApi.getSreaderInstance();
if (sreader.Init() == true) {
sreader.Start();
am.setMode(AudioManager.MODE_NORMAL);
return true;
}
return false;
}
private void CloseSinWave() {
if (sreader != null)
sreader.Stop();
}
private void Initialization() {
swipe.setEnabled(false);
progressDialog = ProgressDialog.show(this, "", "Card Reader Detecting...", true, false);
new Thread() {
public void run() {
int i = 0;
try {
int j = 1;
boolean s_init = false;
while (j < 5) {
try {
s_init = sreader.Initial(2500);
if (s_init)
break;
} catch (Exception ex) {
if (ex instanceof TimeoutException) {
if (j == 4) {
handler.post(timeout_ack);
} else
sleep(1000);
} else {
handler.post(unknown_err);
break;
}
}
j++;
}
if (!s_init) {
CloseSinWave();
progressDialog.dismiss();
return;
}
i++;
ksn = sreader.GetKSN(5000);
if (ksn == null) {
String err = sreader.GetErrorString();
if (err.equalsIgnoreCase("cancel all"))
return;
throw new Exception("ksn is null");
}
handler.post(enable_button);
handler.post(detcet);
progressDialog.dismiss();
} catch (Exception ex) {
progressDialog.dismiss();
if (ex instanceof TimeoutException) {
handler.post(timeout_ack);
} else
handler.post(unknown_err);
CloseSinWave();
}
}
}.start();
}
private void onGet() {
if (sreader == null)
return;
time = new TimeCount(R.id.get, 10000, 1000);
time.start();// ¿ªÊ¼¼Æʱ
get.setEnabled(false);
swipe.setEnabled(false);
handler.post(begin_get);
new Thread() {
public void run() {
String Empty = "Empty";
int i = 0;
handler.post(clear_carddata);
try {
T1PAN_data = sreader.GetT1PAN(5000);
if (T1PAN_data == null) {
T1PAN_data = Empty;
} else {
T1PAN_data = changeHexString2CharString(T1PAN_data);
}
i++;
T1Name_Exd = sreader.GetT1HolderName_Exd(5000);
if (T1Name_Exd == null) {
T1Name_Exd = Empty;
} else {
T1Name_Exd = changeHexString2CharString(T1Name_Exd);
}
i++;
T2PAN_data = sreader.GetT2PAN(5000);
if (T2PAN_data == null) {
T2PAN_data = Empty;
} else {
T2PAN_data = changeHexString2CharString(T2PAN_data);
}
i++;
T2Exd_data = sreader.GetT2Exd(5000);
if (T2Exd_data == null) {
T2Exd_data = Empty;
} else {
T2Exd_data = changeHexString2CharString(T2Exd_data);
}
handler.post(display_get_data);
} catch (Exception ex) {
if (ex instanceof TimeoutException) {
time.cancel();
myToast.cancel();
sreader.Cancel();
handler.post(enable_button);
handler.post(timeout_ack);
return;
} else
handler.post(unknown_err);
CloseSinWave();
}
myToast.cancel();
time.cancel();
handler.post(settext_get);
handler.post(enable_button);
}
}.start();
}
private void onDetect() {
am.setStreamVolume(AudioManager.STREAM_MUSIC, maxVol, 0);
if (Detect_sReader() == true) {
handler.post(clear_all);
if (GenerateSinWave() == true) {
Initialization();
}
}
}
}
Here is the Log cat:
05-20 16:26:30.638: E/AndroidRuntime(1497): FATAL EXCEPTION: main
05-20 16:26:30.638: E/AndroidRuntime(1497): java.lang.IllegalArgumentException: Window type can not be changed after the window is added.
05-20 16:26:30.638: E/AndroidRuntime(1497): at android.os.Parcel.readException(Parcel.java:1429)
05-20 16:26:30.638: E/AndroidRuntime(1497): at android.os.Parcel.readException(Parcel.java:1379)
05-20 16:26:30.638: E/AndroidRuntime(1497): at android.view.IWindowSession$Stub$Proxy.relayout(IWindowSession.java:634)
05-20 16:26:30.638: E/AndroidRuntime(1497): at android.view.ViewRootImpl.relayoutWindow(ViewRootImpl.java:3835)
05-20 16:26:30.638: E/AndroidRuntime(1497): at android.view.ViewRootImpl.performTraversals(ViewRootImpl.java:1384)
05-20 16:26:30.638: E/AndroidRuntime(1497): at android.view.ViewRootImpl.doTraversal(ViewRootImpl.java:998)
05-20 16:26:30.638: E/AndroidRuntime(1497): at android.view.ViewRootImpl$TraversalRunnable.run(ViewRootImpl.java:4212)
05-20 16:26:30.638: E/AndroidRuntime(1497): at android.view.Choreographer$CallbackRecord.run(Choreographer.java:725)
05-20 16:26:30.638: E/AndroidRuntime(1497): at android.view.Choreographer.doCallbacks(Choreographer.java:555)
05-20 16:26:30.638: E/AndroidRuntime(1497): at android.view.Choreographer.doFrame(Choreographer.java:525)
Problem seems to be in onAttachedToWindow(). Change the function as below and give it a try.
public void onAttachedToWindow() {
this.getWindow().setType(WindowManager.LayoutParams.TYPE_KEYGUARD);
super.onAttachedToWindow();
}
your targetSdk must be less than 14.
try setting it to 13
Check this Answer. And it works for me.

Categories

Resources