Can't get bluetooth Adapter in Android - android

I was trying to implement the bluetooth chat example given in the android samples.
I am running it on a jelly beans device which has Android 4.1 version running on it .
The application simply force closes. A part of launcher activity code of launcher activity goes like this.
WHEN I COMMENT THE LINE "mBluetoothAdapter = BluetoothAdapter.getDefaultAdapter();" THE APPLICATION DOES NOT FORCE CLOSE. and all the toast messages are also displayed which are not with the line uncommented
private BluetoothAdapter mBluetoothAdapter = null;
// Member object for the chat services
private BluetoothChatService mChatService = null;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
Toast.makeText(getApplicationContext(),"BluetothChat oncreate()", Toast.LENGTH_LONG).show();
if(D) Log.e(TAG, "+++ ON CREATE +++");
// Set up the window layout
setContentView(R.layout.main);
// Get local Bluetooth adapter
try {
mBluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
//}
// If the adapter is null, then Bluetooth is not supported
if (mBluetoothAdapter == null) {
Toast.makeText(this, "Bluetooth is not available", Toast.LENGTH_LONG).show();
finish();
return;
}
} catch (Exception e) {
Toast.makeText(this,e.toString(), Toast.LENGTH_LONG).show();
}
}
#Override
public void onStart() {
Toast.makeText(getApplicationContext(),"BluetothChat onstart()", Toast.LENGTH_LONG).show();
super.onStart();
if(D) Log.e(TAG, "++ ON START ++");
// If BT is not on, request that it be enabled.
// setupChat() will then be called during onActivityResult
try {
if (!mBluetoothAdapter.isEnabled()) {
Intent enableIntent = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);
startActivityForResult(enableIntent, REQUEST_ENABLE_BT);
// Otherwise, setup the chat session
} else {
if (mChatService == null) {
setupChat();
}
}
} catch (Exception e) {
Toast.makeText(this,e.toString(), Toast.LENGTH_LONG).show();
}
}

Related

Communicating with Arduino Uno and Android nexus 5

