How do I connect programatically the bluetooth(RN4020) with Android app? - java

I am developing an Android app that is going to communicate with target miroprocessor(ARM processor) board through a bluetooth device(RN4020).
Since the pair PIN is random for each bluetooth module, I just want the app source code to connect the app with that RN4020 module (without pairing manually since I don't know the pair PIN).
Also, I just want to know the UUID for RN4020 module, I have tried to find the UUID through some Android app it shows more than ten UUIDs. I am confused to choose the appropriate UUID.
Here is my code:
private static String address = "00:1E:C0:19:DB:A6";
private static final UUID MY_UUID = UUID.fromString("00002A00-0000-1000-8000-00805F9B34FB");
connect.setOnClickListener(new View.OnClickListener()
{
public void onClick(View V)
{
Toast.makeText(getApplicationContext(), "Connecting to ... RN4020_D694", Toast.LENGTH_SHORT).show();
if (mBluetoothAdapter.isEnabled())
Connect();
}
});
public void Connect() {
BluetoothDevice device = mBluetoothAdapter.getRemoteDevice(address);
Toast.makeText(getApplicationContext(), "Connecting to ... " + device, Toast.LENGTH_SHORT).show();
mBluetoothAdapter.cancelDiscovery();
try {
btSocket = device.createRfcommSocketToServiceRecord(MY_UUID);
btSocket.connect();
Toast.makeText(getApplicationContext(), "Connection made", Toast.LENGTH_SHORT).show();
} catch (IOException e) {
try {
btSocket.close();
} catch (IOException e2) {
changingText.setText("Unable to end the connection");
}
Log.d(TAG, "Socket creation failed");
}
beginListenForData();
}
When I tried to press the connect button, my app got stuck and it's not responding.

To avoid pairing you need to go for an insecure UUID rfcomm.
Replace:
btSocket = device.createRfcommSocketToServiceRecord(MY_UUID);
with
btSocket = device.createInsecureRfcommSocketToServiceRecord(MY_UUID);

Related

How to change Wifi P2P device name?

I am trying to detect and connect two Android mobiles using Wifi P2P method and I have been successful in it. But, I want a different name to be shown on the other device when it discovers mine.
Since, I am using Samsung J7 Prime 2(Android 9), changing Device name or Bluetooth name changes the Wifi P2p name, but the code for that didn't work. I tried the same code on Android 6.0.1 i.e. API 23 and it worked fine.
swtWifi.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
changeDevName("Tony Stark");
}
});
public void changeDevName(String devNewName) {
try {
Method method = manager.getClass().getMethod("setDeviceName", WifiP2pManager.Channel.class, String.class, WifiP2pManager.ActionListener.class);
method.invoke(manager, channel, devNewName, new WifiP2pManager.ActionListener() {
#Override
public void onSuccess() {
Toast.makeText(MainActivity.this, "Name successfully changed", Toast.LENGTH_LONG).show();
}
#Override
public void onFailure(int reason) {
Toast.makeText(MainActivity.this, "Request failed: " + reason, Toast.LENGTH_SHORT).show();
}
});
} catch (Exception e) {
e.printStackTrace();
}
}

Android: Use progress dialog till a new activity loads up

I am trying to connect to a bluetooth device(BLE HC05 module) using my app, to do some IOT functionality
Below snippet shows the code which is used to go to a new activity when user clicks on a particular device to connect to.
This is in BluetoothActivity.java
lvPairedDevices.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
final Intent intent = new Intent(BluetoothActivity.this, TemperatureActivity.class);
intent.putExtra("Bluetooth Device Address", mBTPairedDevices.get(position).getAddress());
startActivity(intent);
}
});
As it is mentioned, I am sending the Bluetooth device's MAC Address. Using it an attempt to connect to the device is made.
This is in TemperatureActivity.java
Intent intent = getIntent();
Bundle extras = intent.getExtras();
deviceAddress = extras.getString("Bluetooth Device Address");
bluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
device = bluetoothAdapter.getRemoteDevice(deviceAddress);
try {
btSocket = device.createInsecureRfcommSocketToServiceRecord(myUUID);
bluetoothAdapter.cancelDiscovery();
btSocket.connect();
if(btSocket.isConnected())
Toast.makeText(TemperatureActivity.this,"Connected to " + device.getName() + " successfully", Toast.LENGTH_SHORT).show();
else
Toast.makeText(TemperatureActivity.this,"Couldn\'t connect to " + device.getName() + " properly", Toast.LENGTH_SHORT).show();
outStream = btSocket.getOutputStream();
connectedThread = new ConnectedThread(btSocket);
connectedThread.start();
} catch (IOException e) {
Log.d(TAG, "onResume: Bluetooth device could not be connected using RFCOMM");
Toast.makeText(TemperatureActivity.this, "Connection to device " + device.getName() + " using RFCOMM has failed", Toast.LENGTH_SHORT).show();
finish();
}
According to the above code, if the device is offline or has declined to connect, an exception will arise.
With the current situation, is there any possibility of using Progress dialog in the BluetoothActivity.java and stop it in both cases(bluetooth connection is established successfully or not) in TemperatureActivity.java
I will go to TemperatureActivity with the device's MAC address, if it is successful in connecting to the device it should stay in that page(TemperatureActivity) otherwise, return to the original page (BluetoothActivity) saying "Couldn't connect to the device"
I searched a lot, could not find an answer. Thanks in advance.

