Android Studio Class or interface expected - java

The problem as seen in the title appears in line 102 of the code down below. Im very new to this topic and Im trying to make an app which can control an arduino... This part of code I show you is supposed to manage the connection to the Bluetooth Module and in my MainActivity I plan to send the letters to the other device.
I hope someone can help.
My code (BT_Classic.java):
package com.car.bluetooth.bluetoothcar;
import androidx.appcompat.app.AppCompatActivity;
import android.app.ProgressDialog;
import android.bluetooth.BluetoothAdapter;
import android.bluetooth.BluetoothDevice;
import android.bluetooth.BluetoothSocket;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.ListView;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Set;
import java.util.UUID;
public class BT_Classic extends AppCompatActivity {
private Button pairedButton;
private Button discoveredButton;
private Button btonButton;
private Button btoffButton;
private ProgressDialog progress;
ListView listView;
BluetoothSocket bluetoothSocket;
BluetoothDevice bluetoothDevice;
private final static UUID uuid = UUID.fromString("fc5ffc49-00e3-4c8b-9cf1-6b72aad1001a");
private ArrayList<String> mDeviceList = new ArrayList<String>();
BluetoothAdapter btAdapter = BluetoothAdapter.getDefaultAdapter();
//BLUETOOTH VERBINDUNG
private static final int REQUEST_ENABLED = 0;
private static final int REQUEST_DISCOVERABLE = 0;
private class ConnectingThread extends Thread {
public ConnectingThread(BluetoothDevice device) {
BluetoothSocket temp = null;
BluetoothDevice bluetoothDevice = device;
// Get a BluetoothSocket to connect with the given BluetoothDevice
try {
temp = bluetoothDevice.createRfcommSocketToServiceRecord(uuid);
} catch (IOException e) {
e.printStackTrace();
}
bluetoothSocket = temp;
}
public void run() {
// Cancel any discovery as it will slow down the connection
btAdapter.cancelDiscovery();
try {
// This will block until it succeeds in connecting to the device
// through the bluetoothSocket or throws an exception
bluetoothSocket.connect();
} catch (IOException connectException) {
connectException.printStackTrace();
try {
bluetoothSocket.close();
} catch (IOException closeException) {
closeException.printStackTrace();
}
}
// Code to manage the connection in a separate thread
/*
manageBluetoothConnection(bluetoothSocket);
*/
}
// Cancel an open connection and terminate the thread
public void cancel() {
try {
bluetoothSocket.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_bt__classic);
pairedButton = (Button) findViewById(R.id.pairedButton);
discoveredButton = (Button) findViewById(R.id.discoveredButton);
btonButton = (Button) findViewById(R.id.btonButton);
btoffButton = (Button) findViewById(R.id.btoffButton);
listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
String itemValue = (String) listView.getItemAtPosition(position);
String MAC = itemValue.substring(itemValue.length() - 17);
BluetoothDevice bluetoothDevice = btAdapter.getRemoteDevice(MAC);
// Initiate a connection request in a separate thread
ConnectingThread t = new ConnectingThread(bluetoothDevice);
t.start();
}
});
//Pairing Button
pairedButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Set<BluetoothDevice> pairedDevices = btAdapter.getBondedDevices();
ArrayList<String> devices = new ArrayList<String>();
for (BluetoothDevice bt : pairedDevices){
devices.add(bt.getName());
devices.add(bt.getAddress());
}
ArrayAdapter arrayAdapter = new ArrayAdapter(BT_Classic.this, android.R.layout.simple_list_item_1, devices);
listView.setAdapter(arrayAdapter);
}
});
discoveredButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if(!btAdapter.isDiscovering()){
Intent bton = new Intent(BluetoothAdapter.ACTION_REQUEST_DISCOVERABLE);
startActivityForResult(bton, REQUEST_DISCOVERABLE);
}
}
});
btonButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent bton = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);
startActivityForResult(bton, REQUEST_ENABLED);
}
});
btoffButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
btAdapter.disable();
}
});
}
}

You have an extra } in this section
public void cancel() {
try {
bluetoothSocket.close();
} catch (IOException e) {
e.printStackTrace();
} // Close try
} // Close cancel()
} // Close ConnectingThread
} // DELETE THIS CURLY BRACE

First, it was problem with extra curly braces as Chris has mentioned.
Second, you haven't define your ListView as listView = findViewById(R.id.your_id);
That's it, and good luck. :)

Related

I'm trying to implement Bluetooth functionality in Android Studio, need some help in connecting problem