I'm new to android app. I want to read data from my arduino Uno R3 and display it on my app using a serial cable and an OTG adapter.
Although, I can't get my UsbManager to recognized my device. So when I try to set up a connection, it always fail.
Here's the part of my code where I initiate everything.
public UsbManager = mUsbManager;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_display_depth);
setupActionBar();
textView = (TextView) findViewById(R.id.textView2);
mUsbManager = (UsbManager) getSystemService(Context.USB_SERVICE);
button = (Button) findViewById(R.id.buttonStart);
button.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
textView.setText("Bravo");
updateDevice();
if (mRunning == true) {
receiveThread();
}
}
});
}
public void updateDevice() {
Intent intent= getIntent();
String action = intent.getAction();
UsbDevice device = (UsbDevice) intent.getParcelableExtra(UsbManager.EXTRA_DEVICE);
if (device != null){
Toast.makeText(this, "Initialisation 1", Toast.LENGTH_SHORT).show();
initDevice(device);
}
if (UsbManager.ACTION_USB_DEVICE_ATTACHED.equals(action)) {
Toast.makeText(this, "Initialisation", Toast.LENGTH_SHORT).show();
initDevice(device);
} else {
initDevice(null);
}
}
(...) //Obviously, this is not in my code!!
private boolean initDevice(UsbDevice device) {
mConnection = mUsbManager.openDevice(device);
if (mConnection == null) {
if (DEBUG) Log.e(TAG, "Opening USB device failed!");
Toast.makeText(DisplayDepth.this, "open failed", Toast.LENGTH_SHORT).show();
return false;
}
And it always fail here ( I get the toast msg "open failed" ).
I add to my manifest what it takes so my arduino r3 is recognized and a connection message is always shown when I plug it into my phone.... Need help!!!
Thanks

Android want to send bluetooth pair request to another devices

i want to search and listing bluetooth devices in android, my program now able to list all the active devices but not able to send pairing request to the other devices .I want to implement this onItemClick of list element.And also if bluetooth is not enabled of my device then show a permission to active device,if i go for yes then ok,but if i go for no then permission show again until i press yes..how can i do this?plz help with code..here is my code..
public class Main extends Activity {
TextView out;
private static final int REQUEST_ENABLE_BT = 1;
private BluetoothAdapter btAdapter;
private ArrayList<BluetoothDevice> btDeviceList = new ArrayList<BluetoothDevice>();
private ArrayList<String> mylist= new ArrayList<String>();
private ListView lv;
private Button btn;
public Parcelable[] uuidExtra;
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
public void search(View view)
{
//Register the BroadcastReceiver
IntentFilter filter = new IntentFilter(BluetoothDevice.ACTION_FOUND);
filter.addAction(BluetoothDevice.ACTION_UUID);
filter.addAction(BluetoothAdapter.ACTION_DISCOVERY_STARTED);
filter.addAction(BluetoothAdapter.ACTION_DISCOVERY_FINISHED);
registerReceiver(ActionFoundReceiver, filter); // Don't forget to unregister during onDestroy
// Getting the Bluetooth adapter
btAdapter = BluetoothAdapter.getDefaultAdapter();
Toast.makeText(getApplicationContext(),"\nAdapter: " + btAdapter,5000).show();
CheckBTState();
}
private void setDeviceList(ArrayList<String> list) {
lv = (ListView) findViewById(R.id.listView);
ArrayAdapter<String> adapter= new ArrayAdapter<String>(this,android.R.layout.simple_list_item_1,list);
lv.setAdapter(adapter);
}
/* This routine is called when an activity completes.*/
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == REQUEST_ENABLE_BT) {
CheckBTState();
}
}
#Override
protected void onDestroy() {
super.onDestroy();
if (btAdapter != null) {
btAdapter.cancelDiscovery();
}
unregisterReceiver(ActionFoundReceiver);
}
private void CheckBTState() {
// Check for Bluetooth support and then check to make sure it is turned on
// If it isn't request to turn it on
// List paired devices
// Emulator doesn't support Bluetooth and will return null
if(btAdapter==null) {
Toast.makeText(getApplicationContext(),"\nBluetooth NOT supported. Aborting.",5000).show();
return;
} else {
if (btAdapter.isEnabled()) {
Toast.makeText(getApplicationContext(),"\nBluetooth is enabled...",5000).show();
// Starting the device discovery
btAdapter.startDiscovery();
} else if (!btAdapter.isEnabled()){
Intent enableBtIntent = new Intent(btAdapter.ACTION_REQUEST_ENABLE);
startActivityForResult(enableBtIntent, REQUEST_ENABLE_BT);
}
/* else{
Intent intent = new Intent(btAdapter.ACTION_STATE_CHANGED);
startActivityForResult(intent, RESULT_CANCELED);
}*/
}
}
private final BroadcastReceiver ActionFoundReceiver = new BroadcastReceiver(){
#Override
public void onReceive(Context context, Intent intent) {
String action = intent.getAction();
if(BluetoothDevice.ACTION_FOUND.equals(action)) {
BluetoothDevice device = intent.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE);
Toast.makeText(getApplicationContext(),"\n Device: " + device.getName() + ", " + device,5000).show();
mylist.add(device.getName());
setDeviceList(mylist);
} else {
if(BluetoothDevice.ACTION_UUID.equals(action)) {
BluetoothDevice device = intent.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE);
Parcelable[] uuidExtra = intent.getParcelableArrayExtra(BluetoothDevice.EXTRA_UUID);
for (int i=0; i<uuidExtra.length; i++) {
Toast.makeText(getApplicationContext(),"\n Device: " + device.getName() + ", " + device + ", Service: " + uuidExtra[i].toString(),5000).show();
}
} else {
if(BluetoothAdapter.ACTION_DISCOVERY_STARTED.equals(action)) {
Toast.makeText(getApplicationContext(),"\nDiscovery Started...",5000).show();
} else {
if(BluetoothAdapter.ACTION_DISCOVERY_FINISHED.equals(action)) {
Toast.makeText(getApplicationContext(),"\nDiscovery Finished",5000).show();
Iterator<BluetoothDevice> itr = btDeviceList.iterator();
while (itr.hasNext()) {
// Get Services for paired devices
BluetoothDevice device = itr.next();
Toast.makeText(getApplicationContext(),"\nGetting Services for " + device.getName() + ", " + device,5000).show();
if(!device.fetchUuidsWithSdp()) {
Toast.makeText(getApplicationContext(),"\nSDP Failed for " + device.getName(),5000).show();
}
}
}
}
}
}
}
};
}
It's too late but here is code -> You need to use background thread to connect with bluetooth device as a client. and UUID is Universal Uniquely identification you can use online UUID generator. for secure connections and then get socket with device and connect with it;
ConnectWithDevice(context : ConnectWithBluetooth, device : BluetoothDevice) : Thread(){
private val mContext : ConnectWithBluetooth = context
private val mmSocket : BluetoothSocket
private val mmDevice : BluetoothDevice
// Default UUID
private val mmDefaultUUID = UUID.fromString("78c374fd-f84d-4a9e-aa5b-9b0b6292952e")
init {
var temp : BluetoothSocket? = null
mmDevice = device
try {
// Try here device.createInsecureConnect if it's work then start with this;
temp = device.createRfcommSocketToServiceRecord(mmDevice.uuids[0].uuid)
}catch (en : NullPointerException){
en.printStackTrace()
// Try here device.createInsecureConnect if it's work then start with this;
temp = device.createRfcommSocketToServiceRecord(mmDefaultUUID)
}catch (e : IOException){
e.printStackTrace()
Log.e("TAG","Socket's create() method failed",e)
}
mmSocket = temp!!
Log.i("TAG","Got the Socket")
}
override fun run() {
// Cancel discovery because it otherwise slows down the connection.
if(mContext.bluetoothAdapter != null){
mContext.bluetoothAdapter!!.cancelDiscovery()
}
try{
// Connect to the remote device through the socket. This call blocks
// until it succeeds or throws an exception.
Log.i("TAG","Connecting...")
mmSocket.connect()
Log.i("TAG","Bluetooth Successfully Connected")
}catch (connectException : IOException){
// Unable to connect; close the socket and return.
try{
mmSocket.close()
}catch (closeException : IOException){
Log.e("TAG","Could not close the client socket",closeException)
}
return
}
// The connection attempt succeeded. Perform work associated with
// the connection in a separate thread.
Log.i("TAG","Device is Connected")
//manageMyConnectedSocket(mmSocket)
}
// Closes the client socket and causes the thread to finish.
// Call this method from the main activity to shut down the connection.
fun cancel(){
try {
mmSocket.close()
} catch (e: IOException) {
Log.e(ContentValues.TAG, "Could not close the client socket", e)
}
}
}