ConnectSDK doesn't try to find Chromecast

all.
I try to create an android cast application with google chromecast. So I tryied to find chromecast with this code:
public void startDiscoveringDevices() {
DiscoveryManager.init(mContext);
mDiscoveryManager = DiscoveryManager.getInstance();
mDiscoveryManager.registerDeviceService(CastService.class, CastDiscoveryProvider.class);
mDiscoveryManager.setPairingLevel(DiscoveryManager.PairingLevel.ON);
mDiscoveryManager.setCapabilityFilters(new CapabilityFilter(
MediaPlayer.Any,
MediaControl.Any,
VolumeControl.Any
));
mDiscoveryManager.addListener(this);
mDiscoveryManager.start();
Log.wtf("CastDeviceManager", "discovery manager was started");
}
After this I listen DiscoveryManagerListener:
// ********************* My DiscoveryManagerListener ********************************** //
#Override
public void onDeviceAdded(DiscoveryManager manager, ConnectableDevice device) {
Log.wtf("DiscoveryManagerListener", "Device added");
device.addListener(...); // Here I pass implementation of ConnectableDeviceListener interface.
device.connect(); // connect to device
}
#Override
public void onDeviceUpdated(DiscoveryManager manager, ConnectableDevice device) {
Log.wtf("DiscoveryManagerListener", "Device updated");
device.addListener(...); // Here I pass implementation of ConnectableDeviceListener interface.
// try to connect to device, if it not connected yet
if (device.isConnected()) {
device.disconnect();
}
else {
device.connect();
}
}
#Override
public void onDeviceRemoved(DiscoveryManager manager, ConnectableDevice device) {
Log.wtf("DiscoveryManagerListener", "Device removed");
mCastDevices.remove(device.hashCode()); // remove device from list of devices
}
#Override
public void onDiscoveryFailed(DiscoveryManager manager, ServiceCommandError error) {
Log.wtf("DiscoveryManagerListener", "Device(s) not found", error);
destroyDiscoveryManager();
}
// ************************************************************************************ //
// ************************** My ConnectableDeviceListener **************************** //
#Override
public void onDeviceReady(ConnectableDevice device) {
Log.wtf("ConnectableDeviceListener", "device ready");
outDeviceInfo(device, "ConnectableDeviceListener");
// put to map with devices new connected device
mCastDevices.put(device.hashCode(), new CastDevice(device, mCastLifecycleListener));
Log.wtf("ConnectableDeviceListener", "Count cast devices: " + mCastDevices.size());
}
#Override
public void onDeviceDisconnected(ConnectableDevice device) {
Log.wtf("ConnectableDeviceListener", "device disconnected");
destroyDiscoveryManager();
}
#Override
public void onPairingRequired(ConnectableDevice device, DeviceService service, PairingType pairingType) {
Log.wtf("ConnectableDeviceListener", "device paring required");
}
#Override
public void onCapabilityUpdated(ConnectableDevice device, List<String> added, List<String> removed) {
Log.wtf("ConnectableDeviceListener", "capability updated");
}
#Override
public void onConnectionFailed(ConnectableDevice device, ServiceCommandError error) {
Log.wtf("ConnectableDeviceListener", "connection failed");
destroyDiscoveryManager();
}
// ************************************************************************************ //
// this method I use to disconnect from devices in map and stop discovering new devices
public void destroyDiscoveryManager() {
mDiscoveryManager.stop();
DiscoveryManager.destroy();
Log.wtf("CastDeviceManager", "discovery manager was stopped");
for (Map.Entry<Integer, CastDevice> castDeviceEntry: mCastDevices.entrySet()) {
castDeviceEntry.getValue().stopCast();
castDeviceEntry.getValue().disconnect();
Log.wtf("CastDevice", "device.isConnected(): " + castDeviceEntry.getValue().isConnected());
}
mCastDevices.clear();
}
In my Activity I call startDiscoveringDevices() and destroyDiscoveryManager() by buttons. And all was fine, but in one time it stop finding devices. I wasn't change anything in code.
Maybe I made something with bugs and it worked, but now something happened and it doesn't work now? What I doing wrong?

