Check the connected bluetooth devices status - java

How to know whether a Bluetooth device is still connected to a laptop or not before passing data? I wrote a java program using blue-cove lib to discover and pass the data through the laptop. After passing data for the first time, how can I check whether the device is still connected to laptop before passing data in the next time ?
I saw a similar question like this. But they have asked how to check the Bluetooth device status connected to the android.

You can follow a serie of steps and create an async task to verify the connection while is searching and sharing files between devices.
The functions deviceDiscovered() and inquiryCompleted() are the ones exeuted when a device is found and when the inquiry is finished.
If the device is disconnected, you would get a notify from the method inqueryCompleted and Handle it in the line:
try {
synchronized(lock){
lock.wait();
}
}
catch (InterruptedException e) {
e.printStackTrace();
}
In the InterruptedException you can handle the error.
package bt;
import java.io.OutputStream;
import java.util.ArrayList;
import javax.bluetooth.DataElement;
import javax.bluetooth.DeviceClass;
import javax.bluetooth.DiscoveryAgent;
import javax.bluetooth.DiscoveryListener;
import javax.bluetooth.LocalDevice;
import javax.bluetooth.RemoteDevice;
import javax.bluetooth.ServiceRecord;
import javax.bluetooth.UUID;
import javax.microedition.io.Connector;
import javax.obex.ClientSession;
import javax.obex.HeaderSet;
import javax.obex.Operation;
import javax.obex.ResponseCodes;
import bt.BTListener.MyDeviceListenerFilter;
public class MyDiscoveryListener implements DiscoveryListener{
private static Object lock=new Object();
public ArrayList<RemoteDevice> devices;
public MyDiscoveryListener() {
devices = new ArrayList<RemoteDevice>();
}
public static void main(String[] args) {
MyDiscoveryListener listener = new MyDiscoveryListener();
try{
LocalDevice localDevice = LocalDevice.getLocalDevice();
DiscoveryAgent agent = localDevice.getDiscoveryAgent();
agent.startInquiry(DiscoveryAgent.GIAC, listener);
try {
synchronized(lock){
lock.wait();
}
}
catch (InterruptedException e) {
e.printStackTrace();
return;
}
System.out.println("Device Inquiry Completed. ");
UUID[] uuidSet = new UUID[1];
uuidSet[0]=new UUID(0x1105); //OBEX Object Push service
int[] attrIDs = new int[] {
0x0100 // Service name
};
for (RemoteDevice device : listener.devices) {
agent.searchServices(
attrIDs,uuidSet,device,listener);
try {
synchronized(lock){
lock.wait();
}
}
catch (InterruptedException e) {
e.printStackTrace();
return;
}
System.out.println("Service search finished.");
}
} catch (Exception e) {
e.printStackTrace();
}
}
#Override
public void deviceDiscovered(RemoteDevice btDevice, DeviceClass arg1) {
String name;
try {
name = btDevice.getFriendlyName(false);
} catch (Exception e) {
name = btDevice.getBluetoothAddress();
}
devices.add(btDevice);
System.out.println("device found: " + name);
}
#Override
public void inquiryCompleted(int arg0) {
synchronized(lock){
lock.notify();
}
}
#Override
public void serviceSearchCompleted(int arg0, int arg1) {
synchronized (lock) {
lock.notify();
}
}
#Override
public void servicesDiscovered(int transID, ServiceRecord[] servRecord) {
for (int i = 0; i < servRecord.length; i++) {
String url = servRecord[i].getConnectionURL(ServiceRecord.NOAUTHENTICATE_NOENCRYPT, false);
if (url == null) {
continue;
}
DataElement serviceName = servRecord[i].getAttributeValue(0x0100);
if (serviceName != null) {
System.out.println("service " + serviceName.getValue() + " found " + url);
if(serviceName.getValue().equals("OBEX Object Push")){
sendMessageToDevice(url);
}
} else {
System.out.println("service found " + url);
}
}
}
private static void sendMessageToDevice(String serverURL){
try{
System.out.println("Connecting to " + serverURL);
ClientSession clientSession = (ClientSession) Connector.open(serverURL);
HeaderSet hsConnectReply = clientSession.connect(null);
if (hsConnectReply.getResponseCode() != ResponseCodes.OBEX_HTTP_OK) {
System.out.println("Failed to connect");
return;
}
HeaderSet hsOperation = clientSession.createHeaderSet();
hsOperation.setHeader(HeaderSet.NAME, "Hello.txt");
hsOperation.setHeader(HeaderSet.TYPE, "text");
//Create PUT Operation
Operation putOperation = clientSession.put(hsOperation);
// Send some text to server
byte data[] = "Hello World !!!".getBytes("iso-8859-1");
OutputStream os = putOperation.openOutputStream();
os.write(data);
os.close();
putOperation.close();
clientSession.disconnect(null);
clientSession.close();
}
catch (Exception e) {
e.printStackTrace();
}
}
}

Related

How to add user to SignalR Group in Android