I used Bluetooth API and following code is for on/off, show paired devices list, and connect paired devices.
other functions work well, but connecting devices doesn't work .
I try to use thread bidirectional, when bluetooth turns on, serverthread(acceptthread) generated and started. And when I choose device on the list, clientthread(connectthread) generated and started. This is my intent, but when I try to connect on the phone, app is turned off(almost at the client, occasionally at the server).
I thought maybe it's UUID problem so I checked UUID 00enter code here001101-0000-1000-8000-00805F9B34FB, but it didn't help.enter code here
sorry for the import code chunks, I would really appreciate your help.
'''
package com.practice.bluetoothmodule;
import androidx.appcompat.app.AlertDialog;
import androidx.appcompat.app.AppCompatActivity;
import android.bluetooth.BluetoothAdapter;
import android.bluetooth.BluetoothDevice;
import android.bluetooth.BluetoothServerSocket;
import android.bluetooth.BluetoothSocket;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.SystemClock;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.UnsupportedEncodingException;
import java.util.ArrayList;
import java.util.List;
import java.util.Set;
import java.util.UUID;
import java.util.concurrent.ExecutionException;
public class MainActivity extends AppCompatActivity {
TextView bthStatus;
Button bthOn;
Button bthOff;
Button bthCon;
BluetoothAdapter bthAdapter;
Set<BluetoothDevice> pairedDevices;
List<String> listofPairedDevices;
private String btAddress=null;
BluetoothDevice bthDevice;
AcceptThread acceptThread;
ConnectThread connectThread;
private Handler mHandler = null;
final static int BT_REQUEST_ENABLE=1;
final static UUID BT_UUID = UUID.fromString("fa87c0d0-afac-11de-8a39-0800200c9a66");
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
bthStatus = (TextView)findViewById(R.id.text_check);
bthOn = (Button)findViewById(R.id.bth_on);
bthOff=(Button)findViewById(R.id.bth_off);
bthCon=(Button)findViewById(R.id.dev_con);
bthAdapter=BluetoothAdapter.getDefaultAdapter();
bthOn.setOnClickListener(new Button.OnClickListener(){
#Override
public void onClick(View view){
bluetoothOn();
}
});
bthOff.setOnClickListener(new Button.OnClickListener(){
#Override
public void onClick(View view){
bluetoothOff();
}
});
bthCon.setOnClickListener(new Button.OnClickListener(){
#Override
public void onClick(View view){
listPairedDevices();
}
});
}
#Override
public void onStart(){
super.onStart();
}
#Override
public void onDestroy(){
super.onDestroy();
if(acceptThread != null){
acceptThread.cancel();
acceptThread=null;
}
if(connectThread != null){
connectThread.cancel();
connectThread=null;
}
}
void bluetoothOn(){
if(bthAdapter == null){
Toast.makeText(getApplicationContext(),"블루투스를 지원하지 않는 기기입니다",Toast.LENGTH_SHORT).show();
}
else{
if(bthAdapter.isEnabled()){
Toast.makeText(getApplicationContext(),"블루투스가 이미 활성화된 상태입니다",Toast.LENGTH_SHORT).show();
}
else{
Toast.makeText(getApplicationContext(),"블루투스가 활성화 되어 있지 않습니다",Toast.LENGTH_SHORT).show();
Intent intentBthEnable = new Intent(bthAdapter.ACTION_REQUEST_ENABLE);
startActivityForResult(intentBthEnable,BT_REQUEST_ENABLE);
}
}
}
void bluetoothOff(){
if(bthAdapter.isEnabled()){
bthAdapter.disable();
Toast.makeText(getApplicationContext(),"블루투스가 비활성화 되었습니다.",Toast.LENGTH_SHORT).show();
bthStatus.setText("비활성화");
}
else{
Toast.makeText(getApplicationContext(),"블루투스가 이미 비활성화 상태입니다",Toast.LENGTH_SHORT).show();
}
}
#Override
protected void onActivityResult(int requestCode,int resultCode,Intent data){
switch(requestCode){
case BT_REQUEST_ENABLE:
if(resultCode == RESULT_OK){
Toast.makeText(getApplicationContext(),"블루투스 활성화",Toast.LENGTH_LONG).show();
bthStatus.setText("활성화");
start();
} else if(resultCode == RESULT_CANCELED){
Toast.makeText(getApplicationContext(),"취소",Toast.LENGTH_LONG).show();
bthStatus.setText("비활성화");
}
break;
}
super.onActivityResult(requestCode,resultCode,data);
}
void listPairedDevices(){
if(bthAdapter.isEnabled()){
pairedDevices = bthAdapter.getBondedDevices();
if(pairedDevices.size()>0){
AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setTitle("장치 선택");
listofPairedDevices = new ArrayList();
for(BluetoothDevice device: pairedDevices){
listofPairedDevices.add(device.getName());
}
final CharSequence[] items= listofPairedDevices.toArray(new CharSequence[listofPairedDevices.size()]);
listofPairedDevices.toArray(new CharSequence[listofPairedDevices.size()]);
builder.setItems(items, new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int item) {
connectSelectedDevice(items[item].toString());
}
});
AlertDialog alert=builder.create();
alert.show();
}
else{
Toast.makeText(getApplicationContext(),"페어링된 장치가 없습니다",Toast.LENGTH_LONG).show();
}
}
else{
Toast.makeText(getApplicationContext(),"블루투스가 비활성화 되어 있습니다.",Toast.LENGTH_LONG).show();
}
}
void connectSelectedDevice(String selectedDeviceName){
for(BluetoothDevice tempDevice: pairedDevices){
if(selectedDeviceName.equals(tempDevice.getName())){
bthDevice=tempDevice;
btAddress=bthDevice.getAddress();
break;
}
}
connect(bthDevice);
//Toast.makeText(getApplicationContext(),"연결 시도"+bthDevice.getName(),Toast.LENGTH_LONG).show();
}
public synchronized void start(){
acceptThread = new AcceptThread();
acceptThread.start();
}
public synchronized void connect(BluetoothDevice device){
connectThread=new ConnectThread(device);
connectThread.start();
}
private class AcceptThread extends Thread{
private final BluetoothServerSocket mmServerSocket;
public AcceptThread(){
BluetoothServerSocket tmp=null;
try{
tmp=bthAdapter.listenUsingRfcommWithServiceRecord("Listen",BT_UUID);
Toast.makeText(getApplicationContext(),"서버 열림",Toast.LENGTH_LONG).show();
}catch(IOException e){
Toast.makeText(getApplicationContext(),"서버 안열림",Toast.LENGTH_LONG).show();
}
mmServerSocket=tmp;
}
public void run(){
BluetoothSocket socket=null;
while(true){
try{
socket=mmServerSocket.accept();
} catch(IOException e){
break;
}
if(socket != null){
Toast.makeText(getApplicationContext(),"연결됨",Toast.LENGTH_SHORT).show();
try{
sleep(3000);
} catch (Exception e){}
}
}
}
public void cancel(){
try{
mmServerSocket.close();
} catch(IOException e){
e.printStackTrace();
}
}
}
private class ConnectThread extends Thread{
private final BluetoothSocket mmSocket;
private final BluetoothDevice mmDevice;
public ConnectThread(BluetoothDevice device){
BluetoothSocket tmp=null;
mmDevice=device;
try{
tmp=device.createRfcommSocketToServiceRecord(BT_UUID);
//Toast.makeText(getApplicationContext(),"클라 초기화 됨.",Toast.LENGTH_LONG).show();
}catch (IOException e){
//Toast.makeText(getApplicationContext(),"클라 초기화 실패.",Toast.LENGTH_LONG).show();
}
mmSocket=tmp;
//Toast.makeText(getApplicationContext(),"클라 초기화",Toast.LENGTH_LONG).show();
}
public void run() {
try {
bthAdapter.cancelDiscovery();
mmSocket.connect();
Toast.makeText(getApplicationContext(), "클라이언트 연결", Toast.LENGTH_LONG).show();
} catch (IOException e) {
Toast.makeText(getApplicationContext(), "연결실패", Toast.LENGTH_LONG).show();
}
}
public void cancel(){
try{
mmSocket.close();
} catch (IOException e){
e.printStackTrace();
}
}
}
}
'''
With Android device, Enable BluetoothHCISnoop log to know , what is happening . It will give the sequential flow on what is happening with Bluetooth communication.
https://www.androidcentral.com/all-about-your-phones-developer-options
The following reasons may be the cause:
1. In your code the device address may be wrong
2. The service UUID which you are trying to connect should be present in the service discovery database of remote bluetooth device
3. The app should wait for connect to happen How to programmatically tell if a Bluetooth device is connected?

