我有那个问题。我尝试使用子类应用程序将蓝牙连接到蓝牙设备,因为我必须在更多活动中连接和传输数据。但是我无法使用该错误来做到这一点:java.lang.NullPointerException:android.bluetooth.BluetoothServerSocket:在空对象引用上。 那是我的代码应用程序
public class Bluetooth extends Application {
private static Bluetooth sInstance;
BluetoothAdapter mBluetoothAdapter;
BluetoothSocket btSocket = null;
BluetoothDevice mmDevice;
BluetoothSocket mmSocket;
UUID deviceUUID;
ProgressDialog mProgressDialog;
private ConnectedThread mConnectedThread;
private AcceptThread mInsecureAcceptThread;
private ConnectThread mConnectThread;
Context mContext;
public static Bluetooth getApplication() {
return sInstance;
}
public void onCreate() {
super.onCreate();
sInstance = this;
}
private static final String TAG = "BluetoothConnectionServ";
private static final String appname = "My Application";
private static final UUID MY_UUID_INSECURE =
UUID.fromString("00001101-0000-1000-8000-00805F9B34FB");
int n = 0;
public BluetoothSocket getCurrentBluetoothConnection()
{
return btSocket;
}
public void setupBluetoothConnection(BluetoothDevice device,UUID uuid){
start1();
mConnectThread = new ConnectThread(device,uuid);
mConnectThread.start();
}
private class ConnectThread extends Thread {
public ConnectThread(BluetoothDevice device, UUID uuid) {
mmDevice = device;
deviceUUID = uuid;
}
public void run(){
BluetoothSocket tmp = null;
Log.i(TAG, "RUN mConnectThread ");
// Get a BluetoothSocket for a connection with the
// given BluetoothDevice
try {
Log.d(TAG, "ConnectThread: Trying to create InsecureRfcommSocket using UUID: "
+MY_UUID_INSECURE );
tmp = mmDevice.createRfcommSocketToServiceRecord(deviceUUID);
} catch (IOException e) {
Log.e(TAG, "ConnectThread: Could not create InsecureRfcommSocket " + e.getMessage());
}
mmSocket = tmp;
// Always cancel discovery because it will slow down a connection
mBluetoothAdapter.cancelDiscovery();
// Make a connection to the BluetoothSocket
try {
// This is a blocking call and will only return on a
// successful connection or an exception
mmSocket.connect();
Log.d(TAG, "run: ConnectThread connected.");
} catch (IOException e) {
// Close the socket
try {
mmSocket.close();
Log.d(TAG, "run: Closed Socket.");
} catch (IOException e1) {
Log.e(TAG, "mConnectThread: run: Unable to close connection in socket " + e1.getMessage());
}
Log.d(TAG, "run: ConnectThread: Could not connect to UUID: " + MY_UUID_INSECURE );
}
//will talk about this in the 3rd video
connected(mmSocket,mmDevice);
}
public void cancel() {
try {
Log.d(TAG, "cancel: Closing Client Socket.");
mmSocket.close();
} catch (IOException e) {
Log.e(TAG, "cancel: close() of mmSocket in Connectthread failed. " + e.getMessage());
}
}
}
public class AcceptThread extends Thread {
// The local server socket
public final BluetoothServerSocket mmServerSocket;
public AcceptThread(){
BluetoothServerSocket tmp = null;
// Create a new listening server socket
try{
tmp = mBluetoothAdapter.listenUsingInsecureRfcommWithServiceRecord(appname,MY_UUID_INSECURE);
Log.d(TAG, "AcceptThread: Setting up Server using: " + MY_UUID_INSECURE);
}catch (IOException e){
Log.e(TAG, "AcceptThread: IOException: " + e.getMessage() );
}
mmServerSocket = tmp;
}
public void run(){
Log.d(TAG, "run: AcceptThread Running.");
BluetoothSocket socket = null;
try{
// This is a blocking call and will only return on a
// successful connection or an exception
Log.d(TAG, "run: RFCOM server socket start.....");
socket = mmServerSocket.accept();
Log.d(TAG, "run: RFCOM server socket accepted connection.");
}catch (IOException e){
Log.e(TAG, "AcceptThread: IOException: " + e.getMessage() );
}
//talk about this is in the 3rd
if(socket != null){
connected(socket,mmDevice);
}
Log.i(TAG, "END mAcceptThread ");
}
public void cancel() {
Log.d(TAG, "cancel: Canceling AcceptThread.");
try {
mmServerSocket.close();
} catch (IOException e) {
Log.e(TAG, "cancel: Close of AcceptThread ServerSocket failed. " + e.getMessage() );
}
}
}
public synchronized void start1() {
Log.d(TAG, "start");
// Cancel any thread attempting to make a connection
if (mConnectThread != null) {
mConnectThread.cancel();
mConnectThread = null;
}
if (mInsecureAcceptThread == null) {
mInsecureAcceptThread = new AcceptThread();
mInsecureAcceptThread.start();
}
}
private class ConnectedThread extends Thread {
private final BluetoothSocket mmSocket;
private final InputStream mmInStream;
private final OutputStream mmOutStream;
public ConnectedThread(BluetoothSocket socket) {
Log.d(TAG, "ConnectedThread: Starting.");
mmSocket = socket;
InputStream tmpIn = null;
OutputStream tmpOut = null;
//dismiss the progressdialog when connection is established
try{
mProgressDialog.dismiss();
}catch (NullPointerException e){
e.printStackTrace();
}
try {
tmpIn = mmSocket.getInputStream();
tmpOut = mmSocket.getOutputStream();
} catch (IOException e) {
e.printStackTrace();
}
// bat dau activity ;
mmInStream = tmpIn;
mmOutStream = tmpOut;
n = 1;
}
public void run(){
byte[] buffer = new byte[1024]; // buffer store for the stream
int bytes; // bytes returned from read()
// Keep listening to the InputStream until an exception occurs
while (true) {
// Read from the InputStream
try {
bytes = mmInStream.read(buffer);
String incomingMessage = new String(buffer, 0, bytes);
Log.d(TAG, "InputStream: " + incomingMessage);
} catch (IOException e) {
Log.e(TAG, "write: Error reading Input Stream. " + e.getMessage() );
break;
}
}
}
//Call this from the main activity to send data to the remote device
public void write(byte[] bytes) {
String text = new String(bytes, Charset.defaultCharset());
Log.d(TAG, "write: Writing to outputstream: " + text);
try {
mmOutStream.write(bytes);
} catch (IOException e) {
Log.e(TAG, "write: Error writing to output stream. " + e.getMessage() );
}
}
/* Call this from the main activity to shutdown the connection */
public void cancel() {
try {
mmSocket.close();
} catch (IOException e) { }
}
}
private void connected(BluetoothSocket mmSocket, BluetoothDevice mmDevice) {
Log.d(TAG, "connected: Starting.");
// Start the thread to manage the connection and perform transmissions
mConnectedThread = new Bluetooth.ConnectedThread(mmSocket);
mConnectedThread.start();
}
public void write(byte[] out) {
// Create temporary object
Bluetooth.ConnectedThread r;
// Synchronize a copy of the ConnectedThread
Log.d(TAG, "write: Write Called.");
//perform the write
mConnectedThread.write(out);
}
}
在MainActivity上:
package com.example.myapplication;
import android.Manifest;
import android.bluetooth.BluetoothAdapter;
import android.bluetooth.BluetoothDevice;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.Build;
import android.support.annotation.RequiresApi;
import android.support.v4.app.ShareCompat;
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.Button;
import android.widget.ListView;
import android.widget.TextView;
import java.util.ArrayList;
import java.util.UUID;
public class MainActivity extends AppCompatActivity implements AdapterView.OnItemClickListener {
private static final String TAG = "MainActivity";
private static final int REQUEST_ENABLE_BT = 1;
Button btnSearch;
Button btnConnect;
TextView DEVICENAME;
ListView lvNewDevices;
public ArrayList<BluetoothDevice> mBTDevices = new ArrayList<>();
public DeviceListAdapter mDeviceListAdapter;
BluetoothAdapter bluetoothAdapter;
Bluetooth bluetoothconnection;
private static final UUID MY_UUID_INSECURE =
UUID.fromString("00001101-0000-1000-8000-00805F9B34FB");
BluetoothDevice mBTDevice;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
btnSearch = (Button) findViewById(R.id.btnsearch);
btnConnect = (Button) findViewById(R.id.btnConnect);
bluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
//pairing
IntentFilter filter = new IntentFilter(BluetoothDevice.ACTION_BOND_STATE_CHANGED);
registerReceiver(mBroadcastReceiver4, filter);
mBTDevices = new ArrayList<>();
lvNewDevices = (ListView) findViewById(R.id.lvNewDevices);
lvNewDevices.setOnItemClickListener(MainActivity.this);
bluetoothconnection = Bluetooth.getApplication();
btnSearch.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View View) {
EnableDisable_Discoverable();
Search();
Discover();
}
});
btnConnect.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Bluetooth.getApplication().start1();
Bluetooth.getApplication().setupBluetoothConnection(mBTDevice,MY_UUID_INSECURE);
}
});
}
//create method for starting connection
//***remember the conncction will fail and app will crash if you haven't paired first
private void Search() {
// BAT BlueTooth Neu BlueTooth khong bat duoc
if (bluetoothAdapter == null) {
// Device doesn't support Bluetooth
}
if (!bluetoothAdapter.isEnabled()) {
Intent enableBtIntent = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);
startActivityForResult(enableBtIntent, REQUEST_ENABLE_BT);
}
}
public void EnableDisable_Discoverable() {
Intent discoverableIntent = new Intent(BluetoothAdapter.ACTION_REQUEST_DISCOVERABLE);
discoverableIntent.putExtra(BluetoothAdapter.EXTRA_DISCOVERABLE_DURATION, 300);
startActivity(discoverableIntent);
IntentFilter intentFilter = new IntentFilter(bluetoothAdapter.ACTION_SCAN_MODE_CHANGED);
registerReceiver(mBroadcastReceiver2,intentFilter);
}
public void Discover() {
Log.d(TAG, "btnDiscover: Looking for unpaired devices.");
if (bluetoothAdapter.isDiscovering()) {
bluetoothAdapter.cancelDiscovery();
Log.d(TAG, "btnDiscover: Canceling discovery.");
//check BT permissions in manifest
checkBTPermissions();
bluetoothAdapter.startDiscovery();
IntentFilter discoverDevicesIntent = new IntentFilter(BluetoothDevice.ACTION_FOUND);
registerReceiver(mBroadcastReceiver3, discoverDevicesIntent);
}
if (!bluetoothAdapter.isDiscovering()) {
//check BT permissions in manifest
checkBTPermissions();
bluetoothAdapter.startDiscovery();
IntentFilter discoverDevicesIntent = new IntentFilter(BluetoothDevice.ACTION_FOUND);
registerReceiver(mBroadcastReceiver3, discoverDevicesIntent);
}
}
@RequiresApi(api = Build.VERSION_CODES.M)
private void checkBTPermissions() {
if (Build.VERSION.SDK_INT > Build.VERSION_CODES.LOLLIPOP) {
int permissionCheck = this.checkSelfPermission("Manifest.permission.ACCESS_FINE_LOCATION");
permissionCheck += this.checkSelfPermission("Manifest.permission.ACCESS_COARSE_LOCATION");
if (permissionCheck != 0) {
this.requestPermissions(new String[]{Manifest.permission.ACCESS_FINE_LOCATION, Manifest.permission.ACCESS_COARSE_LOCATION}, 1001); //Any number
}
} else {
Log.d(TAG, "checkBTPermissions: No need to check permissions. SDK version < LOLLIPOP.");
}
}
private final BroadcastReceiver mBroadcastReceiver2 = new BroadcastReceiver() {
@Override
public void onReceive(Context context, Intent intent) {
final String action = intent.getAction();
if (action.equals(BluetoothAdapter.ACTION_SCAN_MODE_CHANGED)) {
int mode = intent.getIntExtra(BluetoothAdapter.EXTRA_SCAN_MODE, BluetoothAdapter.ERROR);
switch (mode) {
//Device is in Discoverable Mode
case BluetoothAdapter.SCAN_MODE_CONNECTABLE_DISCOVERABLE:
Log.d(TAG, "mBroadcastReceiver2: Discoverability Enabled.");
break;
//Device not in discoverable mode
case BluetoothAdapter.SCAN_MODE_CONNECTABLE:
Log.d(TAG, "mBroadcastReceiver2: Discoverability Disabled. Able to receive connections.");
break;
case BluetoothAdapter.SCAN_MODE_NONE:
Log.d(TAG, "mBroadcastReceiver2: Discoverability Disabled. Not able to receive connections.");
break;
case BluetoothAdapter.STATE_CONNECTING:
Log.d(TAG, "mBroadcastReceiver2: Connecting....");
break;
case BluetoothAdapter.STATE_CONNECTED:
Log.d(TAG, "mBroadcastReceiver2: Connected.");
break;
}
}
}
};
private BroadcastReceiver mBroadcastReceiver3 = new BroadcastReceiver() {
@Override
public void onReceive(Context context, Intent intent) {
final String action = intent.getAction();
Log.d(TAG, "onReceive: ACTION FOUND.");
if (action.equals(BluetoothDevice.ACTION_FOUND)) {
BluetoothDevice device = intent.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE);
mBTDevices.add(device);
Log.d(TAG, "onReceive: " + device.getName() + ": " + device.getAddress());
mDeviceListAdapter = new DeviceListAdapter(context, R.layout.devices_list, mBTDevices);
lvNewDevices.setAdapter(mDeviceListAdapter);
}
}
};
private final BroadcastReceiver mBroadcastReceiver4 = new BroadcastReceiver() {
@Override
public void onReceive(Context context, Intent intent) {
final String action = intent.getAction();
if(action.equals(BluetoothDevice.ACTION_BOND_STATE_CHANGED)){
BluetoothDevice mDevice = intent.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE);
//3 cases:
//case1: bonded already
if (mDevice.getBondState() == BluetoothDevice.BOND_BONDED){
Log.d(TAG, "BroadcastReceiver: BOND_BONDED.");
mBTDevice = mDevice;
}
//case2: creating a bone
if (mDevice.getBondState() == BluetoothDevice.BOND_BONDING) {
Log.d(TAG, "BroadcastReceiver: BOND_BONDING.");
}
//case3: breaking a bond
if (mDevice.getBondState() == BluetoothDevice.BOND_NONE) {
Log.d(TAG, "BroadcastReceiver: BOND_NONE.");
}
}
}
};
@Override
protected void onDestroy() {
Log.d(TAG, "onDestroy: called.");
super.onDestroy();
unregisterReceiver(mBroadcastReceiver3);
unregisterReceiver(mBroadcastReceiver2);
unregisterReceiver(mBroadcastReceiver4);
}
public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
//first cancel discovery because its very memory intensive.
bluetoothAdapter.cancelDiscovery();
Log.d(TAG, "onItemClick: You Clicked on a device.");
String deviceName = mBTDevices.get(i).getName();
String deviceAddress = mBTDevices.get(i).getAddress();
Log.d(TAG, "onItemClick: deviceName = " + deviceName);
Log.d(TAG, "onItemClick: deviceAddress = " + deviceAddress);
if (Build.VERSION.SDK_INT > Build.VERSION_CODES.JELLY_BEAN_MR2) {
Log.d(TAG, "Trying to pair with " + deviceName);
mBTDevices.get(i).createBond();
mBTDevice = mBTDevices.get(i);
}
}
}
我看到了教程示例BluetoothChat,但这只是在mainactivity上传输数据。