i wanna add user to signalR group but it says failed.
my android code to add user in group as below
HubConnection connection = new HubConnection("http://www.planetskool.in/");
HubProxy proxy = connection.createHubProxy("ChatHub");
try {
//Log.d(TAG, "connection.start()...");
SignalRFuture<Void> awaitConnection = connection.start();
// Log.d(TAG, "started");
awaitConnection.get();
// Log.d(TAG, "got");
} catch (InterruptedException e) {
/// Log.e(TAG,"InterruptedException");
e.printStackTrace();
} catch (ExecutionException e) {
//Log.e(TAG, "ExecutionException");
e.printStackTrace();
}
SignalRFuture<Void> isGroupCreated2 = proxy.invoke("JoinGroup", loginUserInfoId);
Log.d("isGroupCreated", "isGroupCreated2 = " + proxy.invoke("JoinGroup", loginUserInfoId).isDone());
proxy.on("broadcastMessage",
new SubscriptionHandler1<String>() {
#Override
public void run(final String status) {
//getApplicationContext().runOnUiThread(new Runnable() {
//public void run() {
Log.d("SignalRResult=", status);
if(status.toUpperCase().equals("False".toUpperCase())) {
new SyncMessageFromServer().execute();
}
else {
new SyncGroupMessageFromServer().execute();
}
// }
//});
}
}
, String.class);
and the code in ChatHub in MVC Web Application is
public Task JoinGroup(string groupName)
{
return Groups.Add(Context.ConnectionId, groupName);
}
public void SendAll(string rUId, string message)
{
Clients.Group(rUId).broadcastMessage(message);
}
How can i make it work to send notification to particular user

Checking a wallet's balance (bitcoinj)