WIFI P2P stops discovering peers and doesn't accept connections after 2 minutes

I have been messing around with the following issue for about 2 months now.
I am building an application on a custom android board which will act as a wifi display (WFD). When I boot the board, I can easily connect from several different phones (LG Optimus G, LG Optimus G pro, Samsung S3 and S4). After connecting and watching the screen being duplicated on the TV screen attached to the custom board, I can then disconnect and if I reconnect within 2 minutes, I can connect again.
If I boot the board (or disconnect) and then wait 2 minutes, the device no longer sees the phones, and the phones sometimes sees the board, and sometimes not. If the phone sees the board, I can initiate a connect, but I cannot connect succesfully.
I have tried all kind of options, but none seem viable.
The board is running on AOSP 4.2.2
I have right now some complicated code that does restart the discoverPeers function every 40 seconds, as normally it stops after 30 seconds. Besides that I disable WFD and re-enable it, with a 4 second delay between it.
I also tried disabling and reenabling p2p and the channel, all with no result.
Below is my code, the receiver is in a separate class.
#Override
protected void onCreate(Bundle savedInstanceState)
{
Settings.System.putInt(getContentResolver(), Settings.System.WIFI_SLEEP_POLICY, Settings.System.WIFI_SLEEP_POLICY_NEVER);
AudioManager audioManager = (AudioManager) getSystemService(Context.AUDIO_SERVICE);
audioManager.setStreamVolume(AudioManager.STREAM_MUSIC,
audioManager.getStreamMaxVolume(AudioManager.STREAM_MUSIC), 0);
setContentView(R.layout.wifi_direct_discovery);
connectPicture = findViewById(R.id.LinearLayout1);
Log.d(TAG, "onCreate");
isConnecting = false;
localWifiP2pWfdInfo = new WifiP2pWfdInfo();
localWifiP2pWfdInfo.setWfdEnabled(true);
localWifiP2pWfdInfo.setDeviceType(1);
localWifiP2pWfdInfo.setSessionAvailable(true);
localWifiP2pWfdInfo.setControlPort(7236);
localWifiP2pWfdInfo.setMaxThroughput(50);
final PowerManager pm = (PowerManager) getSystemService(Context.POWER_SERVICE);
PowerManager.WakeLock wl = pm.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, "My Tag");
wl.acquire();
super.onCreate(savedInstanceState);
}
#Override
public void onPeersAvailable(WifiP2pDeviceList peers)
{
List<WifiP2pDevice> peersList = new ArrayList<WifiP2pDevice>();
final ArrayList<String> list = new ArrayList<String>();
final ListView listview = (ListView) findViewById(R.id.deviceListView);
peersList.clear();
peersList.addAll(peers.getDeviceList());
if (peersList.size() == 0)
{
Log.d(TAG, "No devices found");
list.clear();
if ((pd != null) && pd.isShowing() && (isConnecting == false))
{
pd.dismiss();
Log.d(TAG, "Closed connecting dialog, restarting P2P");
Toast.makeText(this, "Connection failed please try again", Toast.LENGTH_LONG).show();
restartP2p(false);
}
else if (isConnecting == false)
{
restartP2p(false);
}
listview.setAdapter(new ArrayAdapter<String>(this, R.layout.list_black_text, R.id.list_content, list));
return;
}
else
{
int i = 0;
boolean found = false;
for (i = 0; i < peersList.size(); i++)
{
Log.d(TAG, "Found device: " + peersList.get(i).toString());
list.add(peersList.get(i).deviceName);
if ((pd != null) && pd.isShowing())
{
if (peersList.get(i).deviceAddress.equalsIgnoreCase(client.deviceAddress))
{
found = true;
}
}
}
if (!found)
{
if ((pd != null) && pd.isShowing())
{
Log.d(TAG, "Failed to find current client: closed connecting dialog, restarting P2P");
Toast.makeText(this, "Disconnected please try again", Toast.LENGTH_LONG).show();
restartP2p(false);
}
else
{
Log.d(TAG, "Failed to find current client, but we weren't trying to connect");
}
}
}
listview.setAdapter(new ArrayAdapter<String>(this, R.layout.list_black_text, R.id.list_content, list));
}
#Override
public void onConnectionInfoAvailable(WifiP2pInfo p2pInfo)
{
if (p2pInfo.isGroupOwner)
{
stopP2PDispeerTimeoutThread();
Log.d(TAG, "Connected as group owner");
int i = p2pInfo.mWfdRtspPort;
Log.d(TAG, "------------------------- onConnectionInfoAvailable rtsp port = " + i);
// get the ip addres from the connected client. Mac address is in
// client
String sourceIP = null;
while (sourceIP == null)
{
sourceIP = getIPFromMac(client.deviceAddress);
millisleep(250);
if (sourceIP == null)
{
Log.e(TAG, "Failed to get client address!!!!! from " + client.deviceAddress);
}
}
if (i == 0)
{
// this is not a wfd source, so let's get into client mode for
// upgrade etc.
Log.e(TAG, "This device is not a WFD source, so switch to client mode, device = "
+ client.deviceAddress);
}
else
{
Log.d(TAG, "Start connect to source : " + sourceIP);
if ((pd != null) && pd.isShowing())
pd.dismiss();
// need to stop the connection timeout thread here..
stopConnectTimeoutThread();
Intent intent = new Intent(getBaseContext(), WFDPlayActivity.class);
intent.putExtra("SOURCE_IP", sourceIP);
intent.putExtra("RTSPPORT", i);
startActivityForResult(intent, 210);
}
}
else
{
Log.e(TAG, "Connected as peer, this is very very wrong!!!!, restartP2P");
restartP2p(false);
startP2PDispeerTimeoutThread(34);
}
}
#Override
public void onConnectionRequested(WifiP2pDevice arg0, WifiP2pConfig arg1)
{
Log.d(TAG, "------------------------------------- onConnectionRequested");
stopP2PDispeerTimeoutThread();
isConnecting = true;
client = arg0;
if ((pd != null) && (pd.isShowing()))
{
pd.dismiss();
}
if (client != null)
{
createConnectionProgressDialog(client.deviceName);
}
}
public void onResume()
{
if (first_time == false)
{
Log.d(TAG, "onResume");
intentFilter.addAction("android.net.wifi.p2p.STATE_CHANGED");
intentFilter.addAction("android.net.wifi.p2p.PEERS_CHANGED");
intentFilter.addAction("android.net.wifi.p2p.CONNECTION_STATE_CHANGE");
intentFilter.addAction("android.net.wifi.p2p.THIS_DEVICE_CHANGED");
registerReceiver(receiver, intentFilter);
if (!mP2PDispeerThread.isRunning)
startP2PDispeerTimeoutThread(34);
manager.setDialogListener(channel, this);
manager.discoverPeers(channel, new WifiP2pManager.ActionListener()
{
#Override
public void onSuccess()
{
Log.d(TAG, "discoverPeers success");
}
#Override
public void onFailure(int reasonCode)
{
Log.d(TAG, "discoverPeers failed");
}
});
}
else
{
Log.d(TAG, "onResume, first time");
restartP2p(first_time);
first_time = false;
}
getWindow().getDecorView().setSystemUiVisibility(View.SYSTEM_UI_FLAG_HIDE_NAVIGATION);
super.onResume();
}
public void restartP2p(boolean first)
{
if (first)
{
mWifiManager = ((WifiManager) getSystemService("wifi"));
mWifiManager.setWifiEnabled(true);
sleep(4); // was 4
manager = (WifiP2pManager) getSystemService(Context.WIFI_P2P_SERVICE);
channel = manager.initialize(this, getMainLooper(), null);
manager.enableP2p(channel);
sleep(3); // was 3
mDisplayManager = ((DisplayManager) getSystemService("display"));
intentFilter.addAction(WifiP2pManager.WIFI_P2P_STATE_CHANGED_ACTION);
intentFilter.addAction(WifiP2pManager.WIFI_P2P_PEERS_CHANGED_ACTION);
intentFilter.addAction(WifiP2pManager.WIFI_P2P_CONNECTION_CHANGED_ACTION);
intentFilter.addAction(WifiP2pManager.WIFI_P2P_THIS_DEVICE_CHANGED_ACTION);
mlock = mWifiManager.createWifiLock(WifiManager.WIFI_MODE_FULL_HIGH_PERF , "LockTag");
mlock.acquire();
instance = this;
receiver = new WiFiDirectBroadcastReceiver(manager, channel, this);
registerReceiver(receiver, intentFilter);
manager.setWFDInfo(channel, localWifiP2pWfdInfo, new WifiP2pManager.ActionListener()
{
public void onFailure(int paramAnonymousInt)
{
Log.d(TAG, "Failed to set WFD info with reason " + paramAnonymousInt + ".");
}
public void onSuccess()
{
Log.d(TAG, "updateWfdEnableState");
}
});
sleep(1);
manager.setDialogListener(channel, this);
manager.discoverPeers(channel, new WifiP2pManager.ActionListener()
{
#Override
public void onSuccess()
{
Log.d(TAG, "discoverPeers success");
}
#Override
public void onFailure(int reasonCode)
{
Log.d(TAG, "discoverPeers failed");
}
});
}
else
{
manager.stopPeerDiscovery(channel, new WifiP2pManager.ActionListener()
{
#Override
public void onSuccess()
{
Log.d(TAG, "stopPeerDiscovery success");
}
#Override
public void onFailure(int reasonCode)
{
Log.d(TAG, "stopPeerDiscovery failed");
}
});
localWifiP2pWfdInfo.setWfdEnabled(false);
manager.setWFDInfo(channel, localWifiP2pWfdInfo, new WifiP2pManager.ActionListener()
{
public void onFailure(int paramAnonymousInt)
{
Log.d(TAG, "Failed to set WFD info with reason " + paramAnonymousInt + ".");
}
public void onSuccess()
{
Log.d(TAG, "updateWfdEnableState");
}
});
sleep(4);
localWifiP2pWfdInfo.setWfdEnabled(true);
manager.setWFDInfo(channel, localWifiP2pWfdInfo, new WifiP2pManager.ActionListener()
{
public void onFailure(int paramAnonymousInt)
{
Log.d(TAG, "Failed to set WFD info with reason " + paramAnonymousInt + ".");
}
public void onSuccess()
{
Log.d(TAG, "updateWfdEnableState");
}
});
manager.discoverPeers(channel, new WifiP2pManager.ActionListener()
{
#Override
public void onSuccess()
{
Log.d(TAG, "discoverPeers success");
}
#Override
public void onFailure(int reasonCode)
{
Log.d(TAG, "discoverPeers failed");
}
});
}
if (first)
startP2PDispeerTimeoutThread(40); // only start the thread 1 time...
}
In the logging initially I see that the device and the phone connect successfully.
After disconnect, I see the devices being lost in the log, and after that, when I try to connect, I see the message:
I/wpa_supplicant(1839): [CTRL_IFACE]p2p0: P2P_CONNECT da:57:ef:cb:8e:be pbc go_intent=0
After this everything stops, the application is still running, I could see that from a log line that runs every second in the thread that stops and restarts the discovery every 40 seconds.
If anyone has any idea left why this behavior is happening, let me know. The only way to recover right now is to reboot the board (but that is not an option).
Thanks for your replies,
Arvy

