私はBluetoothデバイスで作業しており、そのアプリケーションを作成しています。Android:Bluetooth Socket closed
私は上またはそれを私が問題で私を助けるための場所でキャッチいくつかのエラーを持っているコード0または1
を送信することにより、LEDこの装置の電源をオフにすることができるはず、と年齢のためにそれを見つめた後、問題がどこにあるかはわかりません。
デバイスが正しく見つかり、返されたMACアドレスがすべて正常であることを確認しました。ログで見ることができるものから、すべてのソケットを正しく開くようにも見えます。
エラーはデバイスにバイトデータを送信するプロセスの最終段階で発生します。誰も私ができない何かを見つけることができますか?接続が正常に行われていない可能性がありますか?
トリガされた例外を明確にするには、sendData()メソッドを使用します。
エラーを見つけたら、私は永遠にあなたを愛しています。
エラーメッセージ:だからFatal Error, In onResume() and an exception occurred during write:socket closed.
データを送信するか、正常に開かれることはありません前にソケットが閉じているでしょうか?
とにかく、コードのインバウンドの多くは:
public class ScanFragment extends Fragment {
ArrayList<DeviceItem> scannedList;
Button scanningButton;
TextView scanningText;
ListView scannedListView;
BluetoothAdapter mBluetoothAdapter;
DeviceItem item;
DeviceCustomAdapter adapter;
BluetoothDevice device;
String TAG = "TEST";
private BluetoothAdapter btAdapter = null;
private BluetoothSocket btSocket = null;
private OutputStream outStream = null;
// Intent request codes
private static final int REQUEST_CONNECT_DEVICE_SECURE = 1;
private static final int REQUEST_ENABLE_BT = 3;
// Well known SPP UUID
private static final UUID MY_UUID = UUID.fromString("00001101-0000-1000-8000-00805F9B34FB");
// Insert your bluetooth devices MAC address
private static String address = "00:00:00:00:00:00";
public ScanFragment() {
// Required empty public constructor
}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
return inflater.inflate(R.layout.fragment_scan, container, false);
}
@Override
public void onDestroy() {
getActivity().unregisterReceiver(mReceiver);
super.onDestroy();
}
private final BroadcastReceiver mReceiver = new BroadcastReceiver() {
public void onReceive(Context context, Intent intent) {
Log.i("found", "hello" + "");
String action = intent.getAction();
if (BluetoothDevice.ACTION_FOUND.equals(action)) {
device = intent
.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE);
item = new DeviceItem();
item.setDeviceName(device.getName());
item.setDeviceCode(device.getAddress());
item.setDeviceId(MY_UUID);
scannedList.add(item);
Log.i("BT", device.getName() + "\n" + device.getAddress());
} else {
Log.i("BT", "none" + "");
}
adapter = new DeviceCustomAdapter(
getActivity().getApplicationContext(), scannedList);
scannedListView.setAdapter(adapter);
}
};
@Override
public void onActivityCreated(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onActivityCreated(savedInstanceState);
super.onActivityCreated(savedInstanceState);
scannedList = new ArrayList<>();
scanningButton = (Button) getActivity().findViewById(R.id.scanningButton);
scanningText = (TextView) getActivity().findViewById(R.id.scanningText);
scannedListView = (ListView) getActivity().findViewById(R.id.scannedListView);
scannedListView.setVisibility(View.VISIBLE);
mBluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
if (Build.VERSION.SDK_INT >= 15 &&
ContextCompat.checkSelfPermission(getActivity(), Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
ActivityCompat.requestPermissions(getActivity(), new String[]{Manifest.permission.ACCESS_COARSE_LOCATION}, 1);
}
if (mBluetoothAdapter == null) {
scanningText.setText("Your device does not support Bluetooth, Sorry!");
} else if (!mBluetoothAdapter.isEnabled()) {
scanningText.setText("You need to enable bluetooth to use this app..");
Intent enableBtIntent = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);
startActivityForResult(enableBtIntent, REQUEST_ENABLE_BT);
}
scanningButton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
scanningText.setText("Scanning...");
mBluetoothAdapter.startDiscovery();
mBluetoothAdapter.isDiscovering();
scanningText.setText("Click on a device to connect");
}
});
// Register for broadcasts when a device is discovered.
IntentFilter filter = new IntentFilter(BluetoothDevice.ACTION_FOUND);
getActivity().registerReceiver(mReceiver, filter);
scannedListView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
@Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
item = scannedList.get(position);
String name= scannedList.get(position).getDeviceName();
Toast toast = Toast.makeText(getActivity().getApplicationContext(), "Connecting to " + item.getDeviceCode() + "" + name, Toast.LENGTH_SHORT);
toast.show();
scanningText.setText(item.getDeviceCode());
mBluetoothAdapter.cancelDiscovery();
address = item.getDeviceCode();
// Create the result Intent and include the MAC address
connectDevice(address, true);
ledOff(view);
}
});
}
public void ledOn(View v){
sendData("1");
Toast msg = Toast.makeText(getActivity().getApplicationContext(), "LED is ON", Toast.LENGTH_SHORT);
msg.show();
}
public void ledOff(View v){
sendData("0");
Toast msg = Toast.makeText(getActivity().getApplicationContext(), "LED is OFF", Toast.LENGTH_SHORT);
msg.show();
}
public void connectToDevice(String adr) {
super.onResume();
//enable buttons once connection established.
// btnOn.setEnabled(true);
// btnOff.setEnabled(true);
// Set up a pointer to the remote node using it's address.
btAdapter = mBluetoothAdapter;
BluetoothDevice device = btAdapter.getRemoteDevice(adr);
// Two things are needed to make a connection:
// A MAC address, which we got above.
// A Service ID or UUID. In this case we are using the
// UUID for SPP.
try {
btSocket = device.createRfcommSocketToServiceRecord(MY_UUID);
} catch (IOException e) {
errorExit("Fatal Error", "In onResume() and socket create failed: " + e.getMessage() + ".");
}
// Discovery is resource intensive. Make sure it isn't going on
// when you attempt to connect and pass your message.
btAdapter.cancelDiscovery();
// Establish the connection. This will block until it connects.
try {
btSocket.connect();
} catch (IOException e) {
try {
btSocket.close();
} catch (IOException e2) {
errorExit("Fatal Error", "In onResume() and unable to close socket during connection failure" + e2.getMessage() + ".");
}
}
// Create a data stream so we can talk to server.
try {
outStream = btSocket.getOutputStream();
} catch (IOException e) {
errorExit("Fatal Error", "In onResume() and output stream creation failed:" + e.getMessage() + ".");
}
}
private void errorExit(String title, String message){
Toast msg = Toast.makeText(getActivity().getApplicationContext(), title + " - " + message, Toast.LENGTH_SHORT);
msg.show();
// finish();
}
private void sendData(String message) {
byte[] msgBuffer = message.getBytes();
try {
outStream.write(msgBuffer);
} catch (IOException e) {
String msg = "In onResume() and an exception occurred during write: " + e.getMessage();
errorExit("Fatal Error", msg);
}
}
private void connectDevice(String address, boolean secure) {
// Get the device MAC address
connectToDevice(address);
// Get the BluetoothDevice object
BluetoothDevice device = btAdapter.getRemoteDevice(address);
}
}