Multithreading not supported in MI devices for android app

We are building android app using multi threading as its working on almost all device except MI and few other devices that not supported Multi threading.
Try to call recording service in background using new threads. for that we create stopRecording() function that will call in new threads and its work in all device well but only few device like MI not working as we assumed there are not multi thread support in these devices ?
we are using below code
if(TelephonyManager.EXTRA_STATE_IDLE.equals(state)&&recording==true)
{
//Toast.makeText(getApplicationContext(), state, Toast.LENGTH_LONG).show();
//Toast.makeText(arg0, "STOP Called :"+recording, Toast.LENGTH_LONG).show();
stopRecording();
}
public void stopRecording()
{
if(recording==true)
{
try
{
te = getCurrentTS();
recorder.stop();
recorder.reset();
recorder.release();
recorder=null;
recording=false;
editor.putString("mdialerRecording", "false");editor.commit();
//broadcastIntent();
//Toast.makeText(getApplicationContext(), "Recorder_Relesed", Toast.LENGTH_LONG).show();
File oldfile = new File(fname);
byte[] fileData = new byte[(int) oldfile.length()];
DataInputStream dis = new DataInputStream(new FileInputStream(oldfile));
dis.readFully(fileData);
dis.close();
oldfile.delete();
try
{
String s64mp3file=Base64.encodeToString(fileData,Base64.NO_WRAP);
String newKey=calledCRM+"_"+sysNumber+"_"+ts+"_"+te;
editor.putString(newKey, s64mp3file);
String mdialerKeys=settings.getString("mdialerKeys", "");
editor.putString("mdialerKeys", mdialerKeys+"|"+newKey);
editor.commit();
}
catch(Exception e)
{
//Toast.makeText(getApplicationContext(), "File_EX "+e.toString(), Toast.LENGTH_LONG).show();
}
calledCRM="";
if(calledNum.equals(sysNumber))deleteLogNumber(sysNumber);
calledNum="";
}
catch(Exception e)
{
//Toast.makeText(getApplicationContext(), "Rec_Stop_EX "+e.toString(), Toast.LENGTH_LONG).show();
}
}
}

Printing Using USB cable issue

