I have an app that connects to a device using SPP, and for some reason, our Acer Iconia One B3-A10 won't connect to this device. Our other tablets have no issue connecting.
Here is my code:
public class BluetoothConnectionService {
Context mContext;
static BluetoothAdapter btAdapter;
static ArrayList<BluetoothDevice> pairedDevices;
static BluetoothDevice selectedDevice;
static BluetoothSocket socket;
static InputStream inStream;
static OutputStream outStream;
public static boolean isBluetoothEnabled() {
btAdapter = BluetoothAdapter.getDefaultAdapter();
if (btAdapter == null) {
return false;
} else {
if (!btAdapter.isEnabled()) {
// Bluetooth is not enabled :)
return false;
} else {
return true;
}
}
}
public static ArrayList<BluetoothDevice> getPairedDevices() {
btAdapter = BluetoothAdapter.getDefaultAdapter();
Set<BluetoothDevice> devices = btAdapter.getBondedDevices();
if (devices.size() > 0) {
pairedDevices = new ArrayList<BluetoothDevice>();
for (BluetoothDevice device : devices) {
pairedDevices.add(device);
}
}
return pairedDevices;
}
static void sendMessage(BluetoothSocket socket, String msg) {
OutputStream outStream;
if (socket != null) {
try {
outStream = socket.getOutputStream();
outStream.write(msg.getBytes());
} catch (IOException e) {
Log.d("BLUETOOTH_COMMS", e.getMessage());
}
}
}
public static void setDevice(BluetoothDevice device) {
selectedDevice = device;
}
public static BluetoothDevice getDevice() {
return selectedDevice;
}
public static void setSocket(BluetoothSocket msocket) {
socket = msocket;
}
public static void closeSocket() {
try {
if (socket != null) {
socket.close();
}
} catch (IOException e) {
Log.e("Error", "Could not close socket!");
}
}
public static BluetoothSocket getSocket() {
return socket;
}
public static void setInStream(InputStream inStream) {
inStream = inStream;
}
public static void setOutStream(OutputStream outStream) {
outStream = outStream;
}
public static InputStream getInStream() {
return inStream;
}
public static OutputStream getOutStream() {
return outStream;
}
}
public abstract class ConnectTask extends AsyncTask<Void, Void, Void> {
Context mContext;
BluetoothDevice mdevice;
BluetoothSocket mSocket;
ProgressDialog pd;
public ConnectTask(Context context) {
mContext = context;
}
#Override
protected void onPreExecute() {
super.onPreExecute();
if (pd !=null) {
pd = null;
}
pd = new ProgressDialog(mContext);
pd.setTitle("Connecting...");
pd.setCancelable(false);
if (!pd.isShowing()) {
pd.show();
}
}
#Override
protected Void doInBackground(Void... params) {
try {
mdevice = BluetoothConnectionService.getDevice();
UUID uuid = mdevice.getUuids()[0].getUuid();
mSocket = mdevice.createRfcommSocketToServiceRecord(uuid);
mSocket=mdevice.createInsecureRfcommSocketToServiceRecord(uuid);
mSocket.connect();
} catch (IOException e) {
Log.e("Error", "Could not connect socket!");
if (mSocket != null) {
try {
mSocket.close();
} catch (IOException e1) {
Log.e("Error", "Can't close socket!");
}
}
return null;
}
#Override
protected void onPostExecute(Void result) {
super.onPostExecute(result);
try {
if (pd != null) {
if (pd.isShowing()) {
pd.dismiss();
}
}
} catch (final IllegalArgumentException are) {
Log.e("Error", "Illegal Argument Exception);
} finally {
pd = null;
}
BluetoothConnectionService.setSocket(mSocket);
onComplete();
}
//start session
abstract void onComplete();
public void dismissDialog() {
if (pd != null) {
if (pd.isShowing()) {
pd.dismiss();
}
}
pd = null;
}
}
Is there any way to get the Acer Iconia One B3-A10 to connect? Or is there a hardware limitation that prevents it?
Related
I am using Android-Bluetooth-Printer.it works fine if i type English text in edittext,but the issue is if i select hindi language from soft keyboard,and then i enter some hindi text and try to print,but it display nothing in paper.
public class BlueToothPrinterApp extends Activity
{
EditText message;
Button printbtn;
byte FONT_TYPE;
private static BluetoothSocket btsocket;
private static OutputStream btoutputstream;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
message = (EditText)findViewById(R.id.message);
printbtn = (Button)findViewById(R.id.printButton);
printbtn.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
connect();
}
});
}
protected void connect() {
if(btsocket == null){
Intent BTIntent = new Intent(getApplicationContext(), BTDeviceList.class);
this.startActivityForResult(BTIntent, BTDeviceList.REQUEST_CONNECT_BT);
}
else{
OutputStream opstream = null;
try {
opstream = btsocket.getOutputStream();
} catch (IOException e) {
e.printStackTrace();
}
btoutputstream = opstream;
print_bt();
}
}
private void print_bt() {
try {
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
btoutputstream = btsocket.getOutputStream();
byte[] printformat = { 0x1B, 0x21, FONT_TYPE };
btoutputstream.write(printformat);
String msg = message.getText().toString();
btoutputstream.write(msg.getBytes());
btoutputstream.write(0x0D);
btoutputstream.write(0x0D);
btoutputstream.write(0x0D);
btoutputstream.flush();
} catch (IOException e) {
e.printStackTrace();
}
}
#Override
protected void onDestroy() {
super.onDestroy();
try {
if(btsocket!= null){
btoutputstream.close();
btsocket.close();
btsocket = null;
}
} catch (IOException e) {
e.printStackTrace();
}
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
try {
btsocket = BTDeviceList.getSocket();
if(btsocket != null){
print_bt();
}
} catch (Exception e) {
e.printStackTrace();
}
}
}
Can any one help me with this?
Printers have predefined character sets built in. These character sets are known as code pages.
Your Bluetooth printer, like most POS printers doesn't seem to support Unicode.
To solve this you could try converting your output to an image and send it to the printer as bytes using an emulation the printer understands.(PCL, ESC/POS, ZPL etc.)
I was trying to create Server and Client application using RxAndroid,
Since i am new to Reactive Programming, still i am confused on what Map should be used and how exactly can this be implemented?
This is my current server using Thread:
import com.mbh.usbcom.MBLogger.MBLogger;
import java.net.ServerSocket;
/**
* Created by MBH on 2016-02-01.
*/
public class MBUSBServer {
interface IRepliedMessageHandler {
void repliedMessage(String message, int count);
}
interface IReceivedMessageHandler {
void receivedMessage(String message, int count);
}
MBLogger logger;
private static MBUSBServer mInstance = null;
// private final int PORT = 59900; // anyport
ServerSocket serverSocket;
private volatile boolean isRunning = false;
private final String ReplyMessage = "Client#";
IRepliedMessageHandler repliedMessageHandler;
IReceivedMessageHandler receivedMessageHandler;
Thread mThread;
int clinetsCount = 0;
// Singlton : 1 Server at a time
public static MBUSBServer getInstance() {
if (mInstance == null) {
mInstance = new MBUSBServer();
}
return mInstance;
}
private MBUSBServer() {
logger = new MBLogger.Builder()
.setTag(MBUSBServer.class)
.createLogger();
}
public void start(IReceivedMessageHandler receivedMessageHandler,
IRepliedMessageHandler repliedMessageHandler) {
this.repliedMessageHandler = repliedMessageHandler;
this.receivedMessageHandler = receivedMessageHandler;
start();
}
private void start() {
if (isRunning) return;
if (mThread != null) {
mThread = null;
}
isRunning = true;
mThread = new Thread(new Runnable() {
#Override
public void run() {
try {
logger.logDebug("Initializing ServerSocket");
serverSocket = new ServerSocket(59900);
serverSocket.setReuseAddress(true);
logger.logDebug("ServerSocker initialized--InetAddress=" + serverSocket.getInetAddress());
while (isRunning) {
logger.logInfo("ServerSocket is waiting for Client");
MBTCPClient mbtcpClient = new MBTCPClient(serverSocket.accept());
clinetsCount++;
//logger.logDebug("Received Request from Client #" + clinetsCount);
// Write rely to socket, then Read from socket, and push message to handler
receiveAndReplyWithSocket(false, mbtcpClient, clinetsCount);
}
isRunning = false;
} catch (Exception e) {
isRunning = false;
logger.logError(e);
}
}
});
mThread.start();
}
private void receiveAndReplyWithSocket(boolean sameThread, final MBTCPClient mbtcpClient, final int count) {
if (sameThread) {
receiveAndReplyWithSocket(mbtcpClient, count);
} else {
new Thread(new Runnable() {
#Override
public void run() {
receiveAndReplyWithSocket(mbtcpClient, count);
}
}).start();
}
}
private void receiveAndReplyWithSocket(MBTCPClient mbtcpClient, int count) {
try {
final String reply = ReplyMessage + count;
mbtcpClient.write(reply);
if (repliedMessageHandler != null) {
repliedMessageHandler.repliedMessage(reply, count);
}
String response = mbtcpClient.read();
if (receivedMessageHandler != null) {
receivedMessageHandler.receivedMessage(response, count);
}
mbtcpClient.close();
} catch (Exception e) {
logger.logError(e);
}
}
public void stop() {
isRunning = false;
if (mThread != null) {
mThread = null;
}
if (serverSocket != null) {
try {
serverSocket.close();
serverSocket = null;
} catch (Exception e) {
e.printStackTrace();
}
}
logger.logDebug("Server Has Been Stopped");
}
}
and my current client:
import com.mbh.usbcom.MBLogger.MBLogger;
import java.io.BufferedReader;
import java.io.DataOutputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.Socket;
/**
* Created by MBH on 2016-02-02.
*/
public class MBTCPClient {
Socket socket;
DataOutputStream out;
BufferedReader in;
MBLogger logger = new MBLogger.Builder().setTag(MBTCPClient.class)
.createLogger();
public MBTCPClient(Socket socket) {
this.socket = socket;
}
public MBTCPClient(String hostAdds, int port) {
try {
socket = new Socket(hostAdds, port);
} catch (IOException e) {
logger.logError(e);
}
}
public String read() {
try {
in = new BufferedReader(new InputStreamReader(socket.getInputStream()));
return in.readLine();
} catch (IOException e) {
logger.logError(e);
return null;
}
}
public boolean write(String reply) {
if(socket == null) return false;
try {
out = new DataOutputStream(socket.getOutputStream());
out.writeBytes(reply);
return true;
} catch (IOException e) {
logger.logError(e);
return false;
}
}
public void close() {
// close socket
if (socket != null) {
try {
socket.close();
} catch (IOException e) {
logger.logError(e);
}
}
// close input stream
if (in != null) {
try {
in.close();
} catch (IOException e) {
logger.logError(e);
}
}
// close output stream
if (out != null) {
try {
out.close();
} catch (IOException e) {
logger.logError(e);
}
}
}
}
this is my service class. When i launch my app for the first time the service gets created but it does not show any notification until i close the app. when i close the app the service restarts and starts giving me notifications and sending broadcast.
public class XMPPService extends Service {
private XMPPTCPConnection mConnection = null;
private ChatManager chatManager;
int mNotificationId = 1;
#Override
public int onStartCommand(final Intent intent, int flags, int startId) {
new Thread(new Runnable() {
#Override
public void run() {
try {
onHandleIntent(intent);
} catch (IOException e) {
e.printStackTrace();
} catch (XMPPException e) {
e.printStackTrace();
} catch (SmackException e) {
e.printStackTrace();
}
}
}).start();
return START_STICKY;
}
protected void onHandleIntent(Intent intent) throws IOException, XMPPException, SmackException {
if (mConnection == null) {
mConnection = ProfileCreationActivity.returnConnection();
if(!mConnection.isAuthenticated())
mConnection.login(new TinyDB(getApplicationContext()).getString("username"), new TinyDB(getApplicationContext()).getString("password"));
chatManager = ChatManager.getInstanceFor(mConnection);
chatManager.addChatListener(new ChatManagerListenerImpl());
StanzaFilter filter = new StanzaTypeFilter(Message.class);
mConnection.addSyncStanzaListener(new StanzaListener() {
#Override
public void processPacket(Stanza packet) throws SmackException.NotConnectedException {
Message message = (Message) packet;
}
}, filter);
}
mConnection.addConnectionListener(new AbstractConnectionListener() {
public void connectionClosed() {
Log.i("connection", "closed");
}
public void connectionClosedOnError(Exception e) {
Log.i("connection", "closed on error");
}
public void reconnectionFailed(Exception e) {
Log.i("reconnection", "failed");
}
public void reconnectionSuccessful() {
if (mConnection.isAuthenticated()) {
Log.i("isAuthenticated", String.valueOf(XMPPClient.getConnection().isAuthenticated()));
} else {
try {
mConnection.login(new TinyDB(getApplicationContext()).getString("username"), new TinyDB(getApplicationContext()).getString("password"));
} catch (XMPPException e) {
e.printStackTrace();
} catch (SmackException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
Log.i("reconnection", "succesful");
}
public void reconnectingIn(int seconds) {
Log.i("reconnectingIn", String.valueOf(seconds));
}
});
}
#Override
public void onCreate() {
Log.i("service", "created");
}
private class ChatManagerListenerImpl implements ChatManagerListener {
#Override
public void chatCreated(Chat chat, boolean createdLocally) {
if (!createdLocally) {
chat.addMessageListener(new ChatMessageListener() {
#Override
public void processMessage(Chat chat, Message message) {
Log.i("yeah :", "yeah");
new DBHelper(getApplicationContext()).addMessage(message.getBody().toString(), message.getFrom().toString().substring(0, 12), false);
NotificationCompat.Builder builder = new NotificationCompat.Builder(getApplicationContext());
builder.setSmallIcon(R.drawable.user);
builder.setContentText(message.getBody().toString());
builder.setContentTitle(message.getFrom().toString().substring(0, 12));
builder.setPriority(Notification.PRIORITY_HIGH);
builder.setDefaults(Notification.DEFAULT_ALL);
NotificationManager notificationManager = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
notificationManager.notify(mNotificationId, builder.build());
Intent intent = new Intent();
intent.setAction("com.SINGLE_MESSAGE_RECEIVED");
sendBroadcast(intent);
Log.i("Notification : ", "notified");
}
});
}
}
}
#Override
public void onDestroy() {
mConnection.disconnect();
Log.i("service :", "destroyed");
}
#Override
public IBinder onBind(Intent intent) {
// TODO: Return the communication channel to the service.
throw new UnsupportedOperationException("Not yet implemented");
}
}
i am starting my service in my main activity while checking my connection to the xmpp server. heres the code :
private class CheckConnection extends AsyncTask<Void, Void, XMPPTCPConnection> {
#Override
protected XMPPTCPConnection doInBackground(Void... params) {
if (!XMPPClient.getConnection().isAuthenticated()) {
try {
XMPPClient.getConnection().login(new TinyDB(getApplicationContext()).getString("username"), new TinyDB(getApplicationContext()).getString("password"));
} catch (XMPPException e) {
e.printStackTrace();
} catch (SmackException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return XMPPClient.getConnection();
} else
{
return XMPPClient.getConnection();
}
}
#Override
protected void onPostExecute(XMPPTCPConnection con) {
if (isMyServiceRunning(XMPPService.class) && XMPPClient.getConnection().isAuthenticated()) {
Log.i("Service is :", "Running");
getForms(con);
} else {
Intent serviceIntent = new Intent(MainActivity.this, XMPPService.class);
startService(serviceIntent);
if (XMPPClient.getConnection().isAuthenticated()) {
getForms(con);
}
}
}
}
I am working on an network discovery demo where I want to discovery machines which are running udp service. (Connected to a single wifi). I am using following code
public class DnssdDiscovery extends Activity {
android.net.wifi.WifiManager.MulticastLock lock;
android.os.Handler handler = new android.os.Handler();
ListView mListView;
ArrayList<String> new_conn_list;
DeviceListCustomAdapter new_conn_adapter;
ProgressDialog pbdnssd = null;
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main_layout);
mListView = (ListView) findViewById(R.id.listView);
new_conn_list = new ArrayList<String>();
new_conn_adapter = new DeviceListCustomAdapter(getApplicationContext(),
new_conn_list);
mListView.setAdapter(new_conn_adapter);
pbdnssd = new ProgressDialog(DnssdDiscovery.this);
pbdnssd.setCanceledOnTouchOutside(false);
pbdnssd.setMessage("Loading...");
/* handler.postDelayed(new Runnable() {
public void run() {
setUp();
}
}, 1000);*/
} /** Called when the activity is first created. */
private String type = "_Controller._udp.local.";
private JmDNS jmdns = null;
private ServiceListener listener = null;
private ServiceInfo serviceInfo;
#SuppressLint("NewApi")
private void setUp() {
android.net.wifi.WifiManager wifi = (android.net.wifi.WifiManager) getSystemService(android.content.Context.WIFI_SERVICE);
lock = wifi.createMulticastLock("mylockthereturn");
lock.setReferenceCounted(true);
lock.acquire();
try {
jmdns = JmDNS.create();
jmdns.addServiceListener(type, listener = new ServiceListener() {
#Override
public void serviceResolved(ServiceEvent ev) {
notifyUser(ev.getInfo().getName().toString() );
}
#Override
public void serviceRemoved(ServiceEvent ev) {
//notifyUser("Service removed: " + ev.getName());
}
#Override
public void serviceAdded(ServiceEvent event) {
// Required to force serviceResolved to be called again (after the first search)
jmdns.requestServiceInfo(event.getType(), event.getName(), 1);
}
});
serviceInfo = ServiceInfo.create("_Controller._udp.local.", "AndroidTest", 65534, "plain test service from android");
jmdns.registerService(serviceInfo);
} catch (IOException e) {
e.printStackTrace();
return;
}
}
public void clickDiscover(View v) {
if (isConnectingToInternet()) {
/*handler.postDelayed(new Runnable() {
public void run() {
setUp();
}
}, 1000);*/
if (!pbdnssd.isShowing())
pbdnssd.show();
new_conn_adapter.clearAll();
handler.postDelayed(new Runnable() {
public void run() {
setUp();
}
}, 1000);
v.setEnabled(false);
((Button) findViewById(R.id.stop_btn)).setEnabled(true);
}else {
Toast.makeText(getApplicationContext(), "Network Error",
Toast.LENGTH_SHORT).show();
}
}
#SuppressLint("NewApi")
public void clickStop(View v){
((Button) findViewById(R.id.discover_btn)).setEnabled(true);
if (jmdns != null) {
if (listener != null) {
jmdns.removeServiceListener(type, listener);
listener = null;
}
jmdns.unregisterAllServices();
try {
jmdns.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
jmdns = null;
}
//repo.stop();
//s.stop();
try {
lock.release();
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
private void notifyUser(final String msg) {
handler.postDelayed(new Runnable() {
public void run() {
String itemName = msg;
new_conn_adapter.add(itemName);
new_conn_adapter.notifyDataSetChanged();
if(pbdnssd.isShowing())
pbdnssd.dismiss();
}
}, 1);
}
#Override
protected void onStart() {
super.onStart();
//new Thread(){public void run() {setUp();}}.start();
}
#SuppressLint("NewApi")
#Override
protected void onStop() {
if (jmdns != null) {
if (listener != null) {
jmdns.removeServiceListener(type, listener);
listener = null;
}
jmdns.unregisterAllServices();
try {
jmdns.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
jmdns = null;
}
//repo.stop();
//s.stop();
try {
lock.release();
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
super.onStop();
}
public boolean isConnectingToInternet() {
ConnectivityManager connectivity = (ConnectivityManager) getApplicationContext()
.getSystemService(Context.CONNECTIVITY_SERVICE);
if (connectivity != null) {
NetworkInfo[] info = connectivity.getAllNetworkInfo();
if (info != null)
for (int i = 0; i < info.length; i++)
if (info[i].getState() == NetworkInfo.State.CONNECTED) {
return true;
}
}
return false;
}
}
Main thing is I am not sure on service type i am using is correct.
1) What is service type of UDP service?
2) Is it possible to search udp service using android device?
3) Is there any other example regarding this?
At first, my android device scans for bluetooth devices and then displays them in a listview. I select one of them and a new screen appears. How to return to the main screen when the connection is lost. Following is the code for selected device screen.
public class devicefound extends Activity implements OnClickListener {
private BluetoothAdapter mBluetoothAdapter = null;
private BluetoothSocket btSocket = null;
private OutputStream outStream = null;
Button b1;
private static final UUID MY_UUID =
UUID.fromString("00001101-0000-1000-8000-00805F9B34FB");
public static String address;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
findViewById(R.id.b1).setOnClickListener(this);
b1 = (Button) findViewById(R.id.b1);
}
#Override
public void onStart() {
super.onStart();
String address = getIntent().getStringExtra("address");
mBluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
BluetoothDevice device = mBluetoothAdapter.getRemoteDevice(address);
try {
btSocket = device.createRfcommSocketToServiceRecord(MY_UUID);
} catch (IOException e) { }
run();
}
public void run(){
try {
btSocket.connect();
} catch (IOException e) {
try {
btSocket.close();
} catch (IOException e2) { }
return;
}
}
public void onClick(View v){
String message1 = "1";
byte[] msgBuffer1 = message1.getBytes();
try{
outStream = btSocket.getOutputStream();
} catch (IOException e){ }
try {
outStream.write(msgBuffer1);
} catch (IOException e) {
}
}
}
#Override
public void onPause() {
super.onPause();
if (outStream != null) {
try {
outStream.flush();
} catch (IOException e) { }
}
}
#Override
public void onStop() {
super.onStop();
}
#Override
public void onDestroy() {
super.onDestroy();
}
}
As I know you should use BroadcastReceiver in a such situation.
Something like this http://android-er.blogspot.com/2011/05/start-bluetooth-discoverable-and.html
If you want to return to the previous screen, then you can call the finish method which your devicefound class inherits from Activity.