How to connect multiple clients to one host via Wifi P2P

I'm trying to create a WiFiP2P to communicate with 2 android phones and one Raspberry Pi. I want one phone as host and the second phone + Raspberry Pi as clients.
Until know i could create a test APP to connect the 2 phones via Wifi direct (tested successful). I was following a great tutorial on Youtube Wifi P2P. Unfortunately the tutorial just show how to connect one host with one client and not multiple clients.
I was trying to follow the Android developer guide, but I have not enough experience to understand everything.
I hope you guys can help me to understand what I have to change in my code and explain me why.
The following code is the exact copy from the mentioned tutorial.
Here my MainActivity:
package com.example.wifip2p;
import android.Manifest;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.IntentFilter;
import android.content.pm.PackageManager;
import android.net.wifi.WifiManager;
import android.net.wifi.p2p.WifiP2pConfig;
import android.net.wifi.p2p.WifiP2pDevice;
import android.net.wifi.p2p.WifiP2pDeviceList;
import android.net.wifi.p2p.WifiP2pGroup;
import android.net.wifi.p2p.WifiP2pInfo;
import android.net.wifi.p2p.WifiP2pManager;
import android.os.Handler;
import android.os.Message;
import android.os.StrictMode;
import android.support.v4.app.ActivityCompat;
import android.support.v4.content.ContextCompat;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.InetAddress;
import java.net.InetSocketAddress;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.ArrayList;
import java.util.List;
public class MainActivity extends AppCompatActivity {
Button btnOnOff, btnDiscover, btnSend;
ListView listView;
TextView read_msg_box, connectionStatus;
EditText writeMsg;
WifiManager wifiManager;
WifiP2pManager mManager;
WifiP2pManager.Channel mChannel;
BroadcastReceiver mReceiver;
IntentFilter mIntentFilter;
List<WifiP2pDevice> peers = new ArrayList<WifiP2pDevice>();
String[] deviceNameArray;
WifiP2pDevice[] deviceArray;
static final int MESSAGE_READ=1;
ServerClass serverClass;
ClientClass clientClass;
SendReceive sendReceive;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().permitAll().build();
StrictMode.setThreadPolicy(policy);
if (ContextCompat.checkSelfPermission(this, Manifest.permission.ACCESS_COARSE_LOCATION)
!= PackageManager.PERMISSION_GRANTED) {
// Permission is not granted
ActivityCompat.requestPermissions(this,
new String[]{Manifest.permission.ACCESS_COARSE_LOCATION},
1);
}
initialWork();
exqListener();
}
Handler handler = new Handler(new Handler.Callback() {
#Override
public boolean handleMessage(Message msg) {
switch (msg.what){
case MESSAGE_READ:
byte[] readBuff = (byte[])msg.obj;
String tempMsg = new String(readBuff,0,msg.arg1);
read_msg_box.setText(tempMsg);
break;
}
return true;
}
});
private void exqListener() {
btnOnOff.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
if(wifiManager.isWifiEnabled()){
wifiManager.setWifiEnabled(false);
btnOnOff.setText("ON");
if(mManager!=null) {
mManager.removeGroup(mChannel, null);
}
}else{
wifiManager.setWifiEnabled(true);
btnOnOff.setText("OFF");
}
}
});
btnDiscover.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
mManager.discoverPeers(mChannel, new WifiP2pManager.ActionListener() {
#Override
public void onSuccess() {
connectionStatus.setText("Discovery Started");
}
#Override
public void onFailure(int reason) {
connectionStatus.setText("Discovery Starting Failed");
}
});
}
});
listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int i, long l) {
final WifiP2pDevice device = deviceArray[i];
WifiP2pConfig config = new WifiP2pConfig();
config.deviceAddress = device.deviceAddress;
mManager.connect(mChannel, config, new WifiP2pManager.ActionListener() {
#Override
public void onSuccess() {
Toast.makeText(getApplicationContext(),"Connected to " + device.deviceName, Toast.LENGTH_LONG).show();
}
#Override
public void onFailure(int reason) {
Toast.makeText(getApplicationContext(),"Not Connected",Toast.LENGTH_SHORT).show();
}
});
}
});
btnSend.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
String msg = writeMsg.getText().toString();
Toast.makeText(getApplicationContext(),"MSG: " + msg,Toast.LENGTH_SHORT).show();
sendReceive.write(msg.getBytes());
}
});
}
private void initialWork() {
btnOnOff= findViewById(R.id.onOff);
btnDiscover = findViewById(R.id.discover);
btnSend = findViewById(R.id.sendButton);
listView = findViewById(R.id.peerListView);
read_msg_box = findViewById(R.id.readMsg);
connectionStatus = findViewById(R.id.connectionStatus);
writeMsg = findViewById(R.id.writeMsg);
wifiManager = (WifiManager) getApplicationContext().getSystemService(Context.WIFI_SERVICE);
mManager = (WifiP2pManager) getSystemService(Context.WIFI_P2P_SERVICE);
mChannel = mManager.initialize(this, getMainLooper(),null);
mReceiver = new WiFiDirectBroadcastReceiver(mManager, mChannel, this);
mIntentFilter = new IntentFilter();
mIntentFilter.addAction(WifiP2pManager.WIFI_P2P_STATE_CHANGED_ACTION);
mIntentFilter.addAction(WifiP2pManager.WIFI_P2P_PEERS_CHANGED_ACTION);
mIntentFilter.addAction(WifiP2pManager.WIFI_P2P_CONNECTION_CHANGED_ACTION);
mIntentFilter.addAction(WifiP2pManager.WIFI_P2P_THIS_DEVICE_CHANGED_ACTION);
}
WifiP2pManager.PeerListListener peerListListener = new WifiP2pManager.PeerListListener() {
#Override
public void onPeersAvailable(WifiP2pDeviceList peerList) {
if(!peerList.getDeviceList().equals(peers)){
peers.clear();
peers.addAll(peerList.getDeviceList());
deviceNameArray = new String[peerList.getDeviceList().size()];
deviceArray = new WifiP2pDevice[peerList.getDeviceList().size()];
int index = 0;
for(WifiP2pDevice device : peerList.getDeviceList()){
deviceNameArray[index] = device.deviceAddress;
deviceArray[index] = device;
index++;
}
ArrayAdapter<String> adapter = new ArrayAdapter<String>(getApplicationContext(),android.R.layout.simple_list_item_1,deviceNameArray);
listView.setAdapter(adapter);
}
if(peers.size()==0){
Toast.makeText(getApplicationContext(), "No Devices Found",Toast.LENGTH_SHORT).show();
}
}
};
WifiP2pManager.ConnectionInfoListener connectionInfoListener = new WifiP2pManager.ConnectionInfoListener() {
#Override
public void onConnectionInfoAvailable(WifiP2pInfo wifiP2pInfo) {
final InetAddress groupOwnerAddress = wifiP2pInfo.groupOwnerAddress;
if(wifiP2pInfo.groupFormed && wifiP2pInfo.isGroupOwner){
connectionStatus.setText("Host");
serverClass=new ServerClass();
serverClass.start();
}else if(wifiP2pInfo.groupFormed){
connectionStatus.setText("Client");
clientClass = new ClientClass(groupOwnerAddress);
clientClass.start();
}
}
};
#Override
protected void onResume() {
super.onResume();
registerReceiver(mReceiver,mIntentFilter);
}
#Override
protected void onPause() {
super.onPause();
registerReceiver(mReceiver,mIntentFilter);
}
#Override
protected void onDestroy() {
super.onDestroy();
try {
clientClass.socket.close();
serverClass.serverSocket.close();
serverClass.socket.close();
} catch (IOException e) {
e.printStackTrace();
}
}
#Override
protected void finalize() throws Throwable {
super.finalize();
try {
clientClass.socket.close();
serverClass.serverSocket.close();
serverClass.socket.close();
} catch (IOException e) {
e.printStackTrace();
}
}
public class ServerClass extends Thread{
Socket socket;
ServerSocket serverSocket;
#Override
public void run() {
// serverSocket= null;
// socket = null;
try {
Log.i("ServerSocket is called", "Called");
serverSocket = new ServerSocket(8888);
socket = serverSocket.accept();
sendReceive = new SendReceive(socket);
sendReceive.start();
} catch (IOException e) {
e.printStackTrace();
}
}
}
private class SendReceive extends Thread{
private Socket socket;
private InputStream inputStream;
private OutputStream outputStream;
public SendReceive(Socket skt){
socket = skt;
try {
inputStream = socket.getInputStream();
outputStream = socket.getOutputStream();
} catch (IOException e) {
e.printStackTrace();
}
}
#Override
public void run() {
byte[] buffer = new byte[1024];
int bytes;
while(socket!=null){
try {
bytes = inputStream.read(buffer);
if(bytes > 0){
handler.obtainMessage(MESSAGE_READ,bytes,-1,buffer).sendToTarget();
}
} catch (IOException e) {
e.printStackTrace();
}
}
}
public void write (byte[] bytes){
try {
outputStream.write(bytes);
} catch (IOException e) {
e.printStackTrace();
}
}
}
public class ClientClass extends Thread{
Socket socket;
String hostAdd;
public ClientClass(InetAddress hostAddress){
hostAdd = hostAddress.getHostAddress();
// socket = null;
socket = new Socket();
}
#Override
public void run() {
try {
socket.connect(new InetSocketAddress(hostAdd,8888),500);
sendReceive = new SendReceive(socket);
sendReceive.start();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
Here my BroadcastReceiver Class:
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.net.NetworkInfo;
import android.net.wifi.WifiManager;
import android.net.wifi.p2p.WifiP2pManager;
import android.nfc.Tag;
import android.util.Log;
import android.widget.Toast;
import static android.content.ContentValues.TAG;
public class WiFiDirectBroadcastReceiver extends BroadcastReceiver {
private WifiP2pManager mManager;
private WifiP2pManager.Channel mChannel;
private MainActivity mActivity;
public WiFiDirectBroadcastReceiver(WifiP2pManager mManager, WifiP2pManager.Channel mChannel, MainActivity mActivity)
{
this.mManager = mManager;
this.mChannel = mChannel;
this.mActivity = mActivity;
}
#Override
public void onReceive(Context context, Intent intent) {
String action = intent.getAction();
if(WifiP2pManager.WIFI_P2P_STATE_CHANGED_ACTION.equals(action)){
int state = intent.getIntExtra(WifiP2pManager.EXTRA_WIFI_STATE,-1);
if(state==WifiP2pManager.WIFI_P2P_STATE_ENABLED){
Toast.makeText(context,"Wifi is ON",Toast.LENGTH_SHORT).show();
}else {
Toast.makeText(context,"Wifi is OFF",Toast.LENGTH_SHORT).show();
}
}else if(WifiP2pManager.WIFI_P2P_PEERS_CHANGED_ACTION.equals(action)){
if(mManager!=null){
mManager.requestPeers(mChannel,mActivity.peerListListener);
}
Log.d(TAG, "onReceive: P2P peers changed");
}else if(WifiP2pManager.WIFI_P2P_CONNECTION_CHANGED_ACTION.equals(action)){
if(mManager==null){
return;
}
NetworkInfo networkInfo = intent.getParcelableExtra(WifiP2pManager.EXTRA_NETWORK_INFO);
if(networkInfo.isConnected()){
mManager.requestConnectionInfo(mChannel,mActivity.connectionInfoListener);
}else{
mActivity.connectionStatus.setText("Device Disconnected");
}
}else if(WifiP2pManager.WIFI_P2P_THIS_DEVICE_CHANGED_ACTION.equals(action)){
//do something
}
}
}

Android Studio - Issue connecting with device resulting in the socket getting closed

I am attempting to create an android app that connects to an Bluetooth device and am struggling with connecting.When running the run() method when I try to connect it does not work and goes to the catch portion of the code giving me the output of "socket closed". i am not sure why the try is not working.
I am aware that my code has several flaws, i am on my 5th day of android developing, however any help I could get would be greatly appreciated. The big problem I need to fix is being able to connect to the device and ultimately being able to receive a stream of data from it.
public class BluetoothConnection extends Thread {
private final BluetoothSocket mmSocket;
private final InputStream mmInStream;
private final OutputStream mmOutStream;
byte[] buffer;
BluetoothAdapter mmAdapter;
// Unique UUID for this application, you may use different
private static final UUID MY_UUID = UUID
.fromString("eb58f747-a241-4ccb-935d-04ac6039895d");
public BluetoothConnection(BluetoothDevice device) {
BluetoothSocket tmp = null;
mmAdapter = null;
System.out.println("\n\n\n\n\n\n print is working? \n\n\n\n\n\n");
// Get a BluetoothSocket for a connection with the given BluetoothDevice
try {
tmp = device.createRfcommSocketToServiceRecord(MY_UUID);
} catch (IOException e) {
e.printStackTrace();
}
mmSocket = tmp;
//now make the socket connection in separate thread to avoid FC
Thread connectionThread = new Thread(new Runnable() {
#Override
public void run() {
// Always cancel discovery because it will slow down a connection
Log.d("workkkkkk","$$$$$$$$$$$$$$$$****** printingggggg ******$$$$$$$$$$$$$$$$");
//mmAdapter.cancelDiscovery();
}
});
connectionThread.start();
InputStream tmpIn = null;
OutputStream tmpOut = null;
// Get the BluetoothSocket input and output streams
try {
try {
// This is a blocking call and will only return on a
// successful connection or an exception
mmSocket.connect();
System.out.println("\n\n\n\n\n\n socket connected\n\n\n\n\n\n");
} catch (IOException e) {
//connection to device failed so close the socket
try {
mmSocket.close();
System.out.println("\n\n\n\n\n\n socket closed\n\n\n\n\n\n");
} catch (IOException e2) {
System.out.println("\n\n\n\n\n\n in catch\n\n\n\n\n\n");
e2.printStackTrace();
}
}
tmpIn = mmSocket.getInputStream();
tmpOut = mmSocket.getOutputStream();
buffer = new byte[1024];
} catch (IOException e) {
e.printStackTrace();
}
mmInStream = tmpIn;
mmOutStream = tmpOut;
}
public void run() {
// Keep listening to the InputStream while connected
while (true) {
try {
//read the data from socket stream
if(mmInStream != null) {
mmInStream.read(buffer);
}
// Send the obtained bytes to the UI Activity
} catch (IOException e) {
//an exception here marks connection loss
//send message to UI Activity
break;
}
}
}
public void write(byte[] buffer) {
try {
//write the data to socket stream
if(mmOutStream != null)
mmOutStream.write(buffer);
} catch (IOException e) {
e.printStackTrace();
}
}
public void cancel() {
try {
mmSocket.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
This is being run in my DeviceList Class which is here. I am running into multiple problems here but the big one is pertaining to the BluetoothConnection.java however i am not sure if the issue is happening because of this class.
package com.example.curie.fairbanks_01;
import android.bluetooth.BluetoothAdapter;
import android.bluetooth.BluetoothDevice;
import android.bluetooth.BluetoothManager;
import android.bluetooth.BluetoothSocket;
import android.app.Activity;
import android.os.Bundle;
import java.io.IOException;
import android.util.Log;
import android.view.View;
import android.view.MenuItem;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.ListView;
import android.widget.PopupMenu;
import android.widget.Switch;
import android.widget.Toast;
import android.content.Intent;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.ArrayList;
import java.util.Set;
import java.util.UUID;
public class DeviceList extends Activity {
Button deviceSearch;
Switch btSwitch;
private BluetoothAdapter BA;
private Set<BluetoothDevice>pairedDevices;
private String instrumentName;
private UUID instrumentUUID;
BluetoothSocket socket;
BluetoothConnection connector;
ListView lv;
public static BluetoothDevice instrument;
PopupMenu pMenu;
ArrayList<MenuItem> popupList;
ArrayList<BluetoothDevice> list;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_device_list);
deviceSearch = (Button) findViewById(R.id.device_search);
deviceSearch.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
PopupMenu popup = new PopupMenu(DeviceList.this, findViewById(R.id.device_search));
pairedDevices = BA.getBondedDevices();
list = new ArrayList<BluetoothDevice>();
for (BluetoothDevice bt : pairedDevices) {
list.add(bt);
popup.getMenu().add(bt.getName());
popup.show();
}
popup.setOnMenuItemClickListener(new PopupMenu.OnMenuItemClickListener() {
public boolean onMenuItemClick(MenuItem item) {
ArrayList<BluetoothDevice> deviceArrayList = new ArrayList<BluetoothDevice>(pairedDevices);
Toast.makeText(DeviceList.this, "Testing: " + item.getTitle(), Toast.LENGTH_SHORT).show();
// instrument = deviceArrayList.get(deviceArrayList.indexOf(item.getItemId()));
instrument = deviceArrayList.get(0);
connector = new BluetoothConnection(instrument);
connector.run();
Toast.makeText(DeviceList.this, "Connected to : " + item.getTitle(), Toast.LENGTH_SHORT).show();
Intent myIntent = new Intent(DeviceList.this, InputActivity.class);
DeviceList.this.startActivity(myIntent);
return true;
}
});
}
});
btSwitch = (Switch) findViewById(R.id.switch1);
BA =BluetoothAdapter.getDefaultAdapter();
lv =(ListView) findViewById(R.id.listView);
if(BA.isEnabled())
btSwitch.setChecked(true);
else
btSwitch.setChecked(false);
// pMenu = new PopupMenu(this,findViewById(R.id.device_search));
}
public void list(View v){
// pairedDevices = BA.getBondedDevices();
//
// ArrayList list = new ArrayList();
//
// for(BluetoothDevice bt : pairedDevices){
//
// list.add(bt.getName());
// pMenu.getMenu().add(bt.toString());
// }
Toast.makeText(getApplicationContext(), "Showing Paired Devices",Toast.LENGTH_SHORT).show();
final ArrayAdapter adapter = new ArrayAdapter(this,android.R.layout.simple_list_item_1, list);
lv.setAdapter(adapter);
}
public void onOff(View v)
{
if(BA.isEnabled())
{
BA.disable();
Toast.makeText(getApplicationContext(), " BT Turned off" ,Toast.LENGTH_LONG).show();
}
else
{ BA.enable();
Toast.makeText(getApplicationContext(), "BT Turned on" ,Toast.LENGTH_LONG).show();
}
}
public static BluetoothDevice getInstrument() {
return instrument;
}
}
this is what is running on the console when I select the device I would like to connect to:
I/System.out: $$$$$$$$$$$$$$$$****** in constructor ******$$$$$$$$$$$$$$$$
D/workkkkkk: $$$$$$$$$$$$$$$$****** printingggggg ******$$$$$$$$$$$$$$$$
D/BluetoothUtils: isSocketAllowedBySecurityPolicy start : device null
D/BluetoothSocket: connect(): myUserId = 0
W/BluetoothAdapter: getBluetoothService() called with no BluetoothManagerCallback
I/System.out: $$$$$$$$$$$$$$$$****** socket closed ******$$$$$$$$$$$$$$$$
D/BluetoothSocket: getInputStream(): myUserId = 0
getOutputStream(): myUserId = 0
Why is it not connecting in the try?

TextView not updated, and AlertDialog does not show up when called inside thread, even using RunOnUiThread

First of all, I should say that I am a newbie on Java and Android programming. I am very experienced in C programming for embedded systems, but now I need to communicate one of my embedded projects with an Android app, in a very simple way. I am using one of those ESP8266, configured as default. Thus, it behaves as a basic telnet server. My microcontroller has to send a question (through a string, which is not constant) to my app, and receive a "Y" or "N" reply. I have tested it using a telnet client, and it is working fine. However, I want to have an app that pops up an alert dialog and/or show the message in a TextView element, and sends the reply after some button click. For this, I have adapted a telnet client code from:
http://android-er.blogspot.com.br/2014/08/simple-android-chat-application-client.html
I have put everything in one single panel, and reduced the number of elements to a textview element and 4 buttons (connect, disconnect, yes, and no). I am using a fixed IP and port to connect the app to my laptop, which is running a telnet server (hercules). The connection is confirmed, and the YES and NO buttons are sending the correct messages. However, the question string never shows up at the TextView element. I have also added an AlertDialog to pop up, because I think it is more appropriate to the kind of app I am developing.
Notice that the testing of the message income happens inside a thread, and I am calling the TextView update and the AlertDialog show using runOnUiThread.
Here is the Java code (not optimized yet):
package br.unicamp.smpci;
import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.IOException;
import java.net.Socket;
import java.net.UnknownHostException;
import android.app.AlertDialog;
import android.app.Dialog;
import android.content.Context;
import android.content.DialogInterface;
import android.support.v4.app.DialogFragment;
import android.support.v7.app.ActionBarActivity;
import android.os.Bundle;
import android.support.v7.app.NotificationCompat;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;
public class MainActivity extends ActionBarActivity {
static final int SocketServerPORT = 80;
final Context context = this;
LinearLayout Panel;
Button buttonConnect;
TextView chatMsg;
Button buttonSendYes;
Button buttonSendNo;
Button buttonDisconnect;
String msgLog = "";
ChatClientThread chatClientThread = null;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Panel = (LinearLayout)findViewById(R.id.panel);
buttonConnect = (Button) findViewById(R.id.connect);
buttonDisconnect = (Button) findViewById(R.id.disconnect);
chatMsg = (TextView) findViewById(R.id.chatmsg);
buttonConnect.setOnClickListener(buttonConnectOnClickListener);
buttonDisconnect.setOnClickListener(buttonDisconnectOnClickListener);
buttonSendYes = (Button)findViewById(R.id.sendYes);
buttonSendYes.setOnClickListener(buttonSendYesOnClickListener);
buttonSendNo = (Button)findViewById(R.id.sendNo);
buttonSendNo.setOnClickListener(buttonSendNoOnClickListener);
}
OnClickListener buttonDisconnectOnClickListener = new OnClickListener() {
#Override
public void onClick(View v) {
if(chatClientThread==null){
return;
}
chatClientThread.disconnect();
}
};
OnClickListener buttonSendYesOnClickListener = new OnClickListener() {
#Override
public void onClick(View v) {
if(chatClientThread==null){
return;
}
chatClientThread.sendMsg("Y" + "\n");
}
};
OnClickListener buttonSendNoOnClickListener = new OnClickListener() {
#Override
public void onClick(View v) {
if(chatClientThread==null){
return;
}
chatClientThread.sendMsg("N" + "\n");
}
};
OnClickListener buttonConnectOnClickListener = new OnClickListener() {
#Override
public void onClick(View v) {
String textAddress = "192.168.1.11";
msgLog = "NO MESSAGES";
chatMsg.setText(msgLog);
chatClientThread = new ChatClientThread(
textAddress, SocketServerPORT);
chatClientThread.start();
}
};
private class ChatClientThread extends Thread {
String dstAddress;
int dstPort;
String msgToSend = "";
boolean goOut = false;
ChatClientThread(String address, int port) {
dstAddress = address;
dstPort = port;
}
#Override
public void run() {
Socket socket = null;
DataOutputStream dataOutputStream = null;
DataInputStream dataInputStream = null;
try {
socket = new Socket(dstAddress, dstPort);
dataOutputStream = new DataOutputStream(
socket.getOutputStream());
dataInputStream = new DataInputStream(socket.getInputStream());
while (!goOut) {
if (dataInputStream.available() > 0) {
msgLog = dataInputStream.readUTF();
MainActivity.this.runOnUiThread(new Runnable() {
#Override
public void run() {
chatMsg.setText(msgLog);
chatMsg.invalidate();
AlertDialog.Builder alertDialogBuilder = new AlertDialog.Builder(
context);
alertDialogBuilder.setTitle("ALERT");
alertDialogBuilder
.setMessage(MsgLog)
.setCancelable(false)
.setPositiveButton("Yes",new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog,int id) {
if(chatClientThread==null){
return;
}
chatClientThread.sendMsg("Y" + "\n");
}
})
.setNegativeButton("No", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
if (chatClientThread == null) {
return;
}
chatClientThread.sendMsg("N" + "\n");
}
});
AlertDialog alertDialog = alertDialogBuilder.create();
alertDialog.show();
}
});
}
if(!msgToSend.equals("")){
dataOutputStream.writeUTF(msgToSend);
dataOutputStream.flush();
msgToSend = "";
}
}
} catch (UnknownHostException e) {
e.printStackTrace();
final String eString = e.toString();
MainActivity.this.runOnUiThread(new Runnable() {
#Override
public void run() {
Toast.makeText(MainActivity.this, eString, Toast.LENGTH_LONG).show();
}
});
} catch (IOException e) {
e.printStackTrace();
final String eString = e.toString();
MainActivity.this.runOnUiThread(new Runnable() {
#Override
public void run() {
Toast.makeText(MainActivity.this, eString, Toast.LENGTH_LONG).show();
}
});
} finally {
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) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
MainActivity.this.runOnUiThread(new Runnable() {
#Override
public void run() {
//loginPanel.setVisibility(View.VISIBLE);
//chatPanel.setVisibility(View.GONE);
}
});
}
}
private void sendMsg(String msg){
msgToSend = msg;
}
private void disconnect(){
goOut = true;
}
}
}
I have done extensive research on how to make sure that the UI thread updates my elements, and I am using the Show() method for the alertdialog, and invalidating the TextView element to force it to update. I have used debug, and I am sure that the instructions are being executed, but with no result on my app ( I am using a real device for debugging).
I have seen that maybe I could use AsyncTask for this purpose, but as a newbie I am facing difficulties to make the changes, and I believe that calling the updates with a runOnUiThread should do the work.
Can anyone explain why I cannot see my message, and maybe provide me a code correction?
Thanks in advance,
Antonio Quevedo