I am trying to create a p2p android wallet for bitcoin using bitcoinj.
I created an address and added it as a wachedAddress in the wallet.
When I add some coins from http://tpfaucet.appspot.com/ my listener shows me that 0.02 coins have been added to my address but when I try to see the balance in my app is shows me 0 BTC. What am I missing?
Here is the code of my listener:
public class WalletListener extends AbstractWalletEventListener {
public static final String TAG = "WalletListener";
private WalletState walletState;
private Wallet wallet;
#Override
public void onCoinsReceived(Wallet wallet, Transaction tx, Coin prevBalance, Coin newBalance) {
Log.d(TAG, "-----> coins resceived: " + tx.getHashAsString());
Log.d(TAG, "received: " + tx.getValue(wallet));
walletState = WalletState.getInstantce();
wallet = walletState.getReadyWallet();
Log.d(TAG, "The balance is: " + wallet.getBalance().toFriendlyString());
}
}
and here is the code for my WalletState class
package com.tools;
import android.os.AsyncTask;
import android.util.Log;
import com.google.common.util.concurrent.FutureCallback;
import com.google.common.util.concurrent.Futures;
import com.mybitcoinwallet.WalletActivity;
import com.mybitcoinwallet.adapter.MyPagerAdapter;
import com.mybitcoinwallet.fragment.WalletFragment;
import com.mybitcoinwallet.listeners.WalletListener;
import org.bitcoinj.core.Address;
import org.bitcoinj.core.BlockChain;
import org.bitcoinj.core.CheckpointManager;
import org.bitcoinj.core.Coin;
import org.bitcoinj.core.ECKey;
import org.bitcoinj.core.InsufficientMoneyException;
import org.bitcoinj.core.NetworkParameters;
import org.bitcoinj.core.PeerGroup;
import org.bitcoinj.core.ScriptException;
import org.bitcoinj.core.Transaction;
import org.bitcoinj.core.TransactionInput;
import org.bitcoinj.core.Wallet;
import org.bitcoinj.crypto.KeyCrypterException;
import org.bitcoinj.net.discovery.DnsDiscovery;
import org.bitcoinj.params.TestNet3Params;
import org.bitcoinj.store.BlockStore;
import org.bitcoinj.store.SPVBlockStore;
import org.bitcoinj.store.UnreadableWalletException;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
/**
* Created by Mihail on 5/23/15.
*/
public class WalletState {
public static final String TAG = "WalletState";
private NetworkParameters network = TestNet3Params.get();
private Wallet wallet;
private Address address;
private MyPagerAdapter pagerAdapter;
private static WalletState walletState;
private PeerGroup peerGroup;
private BlockStore blockStore;
private File walletFile;
private WalletState() {
}
public void initiate() {
new BackgroundTask().execute();
}
public static WalletState getInstantce() {
if (walletState == null) {
walletState = new WalletState();
}
return walletState;
}
public static Wallet getWallet(NetworkParameters netParams) {
File walletFile = new File(WalletActivity.getMainActivity().getFilesDir().getPath().toString()
+ "my_wallet_file");
Log.i(TAG, WalletActivity.getMainActivity().getFilesDir().getPath().toString()
+ "my_wallet_file");
Wallet wallet;
try {
wallet = Wallet.loadFromFile(walletFile);
} catch (UnreadableWalletException e) {
wallet = new Wallet(netParams);
ECKey key = new ECKey();
wallet.addKey(key);
try {
wallet.saveToFile(walletFile);
} catch (IOException a) {
Log.e(TAG, "Caught IOException: ", a);
}
}
return wallet;
}
public class BackgroundTask extends AsyncTask {
public static final String TAG = "BackgroundTask";
#Override
protected Object doInBackground(Object[] params) {
try {
Log.d(TAG, "Started");
wallet = getWallet(network);
wallet.addEventListener(new WalletListener());
ECKey key = wallet.getImportedKeys().iterator().next();
File file = new File(WalletActivity.getMainActivity().getFilesDir().getPath()
+ "my_wallet_file" + ".spvchain");
boolean chainExistedAlready = file.exists();
blockStore = new SPVBlockStore(network, file);
if (!chainExistedAlready) {
File checkpointsFile = new File("checkpoints");
if (checkpointsFile.exists()) {
FileInputStream stream = new FileInputStream(checkpointsFile);
CheckpointManager.checkpoint(network, stream, blockStore, key.getCreationTimeSeconds());
}
}
BlockChain chain = new BlockChain(network, wallet, blockStore);
// Connect to the localhost node. One minute timeout since we won't try any other peers
Log.i(TAG, "Connecting ...");
peerGroup = new PeerGroup(network, chain);
peerGroup.setUserAgent("PingService", "1.0");
peerGroup.addPeerDiscovery(new DnsDiscovery(network));
peerGroup.addWallet(wallet);
peerGroup.startAsync();
peerGroup.awaitRunning();
Log.i(TAG, "Peers are fully synchronized! ");
address = wallet.currentReceiveAddress();
Log.i(TAG, "currentReceiveAddress: " + address);
wallet.addWatchedAddress(address);
ECKey ecKey = wallet.currentReceiveKey();
// Making sure that everything is shut down cleanly!
Runtime.getRuntime().addShutdownHook(new Thread() {
#Override
public void run() {
try {
System.out.print("Shutting down ... ");
peerGroup.stopAsync();
peerGroup.awaitTerminated();
wallet.saveToFile(walletFile);
blockStore.close();
System.out.print("done ");
} catch (Exception e) {
throw new RuntimeException(e);
}
}
});
} catch (Exception e) {
Log.e(TAG, "AAAAAA Exception!!!!!!", e);
}
return null;
}
#Override
protected void onPostExecute(Object o) {
Log.i(TAG, "onPostExecute! finally and the Key is: " + address.toString());
pagerAdapter = WalletActivity.getMainActivity().getPagerAdapter();
WalletFragment fragment = pagerAdapter.getFragment();
fragment.setmTextView(address.toString());
Coin balance = wallet.getBalance();
fragment.setBalanceText(balance.toFriendlyString());
Log.i(TAG, "The balance is " + balance.toFriendlyString());
fragment.setWallet_progressBar_visibility();
}
}
public void sendCoins(final Wallet wallet, Transaction tx) {
// It's impossible to pick one specific identity that you receive coins from in Bitcoin as there
// could be inputs from many addresses. So instead we just pick the first and assume they were all
// owned by the same person.
try {
Coin value = tx.getValueSentToMe(wallet);
TransactionInput input = tx.getInputs().get(0);
Address from = input.getFromAddress();
final Wallet.SendResult sendResult = wallet.sendCoins(peerGroup, from, value);
System.out.println("Sending ...");
Futures.addCallback(sendResult.broadcastComplete, new FutureCallback<Transaction>() {
public void onSuccess(Transaction transaction) {
System.out.println("Sent coins back! Transaction hash is " + sendResult.tx.getHashAsString());
// The wallet has changed now, it'll get auto saved shortly or when the app shuts down.
}
public void onFailure(Throwable throwable) {
System.err.println("Failed to send coins :(");
throwable.printStackTrace();
}
});
} catch (ScriptException e) {
// If we didn't understand the scriptSig, just crash.
throw new RuntimeException(e);
} catch (KeyCrypterException e) {
e.printStackTrace();
throw new RuntimeException(e);
} catch (InsufficientMoneyException e) {
e.printStackTrace();
}
}
public Wallet getReadyWallet() {
if (wallet != null) {
Log.i(TAG, "The ready wallet was returned");
return wallet;
}
return getWallet(network);
}
}

java.io.IOException: bt socket closed, read return: -1