android bluetooth can't connect

I've been having this problem for a while and haven't been able to figure it out.
I have a android application that puts all paired devices in a listview. When you click one of the list items, it will initiate a request to connect to that bluetooth device.
I can get the list of devices with their addresses no problem.
The problem is that once I try to connect I get an IOException on socket.connect();
The error message is as follows:
"connect read failed, socket might closed or timeout, read ret: -1"
Here is my code. ANY suggestions would be appreciated. I'm pretty stuck on this.
fyi: the "onEvent" methods is a library that simplifies callbacks...that part works.
When the user clicks on a list items this method is called "public void onEvent(EventMessage.DeviceSelected event)"
public class EcoDashActivity extends BaseActivity {
public static final UUID MY_UUID = UUID.fromString("00001101-0000-1000-8000-00805F9B34FB");
private BluetoothAdapter mBluetoothAdapter;
private int REQUEST_ENABLE_BT = 100;
private ArrayList<BluetoothDevice> mDevicesList;
private BluetoothDeviceDialog mDialog;
private ProgressDialog progressBar;
private int progressBarStatus = 0;
private Handler progressBarHandler = new Handler();
#Override
public void onCreate(final Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
requestWindowFeature(Window.FEATURE_NO_TITLE);
setContentView(R.layout.main);
mDevicesList = new ArrayList<BluetoothDevice>();
// Register the BroadcastReceiver
IntentFilter filter = new IntentFilter(BluetoothDevice.ACTION_FOUND);
registerReceiver(mReceiver, filter);
setupBluetooth();
}
private void setupBluetooth() {
mBluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
if (mBluetoothAdapter == null) {
// Device does not support Bluetooth
Toast.makeText(this, "Device does not support Bluetooth", Toast.LENGTH_SHORT).show();
}
if (!mBluetoothAdapter.isEnabled()) {
Intent enableBtIntent = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);
startActivityForResult(enableBtIntent, REQUEST_ENABLE_BT);
} else {
searchForPairedDevices();
mDialog = new BluetoothDeviceDialog(this, mDevicesList);
mDialog.show(getFragmentManager(), "");
}
}
private void searchForPairedDevices() {
Set<BluetoothDevice> pairedDevices = mBluetoothAdapter.getBondedDevices();
// If there are paired devices
if (pairedDevices.size() > 0) {
// Loop through paired devices
for (BluetoothDevice device : pairedDevices) {
// Add the name and address to an array adapter to show in a ListView
mDevices.add(device.getName() + "\n" + device.getAddress());
mDevicesList.add(device);
}
}
}
private final BroadcastReceiver mReceiver = new BroadcastReceiver() {
public void onReceive(Context context, Intent intent) {
String action = intent.getAction();
// When discovery finds a device
if (BluetoothDevice.ACTION_FOUND.equals(action)) {
// Get the BluetoothDevice object from the Intent
BluetoothDevice device = intent.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE);
// Add the name and address to an array adapter to show in a ListView
mDevicesList.add(device);
}
}
};
#Override
protected void onDestroy() {
super.onDestroy();
unregisterReceiver(mReceiver);
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if (requestCode == REQUEST_ENABLE_BT) {
if (resultCode == RESULT_OK) {
Toast.makeText(this, "BT turned on!", Toast.LENGTH_SHORT).show();
searchForPairedDevices();
mDialog = new BluetoothDeviceDialog(this, mDevicesList);
mDialog.show(getFragmentManager(), "");
}
}
super.onActivityResult(requestCode, resultCode, data);
}
public void onEvent(EventMessage.DeviceSelected event) {
mDialog.dismiss();
BluetoothDevice device = event.getDevice();
ConnectThread connectThread = new ConnectThread(device);
connectThread.start();
}
public class ConnectThread extends Thread {
private final BluetoothSocket mmSocket;
private final BluetoothDevice mmDevice;
public ConnectThread(BluetoothDevice device) {
// Use a temporary object that is later assigned to mmSocket,
// because mmSocket is final
BluetoothSocket tmp = null;
mmDevice = device;
// Get a BluetoothSocket to connect with the given BluetoothDevice
try {
// MY_UUID is the app's UUID string, also used by the server code
tmp = device.createRfcommSocketToServiceRecord(MY_UUID);
} catch (IOException e) { }
mmSocket = tmp;
}
public void run() {
setName("ConnectThread");
// Cancel discovery because it will slow down the connection
mBluetoothAdapter.cancelDiscovery();
try {
// Connect the device through the socket. This will block
// until it succeeds or throws an exception
Log.d("kent", "trying to connect to device");
mmSocket.connect();
Log.d("kent", "Connected!");
} catch (IOException connectException) {
// Unable to connect; close the socket and get out
try {
Log.d("kent", "failed to connect");
mmSocket.close();
} catch (IOException closeException) { }
return;
}
Log.d("kent", "Connected!");
}
/** Will cancel an in-progress connection, and close the socket */
public void cancel() {
try {
mmSocket.close();
} catch (IOException e) { }
}
}
Here is my logcat. Pretty short.
07-22 10:37:05.129: DEBUG/kent(17512): trying to connect to device
07-22 10:37:05.129: WARN/BluetoothAdapter(17512): getBluetoothService() called with no BluetoothManagerCallback
07-22 10:37:05.129: DEBUG/BluetoothSocket(17512): connect(), SocketState: INIT, mPfd: {ParcelFileDescriptor: FileDescriptor[98]}
07-22 10:37:40.757: DEBUG/dalvikvm(17512): GC_CONCURRENT freed 6157K, 9% free 62793K/68972K, paused 7ms+7ms, total 72ms
07-22 10:38:06.975: DEBUG/kent(17512): failed to connect
07-22 10:38:06.975: DEBUG/kent(17512): read failed, socket might closed or timeout, read ret: -1
That last line is in the "Catch" section of a try/catch...I'm just logging the error message.
Please note, there is about a 20 second gap between "trying to connect to device" and "failed to connect"
The jelly bean bluetooth stack is markedly different from the other versions.
This might help: http://wiresareobsolete.com/wordpress/2010/11/android-bluetooth-rfcomm/
In gist:
The UUID is a value that must point to a published service on your embedded device, it is not just randomly generated. The RFCOMM SPP connection you want to access has a specific UUID that it publishes to identify that service, and when you create a socket it must match the same UUID.
If you are targeting 4.0.3 device and above , use fetchUuidsWithSdp() and getUuids() to find all the published services and their associated UUID values. For backward compatibility read the article
I got the same error message after connecting the socket a second time. I simply checked if the socket is already connected.
if(!mmSocket.isConnected())
mmSocket.connect();
I was testing on Android 4.4.2 (Moto G).

