无法通过蓝牙设备地址在 android 中创建套接字
Not able to pass Bluetooth Device address to create a socket in android
我正在开发一个 android 应用程序,我需要在其中通过蓝牙发送文本。我想出了一段代码来实现这一点。我的问题是我无法传递另一个设备的地址来创建套接字。该应用程序每次到达该点时都会崩溃:
BluetoothDevice 设备 = bluetooth.getRemoteDevice(地址);其中 address 是我要连接的设备的 mac 地址。我的完整代码是:
package com.example.blueremote;
public class MainActivity extends Activity {
private BluetoothAdapter bluetooth;
private BluetoothSocket socket;
private Button btnSend;
private ArrayList<BluetoothDevice> foundDevices;
private ArrayAdapter<BluetoothDevice> aa;
private Handler handler = new Handler();
private ListView list;
private TextView tvmsg;
private static int DISCOVERY_REQUEST = 1;
private UUID uuid = UUID.fromString("a60f35f0-b93a-11de-8a39-08002009c666");
ImageButton up;
private String address = "D8:50:E6:8A:16:0F";
private String text = "up";
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Intent disc;
disc = new Intent(BluetoothAdapter.ACTION_REQUEST_DISCOVERABLE);
startActivityForResult(disc, DISCOVERY_REQUEST);
up = (ImageButton) findViewById(R.id.btn_up);
registerReceiver(discoveryResult, new IntentFilter(
BluetoothDevice.ACTION_FOUND));
up.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
// TODO Auto-generated method stub
Log.v("Main Activity", "In up Button");
// Log.v("Main Activity", "Invoking switchUI");
AsyncTask<Integer, Void, Void> connectTask = new AsyncTask<Integer, Void, Void>() {
@Override
protected Void doInBackground(Integer... params) {
// TODO Auto-generated method stub
try {
Log.v("Main Activity", " AsyncTask started");
BluetoothDevice device = bluetooth
.getRemoteDevice(address);
socket = device
.createRfcommSocketToServiceRecord(uuid);
Log.v("Main Activity", "Socket Created");
socket.connect();
Log.v("Main Activity", "Socket Connected");
} catch (IOException e) {
Log.d("BLUETOOTH_CLIENT", e.getMessage());
}
return null;
}
@Override
protected void onPostExecute(Void result) {
// Log.v("Main Activity", "Invoking switchUI");
switchUI();
}
};
connectTask.execute();
}
});
}
private void switchUI() {
Log.v("Main Activity", "In SwitchUI Method");
Log.v("Main Activity", "Invoking sendMessage Method ");
sendMessage(socket, text);
Log.v("Main Activity", "Message Sent");
BluetoothSocketListener bsl = new BluetoothSocketListener(socket,
handler);
Thread messageListener = new Thread(bsl);
messageListener.start();
}
private void sendMessage(BluetoothSocket socket, String msg) {
msg = "hi";
OutputStream outStream;
try {
Log.v("Main Activity", "Inside sendMessage Method ");
outStream = socket.getOutputStream();
Log.v("Main Activity", "Outstream:" + outStream);
byte[] byteString = (msg + " ").getBytes();
Log.v("Main Activity", "byteString:" + byteString);
outStream.write(byteString);
Log.v("Main Activity", "outstream written:");
} catch (IOException e) {
Log.d("BLUETOOTH_COMMS", e.getMessage());
}
}
private class MessagePoster implements Runnable {
private TextView textView;
private String message;
public MessagePoster(TextView textView, String message) {
this.textView = textView;
this.message = message;
}
public void run() {
textView.setText(message);
}
}
private class BluetoothSocketListener implements Runnable {
private BluetoothSocket socket;
private TextView textView;
private Handler handler;
public BluetoothSocketListener(BluetoothSocket socket, Handler handler) {
this.socket = socket;
// this.textView = textView;
this.handler = handler;
}
public void run() {
int bufferSize = 2048;
byte[] buffer = new byte[bufferSize];
try {
InputStream instream = socket.getInputStream();
int bytesRead = -1;
String message = "";
while (true) {
message = "hello";
bytesRead = instream.read(buffer);
if (bytesRead != -1) {
while ((bytesRead == bufferSize)
&& (buffer[bufferSize - 1] != 0)) {
message = message
+ new String(buffer, 0, bytesRead);
bytesRead = instream.read(buffer);
}
message = message
+ new String(buffer, 0, bytesRead - 1);
handler.post(new MessagePoster(textView, message));
socket.getInputStream();
}
}
} catch (IOException e) {
Log.d("BLUETOOTH_COMMS", e.getMessage());
}
}
}
/*
* protected void onActivityResult(int requestCode, int resultCode, Intent
* data) { if (requestCode == DISCOVERY_REQUEST) { boolean isDiscoverable =
* resultCode > 0; if (isDiscoverable) { String name = "bluetoothserver";
* try { final BluetoothServerSocket btserver = bluetooth
* .listenUsingRfcommWithServiceRecord(name, uuid); AsyncTask<Integer, Void,
* BluetoothSocket> acceptThread = new AsyncTask<Integer, Void,
* BluetoothSocket>() {
*
* @Override protected void onPostExecute(BluetoothSocket result) { if
* (result != null) switchUI(); }
*
* @Override protected BluetoothSocket doInBackground( Integer... params) {
* // TODO Auto-generated method stub try { socket =
* btserver.accept(params[0] * 1000); return socket; } catch (IOException e)
* { Log.d("BLUETOOTH", e.getMessage()); } return null; } };
* acceptThread.execute(resultCode); } catch (IOException e) {
* Log.d("BLUETOOTH", e.getMessage()); } } } }
*/
BroadcastReceiver discoveryResult = new BroadcastReceiver() {
@Override
public void onReceive(Context context, Intent intent) {
// TODO Auto-generated method stub
BluetoothDevice remoteDevice;
remoteDevice = intent
.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE);
if (bluetooth.getBondedDevices().contains(remoteDevice)) {
foundDevices.add(remoteDevice);
aa.notifyDataSetChanged();
}
}
};
protected void onDestroy() {
super.onDestroy();
unregisterReceiver(discoveryResult);
}
}
这是我的logcat要说的:
E/AndroidRuntime( 5421): FATAL EXCEPTION: AsyncTask #1
E/AndroidRuntime( 5421): java.lang.RuntimeException: An error occured while executing doInBackground()
E/AndroidRuntime( 5421): at android.os.AsyncTask.done(AsyncTask.java:299)
E/AndroidRuntime( 5421): at java.util.concurrent.FutureTask.finishCompletion(FutureTask.java:352)
E/AndroidRuntime( 5421): at java.util.concurrent.FutureTask.setException(FutureTask.java:219)
E/AndroidRuntime( 5421): at java.util.concurrent.FutureTask.run(FutureTask.java:239)
E/AndroidRuntime( 5421): at android.os.AsyncTask$SerialExecutor.run(AsyncTask.java:230)
E/AndroidRuntime( 5421): at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1080)
E/AndroidRuntime( 5421): at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:573)
E/AndroidRuntime( 5421): at java.lang.Thread.run(Thread.java:838)
E/AndroidRuntime( 5421): Caused by: java.lang.NullPointerException
E/AndroidRuntime( 5421): at com.example.blueremote.MainActivity.doInBackground(MainActivity.java:75)
E/AndroidRuntime( 5421): at com.example.blueremote.MainActivity.doInBackground(MainActivity.java:1)
E/AndroidRuntime( 5421): at android.os.AsyncTask.call(AsyncTask.java:287)
E/AndroidRuntime( 5421): at java.util.concurrent.FutureTask.run(FutureTask.java:234)
如果知道如何创建套接字,我们将不胜感激。
提前致谢
原因:java.lang.NullPointerException
at com.example.blueremote.MainActivity.doInBackground(MainActivity.java:75)
表示行
BluetoothDevice device = bluetooth.getRemoteDevice(address);
问题
bluetooth
未初始化。
我正在开发一个 android 应用程序,我需要在其中通过蓝牙发送文本。我想出了一段代码来实现这一点。我的问题是我无法传递另一个设备的地址来创建套接字。该应用程序每次到达该点时都会崩溃: BluetoothDevice 设备 = bluetooth.getRemoteDevice(地址);其中 address 是我要连接的设备的 mac 地址。我的完整代码是:
package com.example.blueremote;
public class MainActivity extends Activity {
private BluetoothAdapter bluetooth;
private BluetoothSocket socket;
private Button btnSend;
private ArrayList<BluetoothDevice> foundDevices;
private ArrayAdapter<BluetoothDevice> aa;
private Handler handler = new Handler();
private ListView list;
private TextView tvmsg;
private static int DISCOVERY_REQUEST = 1;
private UUID uuid = UUID.fromString("a60f35f0-b93a-11de-8a39-08002009c666");
ImageButton up;
private String address = "D8:50:E6:8A:16:0F";
private String text = "up";
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Intent disc;
disc = new Intent(BluetoothAdapter.ACTION_REQUEST_DISCOVERABLE);
startActivityForResult(disc, DISCOVERY_REQUEST);
up = (ImageButton) findViewById(R.id.btn_up);
registerReceiver(discoveryResult, new IntentFilter(
BluetoothDevice.ACTION_FOUND));
up.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
// TODO Auto-generated method stub
Log.v("Main Activity", "In up Button");
// Log.v("Main Activity", "Invoking switchUI");
AsyncTask<Integer, Void, Void> connectTask = new AsyncTask<Integer, Void, Void>() {
@Override
protected Void doInBackground(Integer... params) {
// TODO Auto-generated method stub
try {
Log.v("Main Activity", " AsyncTask started");
BluetoothDevice device = bluetooth
.getRemoteDevice(address);
socket = device
.createRfcommSocketToServiceRecord(uuid);
Log.v("Main Activity", "Socket Created");
socket.connect();
Log.v("Main Activity", "Socket Connected");
} catch (IOException e) {
Log.d("BLUETOOTH_CLIENT", e.getMessage());
}
return null;
}
@Override
protected void onPostExecute(Void result) {
// Log.v("Main Activity", "Invoking switchUI");
switchUI();
}
};
connectTask.execute();
}
});
}
private void switchUI() {
Log.v("Main Activity", "In SwitchUI Method");
Log.v("Main Activity", "Invoking sendMessage Method ");
sendMessage(socket, text);
Log.v("Main Activity", "Message Sent");
BluetoothSocketListener bsl = new BluetoothSocketListener(socket,
handler);
Thread messageListener = new Thread(bsl);
messageListener.start();
}
private void sendMessage(BluetoothSocket socket, String msg) {
msg = "hi";
OutputStream outStream;
try {
Log.v("Main Activity", "Inside sendMessage Method ");
outStream = socket.getOutputStream();
Log.v("Main Activity", "Outstream:" + outStream);
byte[] byteString = (msg + " ").getBytes();
Log.v("Main Activity", "byteString:" + byteString);
outStream.write(byteString);
Log.v("Main Activity", "outstream written:");
} catch (IOException e) {
Log.d("BLUETOOTH_COMMS", e.getMessage());
}
}
private class MessagePoster implements Runnable {
private TextView textView;
private String message;
public MessagePoster(TextView textView, String message) {
this.textView = textView;
this.message = message;
}
public void run() {
textView.setText(message);
}
}
private class BluetoothSocketListener implements Runnable {
private BluetoothSocket socket;
private TextView textView;
private Handler handler;
public BluetoothSocketListener(BluetoothSocket socket, Handler handler) {
this.socket = socket;
// this.textView = textView;
this.handler = handler;
}
public void run() {
int bufferSize = 2048;
byte[] buffer = new byte[bufferSize];
try {
InputStream instream = socket.getInputStream();
int bytesRead = -1;
String message = "";
while (true) {
message = "hello";
bytesRead = instream.read(buffer);
if (bytesRead != -1) {
while ((bytesRead == bufferSize)
&& (buffer[bufferSize - 1] != 0)) {
message = message
+ new String(buffer, 0, bytesRead);
bytesRead = instream.read(buffer);
}
message = message
+ new String(buffer, 0, bytesRead - 1);
handler.post(new MessagePoster(textView, message));
socket.getInputStream();
}
}
} catch (IOException e) {
Log.d("BLUETOOTH_COMMS", e.getMessage());
}
}
}
/*
* protected void onActivityResult(int requestCode, int resultCode, Intent
* data) { if (requestCode == DISCOVERY_REQUEST) { boolean isDiscoverable =
* resultCode > 0; if (isDiscoverable) { String name = "bluetoothserver";
* try { final BluetoothServerSocket btserver = bluetooth
* .listenUsingRfcommWithServiceRecord(name, uuid); AsyncTask<Integer, Void,
* BluetoothSocket> acceptThread = new AsyncTask<Integer, Void,
* BluetoothSocket>() {
*
* @Override protected void onPostExecute(BluetoothSocket result) { if
* (result != null) switchUI(); }
*
* @Override protected BluetoothSocket doInBackground( Integer... params) {
* // TODO Auto-generated method stub try { socket =
* btserver.accept(params[0] * 1000); return socket; } catch (IOException e)
* { Log.d("BLUETOOTH", e.getMessage()); } return null; } };
* acceptThread.execute(resultCode); } catch (IOException e) {
* Log.d("BLUETOOTH", e.getMessage()); } } } }
*/
BroadcastReceiver discoveryResult = new BroadcastReceiver() {
@Override
public void onReceive(Context context, Intent intent) {
// TODO Auto-generated method stub
BluetoothDevice remoteDevice;
remoteDevice = intent
.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE);
if (bluetooth.getBondedDevices().contains(remoteDevice)) {
foundDevices.add(remoteDevice);
aa.notifyDataSetChanged();
}
}
};
protected void onDestroy() {
super.onDestroy();
unregisterReceiver(discoveryResult);
}
}
这是我的logcat要说的:
E/AndroidRuntime( 5421): FATAL EXCEPTION: AsyncTask #1
E/AndroidRuntime( 5421): java.lang.RuntimeException: An error occured while executing doInBackground()
E/AndroidRuntime( 5421): at android.os.AsyncTask.done(AsyncTask.java:299)
E/AndroidRuntime( 5421): at java.util.concurrent.FutureTask.finishCompletion(FutureTask.java:352)
E/AndroidRuntime( 5421): at java.util.concurrent.FutureTask.setException(FutureTask.java:219)
E/AndroidRuntime( 5421): at java.util.concurrent.FutureTask.run(FutureTask.java:239)
E/AndroidRuntime( 5421): at android.os.AsyncTask$SerialExecutor.run(AsyncTask.java:230)
E/AndroidRuntime( 5421): at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1080)
E/AndroidRuntime( 5421): at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:573)
E/AndroidRuntime( 5421): at java.lang.Thread.run(Thread.java:838)
E/AndroidRuntime( 5421): Caused by: java.lang.NullPointerException
E/AndroidRuntime( 5421): at com.example.blueremote.MainActivity.doInBackground(MainActivity.java:75)
E/AndroidRuntime( 5421): at com.example.blueremote.MainActivity.doInBackground(MainActivity.java:1)
E/AndroidRuntime( 5421): at android.os.AsyncTask.call(AsyncTask.java:287)
E/AndroidRuntime( 5421): at java.util.concurrent.FutureTask.run(FutureTask.java:234)
如果知道如何创建套接字,我们将不胜感激。 提前致谢
原因:java.lang.NullPointerException
at com.example.blueremote.MainActivity.doInBackground(MainActivity.java:75)
表示行
BluetoothDevice device = bluetooth.getRemoteDevice(address);
问题
bluetooth
未初始化。