As i am working on OBD Reader Demo .Through my app i am trying to connect obd reader device and my app is installed in Nexus 7.OBD Reader device is connecting to other apps which is available on google play but if i am connecting with my app it is getting error java.io.IOException: bt socket closed, read return: -1 after connection establish .Any suggestions...
=========================================================
**MainActivity:-**
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.lang.reflect.Method;
import java.util.ArrayList;
import java.util.Set;
import java.util.UUID;
import android.annotation.SuppressLint;
import android.app.AlertDialog;
import android.bluetooth.BluetoothAdapter;
import android.bluetooth.BluetoothDevice;
import android.bluetooth.BluetoothSocket;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import android.util.Log;
import android.view.Menu;
import android.view.View;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;
import com.virgosys.demo.commands.SpeedObdCommand;
import com.virgosys.demo.commands.engine.EngineRPMObdCommand;
import com.virgosys.demo.commands.fuel.FindFuelTypeObdCommand;
public class MainActivity extends Bluetooth {
#SuppressWarnings("unused")
private Button On, Off, Visible, list;
private BluetoothAdapter BA;
private Set<BluetoothDevice> pairedDevices;
#SuppressWarnings("unused")
private ListView lv;
private BluetoothDevice device;
// private UUID uuid;
// private BluetoothSocketWrapper bluetoothSocket;
private BluetoothSocket socket;
private String deviceAddress;
String RPM, Speed, FuelType;
private TextView uuidTextView, deviceTextView, showRpm, showSpeed,
showFuelType, tv_connection_e, tv_connection_f;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
showRpm = ((TextView) findViewById(R.id.show_rpm));
showSpeed = ((TextView) findViewById(R.id.txt_speed));
showFuelType = ((TextView) findViewById(R.id.txt_fueltype));
uuidTextView = ((TextView) findViewById(R.id.txt_uuid));
deviceTextView = ((TextView) findViewById(R.id.txt_device));
// tv_connection_e = ((TextView) findViewById(R.id.txt_device));
// tv_connection_f = ((TextView) findViewById(R.id.show_error));
On = (Button) findViewById(R.id.button1);
Off = (Button) findViewById(R.id.button2);
Visible = (Button) findViewById(R.id.button3);
list = (Button) findViewById(R.id.button4);
lv = (ListView) findViewById(R.id.listView1);
BA = BluetoothAdapter.getDefaultAdapter();
try {
Process process = Runtime.getRuntime().exec("logcat -d");
BufferedReader bufferedReader = new BufferedReader(
new InputStreamReader(process.getInputStream()));
StringBuilder log = new StringBuilder();
String line = "";
while ((line = bufferedReader.readLine()) != null) {
log.append(line);
}
TextView tv_connection_e = (TextView) findViewById(R.id.show_error);
tv_connection_e.setText(log.toString());
} catch (IOException e) {
}
}
public void on(View view) {
if (!BA.isEnabled()) {
Intent turnOn = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);
startActivityForResult(turnOn, 0);
Toast.makeText(getApplicationContext(), "Turned on",
Toast.LENGTH_LONG).show();
} else {
Toast.makeText(getApplicationContext(), "Already on",
Toast.LENGTH_LONG).show();
}
}
#SuppressWarnings("unchecked")
public void list(View view) {
ArrayList deviceStrs = new ArrayList();
final ArrayList devices = new ArrayList();
BluetoothAdapter btAdapter = BluetoothAdapter.getDefaultAdapter();
pairedDevices = btAdapter.getBondedDevices();
if (pairedDevices.size() > 0) {
for (BluetoothDevice device : pairedDevices) {
deviceStrs.add(device.getName() + "\n" + device.getAddress());
devices.add(device.getAddress());
}
}
// show list
final AlertDialog.Builder alertDialog = new AlertDialog.Builder(this);
ArrayAdapter adapter = new ArrayAdapter(this,
android.R.layout.select_dialog_singlechoice,
deviceStrs.toArray(new String[deviceStrs.size()]));
alertDialog.setSingleChoiceItems(adapter, -1,
new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
dialog.dismiss();
int position = ((AlertDialog) dialog).getListView()
.getCheckedItemPosition();
deviceAddress = (String) devices.get(position);
System.out.println("Device Address-->" + deviceAddress);
/*
* Intent i = new Intent(MainActivity.this,
* SecondActivity.class); i.putExtra("uuid",
* "00001101-0000-1000-8000-00805F9B34FB");
* i.putExtra("deviceAddress", deviceAddress);
* i.putExtra("RPM", RPM); i.putExtra("Speed", Speed);
* startActivity(i);
*/
try {
dothings();
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
// save deviceAddress
}
});
alertDialog.setTitle("Choose Bluetooth device");
alertDialog.show();
}
#SuppressLint("NewApi")
protected void dothings() throws InterruptedException {
System.out.println("Inside Do things");
System.out.println("Device address in Do things -->" + deviceAddress);
device = BA.getRemoteDevice(deviceAddress);
// UUID SERIAL_UUID = device.getUuids()[0].getUuid();
// uuid = UUID.fromString("00001101-0000-1000-8000-00805F9B34FB");
System.out.println("Device Name-->" + device.getName());
System.out.println("Device Address-->" + device.getAddress());
System.out.println("Device Bond State-->" + device.getBondState());
System.out.println("Device Type-->" + device.getType());
System.out.println("Device UUIDS-->" + device.getUuids());
ConnectThread t = new ConnectThread(device);
t.start();
showRpm.setText(RPM);
showSpeed.setText(Speed);
showFuelType.setText(FuelType);
uuidTextView.setText("00001101-0000-1000-8000-00805F9B34FB");
deviceTextView.setText(deviceAddress);
}
public void off(View view) {
BA.disable();
Toast.makeText(getApplicationContext(), "Turned off", Toast.LENGTH_LONG)
.show();
}
public void visible(View view) {
Intent getVisible = new Intent(
BluetoothAdapter.ACTION_REQUEST_DISCOVERABLE);
startActivityForResult(getVisible, 0);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
private class ConnectThread extends Thread {
private final BluetoothSocket mmSocket;
private final UUID WELL_KNOWN_UUID = UUID
.fromString("00001101-0000-1000-8000-00805f9b34fb");
private Object e;
public ConnectThread(BluetoothDevice device) {
// Use a temporary object that is later assigned to mmSocket,because
// mmSocket is final
BluetoothSocket tmp = null;
// Get a BluetoothSocket to connect with the given BluetoothDevice
try {
tmp = device.createRfcommSocketToServiceRecord(WELL_KNOWN_UUID);
// This is the trick
Method m = device.getClass().getMethod("createRfcommSocket",
new Class[] { int.class });
tmp = (BluetoothSocket) m.invoke(device, 1);
} catch (Exception e) {
e.printStackTrace();
}
mmSocket = tmp;
}
public void run() {
System.out.println("Trying to connect...");
// Cancel discovery because it will slow down the connection
BA.cancelDiscovery();
try {
// Connect the device through the socket. This will block
// until it succeeds or throws an exception
mmSocket.connect();
System.out.println("Connection established");
// tv_connection_e.setText(e.print.stacktrace);
ConnectedThread tc = new ConnectedThread(mmSocket);
tc.start();
} catch (IOException connectException) {
// Unable to connect; close the socket and get out
System.out.println("Fail to connect!");
try {
mmSocket.close();
} catch (IOException closeException) {
System.out.println("Fail to close connection");
}
return;
}
}
/** Will cancel an in-progress connection, and close the socket */
public void cancel() {
try {
mmSocket.close();
} catch (IOException e) {
}
}
}
private class ConnectedThread extends Thread {
private final BluetoothSocket mmSocket;
private final InputStream mmInStream;
private final OutputStream mmOutStream;
public ConnectedThread(BluetoothSocket socket) {
mmSocket = socket;
InputStream tmpIn = null;
OutputStream tmpOut = null;
try {
tmpIn = socket.getInputStream();
tmpOut = socket.getOutputStream();
} catch (IOException e) {
}
System.out.println("Inside the thread");
mmInStream = tmpIn;
mmOutStream = tmpOut;
try {
EngineRPMObdCommand engineRpmCommand = new EngineRPMObdCommand();
SpeedObdCommand speedCommand = new SpeedObdCommand();
FindFuelTypeObdCommand fueltypeCommand = new FindFuelTypeObdCommand();
System.out.println("Inside the try block");
while (!Thread.currentThread().isInterrupted()) {
System.out.println("Inside while");
// TODO handle commands result
Log.d("Poonam",
"RPM: " + engineRpmCommand.getFormattedResult());
Log.d("Poonam",
"Speed: " + speedCommand.getFormattedResult());
Log.d("Poonam",
"FuelType: " + fueltypeCommand.getFormattedResult());
RPM = engineRpmCommand.getFormattedResult();
Speed = speedCommand.getFormattedResult();
FuelType = fueltypeCommand.getFormattedResult();
try {
engineRpmCommand.run(mmInStream, mmOutStream);
speedCommand.run(mmInStream, mmOutStream);
fueltypeCommand.run(mmInStream, mmOutStream);
System.out.println("Commands Processed");
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
System.out.println("outside try catch");
}
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
System.out.println("inside catch before while");
}
// Get the input and output streams, using temp objects because
// member streams are final
}
public void run() {
byte[] buffer = new byte[1024]; // buffer store for the stream
int bytes; // bytes returned from read()
// Keep listening to the InputStream until an exception occurs
while (true) {
}
}
/* Call this from the main activity to send data to the remote device */
public void write(byte[] bytes) {
try {
mmOutStream.write(bytes);
} catch (IOException e) {
}
}
/* Call this from the main activity to shutdown the connection */
public void cancel() {
try {
mmSocket.close();
} catch (IOException e) {
}
}
}
}
**Bluetooth.java**
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.util.ArrayList;
import java.util.List;
import java.util.UUID;
import android.app.Activity;
import android.bluetooth.BluetoothAdapter;
import android.bluetooth.BluetoothDevice;
import android.bluetooth.BluetoothSocket;
import android.util.Log;
public class Bluetooth extends Activity{
private BluetoothSocketWrapper bluetoothSocket;
private BluetoothDevice device;
private boolean secure;
private BluetoothAdapter adapter;
private List<UUID> uuidCandidates;
private int candidate;
/**
* #param device the device
* #param secure if connection should be done via a secure socket
* #param adapter the Android BT adapter
* #param uuidCandidates a list of UUIDs. if null or empty, the Serial PP id is used
* #return
*/
public void BluetoothConnector(BluetoothDevice device, boolean secure, BluetoothAdapter adapter,
List<UUID> uuidCandidates) {
this.device = device;
this.secure = secure;
this.adapter = adapter;
this.uuidCandidates = uuidCandidates;
if (this.uuidCandidates == null || this.uuidCandidates.isEmpty()) {
this.uuidCandidates = new ArrayList<UUID>();
this.uuidCandidates.add(UUID.fromString("00001101-0000-1000-8000-00805f9b34fb"));
}
}
public BluetoothSocketWrapper connect() throws IOException {
boolean success = false;
while (selectSocket()) {
adapter.cancelDiscovery();
try {
bluetoothSocket.connect();
success = true;
break;
} catch (IOException e) {
//try the fallback
try {
bluetoothSocket = new FallbackBluetoothSocket(bluetoothSocket.getUnderlyingSocket());
Thread.sleep(500);
bluetoothSocket.connect();
success = true;
break;
} catch (FallbackException e1) {
Log.w("BT", "Could not initialize FallbackBluetoothSocket classes.", e);
} catch (InterruptedException e1) {
Log.w("BT", e1.getMessage(), e1);
} catch (IOException e1) {
Log.w("BT", "Fallback failed. Cancelling.", e1);
}
}
}
if (!success) {
throw new IOException("Could not connect to device: "+ device.getAddress());
}
return bluetoothSocket;
}
private boolean selectSocket() throws IOException {
if (candidate >= uuidCandidates.size()) {
return false;
}
BluetoothSocket tmp = null;
UUID uuid = uuidCandidates.get(candidate++);
Log.i("BT", "Attempting to connect to Protocol: "+ uuid);
if (secure) {
Method m = null;
try {
m = device.getClass().getMethod("createRfcommSocket", new Class[] {int.class});
} catch (NoSuchMethodException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
try {
tmp = (BluetoothSocket) m.invoke(device, 1);
} catch (IllegalAccessException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IllegalArgumentException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (InvocationTargetException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
} else {
tmp = device.createInsecureRfcommSocketToServiceRecord(uuid);
}
bluetoothSocket = new NativeBluetoothSocket(tmp);
return true;
}
public static interface BluetoothSocketWrapper {
InputStream getInputStream() throws IOException;
OutputStream getOutputStream() throws IOException;
String getRemoteDeviceName();
void connect() throws IOException;
String getRemoteDeviceAddress();
void close() throws IOException;
BluetoothSocket getUnderlyingSocket();
}
public static class NativeBluetoothSocket implements BluetoothSocketWrapper {
private BluetoothSocket socket;
public NativeBluetoothSocket(BluetoothSocket tmp) {
this.socket = tmp;
}
#Override
public InputStream getInputStream() throws IOException {
return socket.getInputStream();
}
#Override
public OutputStream getOutputStream() throws IOException {
return socket.getOutputStream();
}
#Override
public String getRemoteDeviceName() {
return socket.getRemoteDevice().getName();
}
#Override
public void connect() throws IOException {
socket.connect();
}
#Override
public String getRemoteDeviceAddress() {
return socket.getRemoteDevice().getAddress();
}
#Override
public void close() throws IOException {
socket.close();
}
#Override
public BluetoothSocket getUnderlyingSocket() {
return socket;
}
}
public class FallbackBluetoothSocket extends NativeBluetoothSocket {
private BluetoothSocket fallbackSocket;
public FallbackBluetoothSocket(BluetoothSocket tmp) throws FallbackException {
super(tmp);
try
{
Class<?> clazz = tmp.getRemoteDevice().getClass();
Class<?>[] paramTypes = new Class<?>[] {Integer.TYPE};
Method m = clazz.getMethod("createRfcommSocket", paramTypes);
Object[] params = new Object[] {Integer.valueOf(1)};
fallbackSocket = (BluetoothSocket) m.invoke(tmp.getRemoteDevice(), params);
}
catch (Exception e)
{
throw new FallbackException(e);
}
}
#Override
public InputStream getInputStream() throws IOException {
return fallbackSocket.getInputStream();
}
#Override
public OutputStream getOutputStream() throws IOException {
return fallbackSocket.getOutputStream();
}
#Override
public void connect() throws IOException {
fallbackSocket.connect();
}
#Override
public void close() throws IOException {
fallbackSocket.close();
}
}
public static class FallbackException extends Exception {
/**
*
*/
private static final long serialVersionUID = 1L;
public FallbackException(Exception e) {
super(e);
}
}
}
(MainActivity.java:367)
try {
engineRpmCommand.run(mmInStream, mmOutStream);
speedCommand.run(mmInStream, mmOutStream);
fueltypeCommand.run(mmInStream, mmOutStream);
System.out.println("Commands Processed");
} catch (InterruptedException e) {
// TODO Auto-generated catch block
367--> e.printStackTrace();
}
System.out.println("outside try catch");
}
(ObdCommand.java:164)
protected void readRawData(InputStream in) throws IOException {
byte b = 0;
StringBuilder res = new StringBuilder();
// read until '>' arrives
164--> while ((char) (b = (byte) in.read()) != '>')
res.append((char) b);
Have you checked if your string builder / buffer contains anything at the time the exception is thrown?
I've had this trouble with Bluetooth on a Nexus 7 2012 and the only thing I can suggest is that you Thread.sleep() while waiting for data and use .available() from the stream to make sure you don't read more than what is available.
You could sleep loop while .available() is zero and not equal to the amount as the last loop, and then assume you have all the data when it stabilizes. Alternatively you can simply catch the exception and assume you have received all the data at that point.
I think its a bug in read() method. From #Keilaron's answer.. I tried this and this works:
while (inputStream.available() == 0);
val available = inputStream.available()
val bytes = ByteArray(available)
inputStream.read(bytes, 0, available)
val text = String(bytes)

Why I am getting java.lang.NullPointerException?

I am trying to test this script, to get print some demo text to my Zebra printer using Android, but I am getting a java.lang.NullPointerException. I have read is something about an initialization, but I can't identify what is the object to initializate.
this is the error:
E/AndroidRuntime(2098):
FATAL EXCEPTION: Thread-9874
Process: com.stihn.sibmovil, PID: 2098
java.lang.NullPointerException
at com.stihn.sibmovil.sendfile.SibPrint.testSendFile(SibPrint.java:88)
at com.stihn.sibmovil.sendfile.SibPrint.access$0(SibPrint.java:86)
at com.stihn.sibmovil.sendfile.SibPrint$1.run(SibPrint.java:53)
at java.lang.Thread.run(Thread.java:841)
Thanks for your help!
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import android.os.Looper;
import com.stihn.sibmovil.util.SettingsHelper;
import com.zebra.sdk.comm.BluetoothConnection;
import com.zebra.sdk.comm.Connection;
import com.zebra.sdk.comm.ConnectionException;
import com.zebra.sdk.printer.ZebraPrinter;
import com.zebra.sdk.printer.ZebraPrinterFactory;
import com.zebra.sdk.printer.ZebraPrinterLanguageUnknownException;
import org.apache.cordova.api.Plugin;
import org.apache.cordova.api.PluginResult;
import com.zebra.sdk.printer.PrinterLanguage;
import org.json.JSONArray;
import org.json.JSONException;
import android.app.Activity;
import android.app.ProgressDialog;
import android.content.Context;
public class SibPrint extends Plugin {
ProgressDialog loadingDialog;
Activity activity;
private Context context;
String macAddress;
String filepath;
public PluginResult execute(String action, JSONArray args, String callbackId) {
try {
if (action.equals("sibPrintTicket")) {
String echo = args.getString(0);
filepath = args.getString(1);
macAddress = args.getString(2);
if (echo != null && echo.length() > 0) {
new Thread(new Runnable() {
public void run() {
Looper.prepare();
Connection connection = null;
connection = new BluetoothConnection(macAddress);
try {
System.out.println("Imprimiendo ...");
connection.open();
ZebraPrinter printer = ZebraPrinterFactory
.getInstance(connection);
testSendFile(printer);
connection.close();
} catch (ConnectionException e) {
System.out.println("Error Try 1 "
+ e.getMessage());
} catch (ZebraPrinterLanguageUnknownException e) {
System.out.println("Error Catch 1 "
+ e.getMessage());
} finally {
if (activity != null && loadingDialog != null) {
loadingDialog.dismiss();
}
}
Looper.loop();
Looper.myLooper().quit();
}
}).start();
//retornar mensaje de imprimiendo
return new PluginResult(PluginResult.Status.OK, "Imprimiendo..");
} else {
return new PluginResult(PluginResult.Status.ERROR);
}
} else {
return new PluginResult(PluginResult.Status.INVALID_ACTION);
}
} catch (JSONException e) {
return new PluginResult(PluginResult.Status.JSON_EXCEPTION);
}
}
private void testSendFile(ZebraPrinter printer) {
try {
File filepath = context.getFileStreamPath("TEST.LBL");
createDemoFile(printer, "TEST.LBL");
printer.sendFileContents(filepath.getAbsolutePath());
this.saveBluetoothAddress(this, macAddress);
} catch (ConnectionException e1) {
System.out.println("Error sending file to printer" + e1.getMessage());
} catch (IOException e) {
System.out.println("Error creating file" + e.getMessage());
}
}
private void saveBluetoothAddress(SibPrint sibPrint,
String macAddress) {
// TODO Auto-generated method stub
}
private void createDemoFile(ZebraPrinter printer, String fileName) throws IOException {
FileOutputStream os = context.openFileOutput(fileName, Context.MODE_PRIVATE);
byte[] configLabel = null;
PrinterLanguage pl = printer.getPrinterControlLanguage();
if (pl == PrinterLanguage.ZPL) {
configLabel = "^XA^FO17,16^GB379,371,8^FS^FT65,255^A0N,135,134^FDTEST^FS^XZ".getBytes();
} else if (pl == PrinterLanguage.CPCL) {
String cpclConfigLabel = "! 0 200 200 406 1\r\n" + "ON-FEED IGNORE\r\n" + "BOX 20 20 380 380 8\r\n" + "T 0 6 137 177 TEST\r\n" + "PRINT\r\n";
configLabel = cpclConfigLabel.getBytes();
}
os.write(configLabel);
os.flush();
os.close();
}
}
you got java.lang.NullPointerException in Context
at
File filepath = context.getFileStreamPath("TEST.LBL");
you are not initialize context in your class.
please add
public void SibPrint(Context context){
this.context=context;
}
in your class.
and create consructor in Activity like
SibPrint mSibPrint = new SibPrint(MyActivity.this);
public class SibPrint extends Plugin {
ProgressDialog loadingDialog;
Activity activity;
private Context context;
String macAddress;
String filepath;
//add this method
public void SibPrint(Context context){
this.context=context;
}
.
.
.
}
Try this..
You have not initialize context that's inside testSendFile() method
File filepath = context.getFileStreamPath("TEST.LBL");
you should initialize context before using it otherwise you will get NPE

Why on double click android client received data?

When I click the first time on login button, data send to server and server received data in return on first click data not show on android client screen. When I pressed login button again it again send data and then it show data on client screen... plz help me. Why data is received on secind click i want my data recived on my first click?
Here is the code :
Client tcpip code...
public class SockProg {
private Socket socket;
DataOutputStream dataOutputStream;
DataInputStream dataInputStream;
String data;
String serverip = "192.168.1.7";
int serverport = 4444;
public void connetToServer(){
try {
socket = new Socket(serverip, serverport);
Log.i("AsyncTank", "doInBackgoung: Created Socket");
} catch (UnknownHostException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
if (socket.isConnected()) {
try {
dataOutputStream = new DataOutputStream(
socket.getOutputStream());
dataInputStream = new DataInputStream(socket.getInputStream());
} catch (IOException e) {
e.printStackTrace();
}
}
}
public void writeToStream(String message) {
try {
if (socket.isConnected()){
dataOutputStream.writeUTF(message.toString());
} else {
Log.i("AsynkTask", "writeToStream : Cannot write to stream, Socket is closed");
}
} catch (Exception e) {
Log.i("AsynkTask", "writeToStream : Writing failed");
}
}
public String readFromStream() {
String ret = null;
try {
if (socket.isConnected()) {
Log.i("AsynkTask", "readFromStream : Reading message");
ret=dataInputStream.readUTF();
Log.i("AsynkTask", "readFromStream : read "+ret);
} else {
Log.i("AsynkTask", "readFromStream : Cannot Read, Socket is closed");
}
} catch (Exception e) {
Log.i("AsynkTask", "readFromStream : Reading failed"+e.getClass());
}
return ret;
}
public void CloseSockets(){
if (socket != null) {
try {
socket.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
if (dataOutputStream != null) {
try {
dataOutputStream.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
if (dataInputStream != null) {
try {
dataInputStream.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
here is the code of sychronized thread
public class TCP implements Runnable {
String data;
SockProg sp;
Thread thh;
private static String rdata;
public TCP(SockProg spr, String val) {
sp = spr;
data = val;
thh = new Thread(this);
thh.start();
}
#Override
public void run() {
synchronized(sp) { // synchronized block
//rdata= sp.DataSendRecive(data);
sp.connetToServer();
sp.writeToStream(data);
rdata=sp.readFromStream();
sp.CloseSockets();
}
}
public static String getData(){
return rdata;
}
}
here is code of Login Activity...
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_login);
msg = (TextView) findViewById(R.id.msg_log);
login = (Button) findViewById(R.id.btn_login);
login.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// try{
txtph = (EditText) findViewById(R.id.txt_phnum);
txtpass = (EditText) findViewById(R.id.txt_pass);
ph = txtph.getText().toString();
pass = txtpass.getText().toString();
int ch = 0;
if (ph.equals("") || ph == null) {
msg.setText("Please Enter Mobile Number....\n");
ch++;
}
if (pass.equals("") || pass == null) {
if (ch == 0) {
msg.setText("Please Enter your Password....\n");
} else {
msg.append("Please Enter your Password....\n");
}
ch++;
}
if (ch == 0) {
ArrayList<String> ph_pass = new ArrayList<String>();
ph_pass.add(0, "LoginAccount");
ph_pass.add(1, ph);
ph_pass.add(2, pass);
SockProg sp=new SockProg();
TCP t=new TCP(sp, ph_pass.toString());
data=t.getData();
msg.setText(data);
}
}
});
}
This looks like a classic case of asynchronous coding delay. The TCP class is a runnable and therefor when it is called the first time (the first click on the login button) it starts running, but the Thread does not have enough time to finish
rdata=sp.readFromStream();
in the run() method, therefor data=t.getData(); does not return anything useful. The second click, provides the runnable with enough time populate the rdata with some data and therefor your program works.
When working with asynchrounous code, you need a better way to wait for code to complete what it is doing.
Why is rdata a static type? Make it non-static and then change the getData() method like this:
public synchronized String getData()

Categories