Android bluetooth application process killed

I'm very new with programming for android. I have two classes : main and btmanager. When i try to test my app on phone, all I get is a information that procees was killed. What am I doing wrong ?
Code implementation :
Main class :
public class MainActivity extends Activity {
BluetoothAdapter bluetooth = BluetoothAdapter.getDefaultAdapter();
Btmanager manager;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
if (bluetooth == null)
{
Toast.makeText(this, "Bluetooth is not enabled on this device", Toast.LENGTH_LONG).show();
System.exit(0);
}
}
#Override
public void onStart()
{
super.onStart();
if (!bluetooth.isEnabled()) {
Intent enableBtIntent = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);
startActivityForResult(enableBtIntent, 2);
}
manager.run();
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.activity_main, menu);
return true;
}
public void closeApp (View view)
{
System.exit(0);
}
}
Btmanager class :
public class Btmanager extends Thread {
private final BluetoothSocket mmSocket;
private final BluetoothDevice mmDevice;
public static final UUID myUUID = UUID.fromString("0x1101");
BluetoothAdapter bluetooth = BluetoothAdapter.getDefaultAdapter();
public Btmanager(BluetoothDevice device) {
// Use a temporary object that is later assigned to mmSocket,
// because mmSocket is final
BluetoothSocket tmp = null;
mmDevice = device;
// Get a BluetoothSocket to connect with the given BluetoothDevice
try {
// MY_UUID is the app's UUID string, also used by the server code
tmp = device.createRfcommSocketToServiceRecord(myUUID);
} catch (IOException e) { }
mmSocket = tmp;
}
public void run() {
// Cancel discovery because it will slow down the connection
bluetooth.cancelDiscovery();
try {
// Connect the device through the socket. This will block
// until it succeeds or throws an exception
mmSocket.connect();
} catch (IOException connectException) {
// Unable to connect; close the socket and get out
try {
mmSocket.close();
} catch (IOException closeException) { }
return;
}
}
/** Will cancel an in-progress connection, and close the socket */
public void cancel() {
try {
mmSocket.close();
} catch (IOException e) { }
}
2 problems I see in your code:
You don't instantiate the Btmanager object, it is still null when you call run. (Will cause a NullPointerException - your app will crash).
You call the run method instead of the start method of the Btmanager. If you want the code in the run method to run in a new thread, you have to call start. Calling run will cause it to run in the same thread. This blocks your UI thread which may cause your app to crash, if it blocks for too long.
For test purporses, I don't use BTmanager class - in onStart() method I add new thread with connection implentation, but still without any results - app crash.
public void onStart()
{
super.onStart();
if (!bluetooth.isEnabled()) {
Intent enableBtIntent = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);
startActivityForResult(enableBtIntent, 2);
}
new Thread(new Runnable()
{
public void run()
{
try {
//Create a Socket connection: need the server's UUID number of registered
socket = device.createRfcommSocketToServiceRecord(myUUID);
socket.connect();
Log.d("EF-BTBee", "Connectted");
}
catch (IOException e)
{
Log.e("EF-BTBee", "Error : ", e);
}
}
}).start();
}

Categories

Resources