I am using following code to print through android device with USB cable attached to my Samsung printer.
When use startPrinting method it give me following verification in debugging log:
Command to printer sent successfully
Permission from printer granted.
and the printer even starts beeping, but the data I provide does not get printed. I am stuck at this stage and have found no help from google or on stackoverflow either.
Note: There is no crash no error either
I am testing this code on Android Jelly bean 4.3 OS
Any help would be appreciated.
private UsbManager mUsbManager;
private UsbDevice mDevice;
private UsbDeviceConnection mConnection;
private UsbInterface mInterface;
private UsbEndpoint mEndPoint;
private PendingIntent mPermissionIntent;
private static final String ACTION_USB_PERMISSION = "com.android.example.USB_PERMISSION";
private static Boolean forceCLaim = true;
HashMap<String, UsbDevice> mDeviceList;
Iterator<UsbDevice> mDeviceIterator;
int protocol;
#Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mUsbManager = (UsbManager) getSystemService(Context.USB_SERVICE);
mDeviceList = mUsbManager.getDeviceList();
mDeviceIterator = mDeviceList.values().iterator();
Button print = (Button) findViewById(R.id.buttonPrint);
Toast.makeText(this, "Device List Size: " + String.valueOf(mDeviceList.size()), Toast.LENGTH_SHORT).show();
TextView textView = (TextView) findViewById(R.id.usbDevice);
String usbDevice = "";
// This is just testing what devices are connected
while (mDeviceIterator.hasNext())
{
UsbDevice usbDevice1 = mDeviceIterator.next();
usbDevice += "\n" + "DeviceID: " + usbDevice1.getDeviceId() + "\n" + "DeviceName: " + usbDevice1.getDeviceName() + "\n" + "DeviceClass: " + usbDevice1.getDeviceClass() + " - "
+ translateDeviceClass(usbDevice1.getDeviceClass()) + "\n" + "DeviceSubClass: " + usbDevice1.getDeviceSubclass() + "\n" + "VendorID: " + usbDevice1.getVendorId() + "\n" + "ProductID: " + usbDevice1.getProductId()
+ "\n";
protocol = usbDevice1.getDeviceProtocol();
int interfaceCount = usbDevice1.getInterfaceCount();
Toast.makeText(this, "INTERFACE COUNT: " + String.valueOf(interfaceCount), Toast.LENGTH_SHORT).show();
mDevice = usbDevice1;
if (mDevice == null)
{
Toast.makeText(this, "mDevice is null", Toast.LENGTH_SHORT).show();
}
else
{
// Toast.makeText(this, "mDevice is not null", Toast.LENGTH_SHORT).show();
}
textView.setText(usbDevice);
}
if (mDevice == null)
{
Toast.makeText(this, "mDevice is null", Toast.LENGTH_SHORT).show();
}
else
{
// Toast.makeText(this, "mDevice is not null", Toast.LENGTH_SHORT).show();
}
print.setOnClickListener(new View.OnClickListener()
{
#Override
public void onClick(View view)
{
mPermissionIntent = PendingIntent.getBroadcast(MainActivity.this, 0, new Intent(ACTION_USB_PERMISSION), 0);
IntentFilter filter = new IntentFilter(ACTION_USB_PERMISSION);
registerReceiver(mUsbReceiver, filter);
if (mDevice != null)
mUsbManager.requestPermission(mDevice, mPermissionIntent);
// else
// Toast.makeText(this, "USB ", Toast.LENGTH_SHORT).show();
// print(mConnection, mInterface);
}
});
}
private String translateDeviceClass(int deviceClass)
{
switch (deviceClass)
{
case UsbConstants.USB_CLASS_APP_SPEC:
return "Application specific USB class";
case UsbConstants.USB_CLASS_AUDIO:
return "USB class for audio devices";
case UsbConstants.USB_CLASS_CDC_DATA:
return "USB class for CDC devices (communications device class)";
case UsbConstants.USB_CLASS_COMM:
return "USB class for communication devices";
case UsbConstants.USB_CLASS_CONTENT_SEC:
return "USB class for content security devices";
case UsbConstants.USB_CLASS_CSCID:
return "USB class for content smart card devices";
case UsbConstants.USB_CLASS_HID:
return "USB class for human interface devices (for example, mice and keyboards)";
case UsbConstants.USB_CLASS_HUB:
return "USB class for USB hubs";
case UsbConstants.USB_CLASS_MASS_STORAGE:
return "USB class for mass storage devices";
case UsbConstants.USB_CLASS_MISC:
return "USB class for wireless miscellaneous devices";
case UsbConstants.USB_CLASS_PER_INTERFACE:
return "USB class indicating that the class is determined on a per-interface basis";
case UsbConstants.USB_CLASS_PHYSICA:
return "USB class for physical devices";
case UsbConstants.USB_CLASS_PRINTER:
return "USB class for printers";
case UsbConstants.USB_CLASS_STILL_IMAGE:
return "USB class for still image devices (digital cameras)";
case UsbConstants.USB_CLASS_VENDOR_SPEC:
return "Vendor specific USB class";
case UsbConstants.USB_CLASS_VIDEO:
return "USB class for video devices";
case UsbConstants.USB_CLASS_WIRELESS_CONTROLLER:
return "USB class for wireless controller devices";
default:
return "Unknown USB class!";
}
}
// Broadcast receiver to obtain permission from user for connection
private final BroadcastReceiver mUsbReceiver = new BroadcastReceiver()
{
public void onReceive(Context context, Intent intent)
{
String action = intent.getAction();
if (ACTION_USB_PERMISSION.equals(action))
{
synchronized (this)
{
UsbDevice device = (UsbDevice) intent.getParcelableExtra(UsbManager.EXTRA_DEVICE);
if (intent.getBooleanExtra(UsbManager.EXTRA_PERMISSION_GRANTED, false))
{
if (device != null)
{
// call method to set up device communication
mInterface = device.getInterface(0);
mEndPoint = mInterface.getEndpoint(0);
mConnection = mUsbManager.openDevice(device);
Log.i("Info", "Device permission granted");
startPrinting(device);
// setup();
}
}
else
{
// Log.d("SUB", "permission denied for device " + device);
Toast.makeText(context, "PERMISSION DENIED FOR THIS DEVICE", Toast.LENGTH_SHORT).show();
}
}
}
}
};
public void startPrinting(final UsbDevice printerDevice)
{
Handler handler = new Handler();
handler.post(new Runnable()
{
UsbDeviceConnection conn;
UsbInterface usbInterface;
#Override
public void run()
{
try
{
Log.i("Info", "Bulk transfer started");
// usbInterface = printerDevice.getInterface(0);
for (int i = 0; i < printerDevice.getInterfaceCount(); i++)
{
usbInterface = printerDevice.getInterface(i);
if (usbInterface.getInterfaceClass() == UsbConstants.USB_CLASS_PRINTER)
{
// usbInterface = mDevice;
}
}
UsbEndpoint endPoint = usbInterface.getEndpoint(0);
conn = mUsbManager.openDevice(mDevice);
conn.claimInterface(usbInterface, true);
String myStringData = "TEXT";
myStringData += "\n";
byte[] array = myStringData.getBytes();
ByteBuffer output_buffer = ByteBuffer.allocate(array.length);
UsbRequest request = new UsbRequest();
request.initialize(conn, endPoint);
request.queue(output_buffer, array.length);
if (conn.requestWait() == request)
{
Log.i("Info", output_buffer.getChar(0) + "");
Message m = new Message();
m.obj = output_buffer.array();
output_buffer.clear();
}
else
{
Log.i("Info", "No request recieved");
}
int transfered = conn.bulkTransfer(endPoint, myStringData.getBytes(), myStringData.getBytes().length, 5000);
Log.i("Info", "Amount of data transferred : " + transfered);
}
catch (Exception e)
{
Log.e("Exception", "Unable to transfer bulk data");
e.printStackTrace();
}
finally
{
try
{
conn.releaseInterface(usbInterface);
Log.i("Info", "Interface released");
conn.close();
Log.i("Info", "Usb connection closed");
unregisterReceiver(mUsbReceiver);
Log.i("Info", "Brodcast reciever unregistered");
}
catch (Exception e)
{
Log.e("Exception", "Unable to release resources because : " + e.getMessage());
e.printStackTrace();
}
}
}
});
}
private void print(UsbDeviceConnection connection, UsbInterface intrface)
{
String test = "THIS IS A PRINT TEST";
// String text = "#move " + protocol + ";" + "#print" + test;
// Log.e("text", text);
byte[] testBytes = test.getBytes();
if (intrface == null)
{
Toast.makeText(this, "INTERFACE IS NULL", Toast.LENGTH_SHORT).show();
}
if (connection == null)
{
Toast.makeText(this, "CONNECTION IS NULL", Toast.LENGTH_SHORT).show();
}
if (forceCLaim == null)
{
Toast.makeText(this, "FORCE CLAIM IS NULL", Toast.LENGTH_SHORT).show();
}
connection.claimInterface(intrface, forceCLaim);
connection.bulkTransfer(mEndPoint, testBytes, testBytes.length, 0);
connection.close();
}
I have had this exact behavior from other operating systems, when the printer manufacturer uses a proprietary (and non disclosed :-( ) protocol over the USB bus. Specifically, the HP Laserjet P1060 series comes to mind. Both with GNU/Linux and Mac OS-X, the OS discoveres the printer quite well, and tries to print using a generic driver (e.g. HP Laserjet II). The printer's LED starts flashing - but nothing comes out. This felt a little as if some command was missing to make the printer actually print the page.
In these cases, a proprietary firmware blob needed to be downloaded to make things work. Unfortunately, it may be difficult to find such a driver for Android for home/small business printer models. I have had some luck with the Samsung Mobile Print Application (http://www.samsung.com/us/mobile-print-app/) with departamental networked laser printers (ML 3471-ND and suchlike). This was over Wifi + Ethernet.
HTH.
From your description everything seems to work - data transfer is happening, there are no errors but printing is not producing anything. Possibly because the Samsung printer is a page printer and the code you have is good for line-printing (Pos printers and Dot Matrix). In such a case the data will reside in the print buffer waiting for the page to be completed. Try to force a page to complete by issuing a formfeed and check.

Categories

Resources