What can I do by getBluetoothService() called with no BluetoothManagerCallback ?

hi I want to write a Android java application that can connect with a bluetooth device but I get the error:
W/BluetoothAdapter﹕ getBluetoothService() called with no BluetoothManagerCallback
I use a Nexus 5 device with android version 4.4.4
here is my code:
package com.example.tarasov.bluetoothexample;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.ArrayList;
import java.util.Set;
import java.util.UUID;
import android.view.Menu;
import android.view.MenuItem;
import android.app.Activity;
import android.bluetooth.BluetoothAdapter;
import android.bluetooth.BluetoothDevice;
import android.bluetooth.BluetoothSocket;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.view.View;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ArrayAdapter;
import android.widget.ListView;
import android.widget.Toast;
public class MyActivity extends Activity implements OnItemClickListener {
/*
* Deklaration
* */
ArrayAdapter<String> listAdapter;
ListView listView;
BluetoothAdapter btAdapter;
Set<BluetoothDevice> deviceArray;
ArrayList<String> pairedDevices;
ArrayList<BluetoothDevice> devices;
public static final UUID MY_UUID = UUID.fromString("00001101-0000-1000-8000-00805F9B34FB");
protected static final int SUCCESS_CONNECT = 0;
protected static final int MESSAGE_READ = 1;
IntentFilter filter;
BroadcastReceiver receiver;
String tag = "debugging";
Handler mHandler = new Handler(){
#Override
public void handleMessage(Message msg) {
// TODO Auto-generated method stub
Log.i(tag, "in handler");
super.handleMessage(msg);
switch(msg.what){
case SUCCESS_CONNECT:
// DO something
ConnectedThread connectedThread = new ConnectedThread((BluetoothSocket)msg.obj);
Toast.makeText(getApplicationContext(), "CONNECT", Toast.LENGTH_SHORT).show();
String s = "successfully connected";
connectedThread.write(s.getBytes());
Log.i(tag, "connected");
break;
case MESSAGE_READ:
byte[] readBuf = (byte[])msg.obj;
String string = new String(readBuf);
Toast.makeText(getApplicationContext(), string, Toast.LENGTH_SHORT).show();
break;
}
}
};
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_my);
init(); //Initialisierung der Komponenten
if(btAdapter==null)
{
Toast.makeText(getApplicationContext(), "Kein Bluetooth aktiviert", Toast.LENGTH_SHORT).show();
finish();
}
else
{
if (!btAdapter.isEnabled()){
turnOnBT();
}
getPairedDevices();
startDiscovery();
}
}
private void startDiscovery() {
btAdapter.cancelDiscovery();
btAdapter.startDiscovery();
}
private void turnOnBT() {
Intent intent = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);
startActivityForResult(intent,1);
}
private void getPairedDevices() {
deviceArray = btAdapter.getBondedDevices();
if (deviceArray.size()>0){
for (BluetoothDevice device:deviceArray){
pairedDevices.add(device.getName());
}
}
}
private void init(){
listView = (ListView)findViewById(R.id.listView); //bindet ListView
listView.setOnItemClickListener(this);
listAdapter = new ArrayAdapter<String>(this,android.R.layout.simple_list_item_1,0);
listView.setAdapter(listAdapter);
btAdapter = BluetoothAdapter.getDefaultAdapter();
pairedDevices = new ArrayList<String>();
filter = new IntentFilter(BluetoothDevice.ACTION_FOUND);
devices = new ArrayList<BluetoothDevice>();
receiver = 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);
devices.add(device);
String s = "";
for (int a=0;a< pairedDevices.size();a++){
if (device.getName().equals(pairedDevices.get(a))){
s = "(Verbunden)";
break;
}
}
listAdapter.add(device.getName()+" "+s+" "+"\n"+device.getAddress());
}
else if (BluetoothAdapter.ACTION_DISCOVERY_STARTED.equals(action)){
}
else if (BluetoothAdapter.ACTION_DISCOVERY_FINISHED.equals(action)){
}
else if (BluetoothAdapter.ACTION_STATE_CHANGED.equals(action)){
if (btAdapter.getState()==btAdapter.STATE_OFF){
turnOnBT();
}
}
}
};
registerReceiver(receiver,filter);
filter = new IntentFilter(BluetoothAdapter.ACTION_DISCOVERY_STARTED);
registerReceiver(receiver,filter);
filter = new IntentFilter(BluetoothAdapter.ACTION_DISCOVERY_FINISHED);
registerReceiver(receiver,filter);
filter = new IntentFilter(BluetoothAdapter.ACTION_STATE_CHANGED);
registerReceiver(receiver,filter);
}
#Override
protected void onPause() {
super.onPause();
unregisterReceiver(receiver);
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (resultCode==RESULT_CANCELED){
Toast.makeText(getApplicationContext(), "Bluetooth muss erst aktiviert werden", Toast.LENGTH_SHORT).show();
finish();
}
}
#Override
public void onItemClick(AdapterView<?> arg0, View arg1, int arg2, long arg3) {
if (btAdapter.isDiscovering()){
btAdapter.cancelDiscovery();
}
if (listAdapter.getItem(arg2).contains("Verbunden")){
BluetoothDevice selectedDevice = devices.get(arg2);
ConnectThread connect = new ConnectThread(selectedDevice);
connect.start();
Log.i(tag, "in click listener");
}
else
{
Toast.makeText(getApplicationContext(), "Gerät ist nicht verbunden", Toast.LENGTH_SHORT).show();
}
}
/*
* Hilfsklassen
* */
private 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;
Log.i(tag, "construct");
// 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) {
Log.i(tag, "get socket failed");
}
mmSocket = tmp;
}
public void run() {
// Cancel discovery because it will slow down the connection
btAdapter.cancelDiscovery();
Log.i(tag, "connect - run");
try {
// Connect the device through the socket. This will block
// until it succeeds or throws an exception
mmSocket.connect();
Log.i(tag, "connect - succeeded");
} catch (IOException connectException) { Log.i(tag, "connect failed");
// Unable to connect; close the socket and get out
try {
mmSocket.close();
} catch (IOException closeException) { }
return;
}
// Do work to manage the connection (in a separate thread)
mHandler.obtainMessage(SUCCESS_CONNECT, mmSocket).sendToTarget();
}
/** 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;
// Get the input and output streams, using temp objects because
// member streams are final
try {
tmpIn = socket.getInputStream();
tmpOut = socket.getOutputStream();
} catch (IOException e) { }
mmInStream = tmpIn;
mmOutStream = tmpOut;
}
public void run() {
byte[] buffer; // buffer store for the stream
int bytes; // bytes returned from read()
// Keep listening to the InputStream until an exception occurs
while (true) {
try {
// Read from the InputStream
buffer = new byte[1024];
bytes = mmInStream.read(buffer);
// Send the obtained bytes to the UI activity
mHandler.obtainMessage(MESSAGE_READ, bytes, -1, buffer)
.sendToTarget();
} catch (IOException e) {
break;
}
}
}
/* 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) { }
}
}

Categories

Resources