尝试获取配对设备的列表时,会发生意外错误,导致我的应用停止。解决所有这些复杂问题对我来说是新的 这是我的MainActivity.java:
package com.example.admin.bluetooth_demo;
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.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.Toast;
import java.io.IOException;
import java.util.ArrayList;
import java.util.UUID;
public class MainActivity extends AppCompatActivity {
private ListView lv;
private ArrayList<String> mDeviceList = new ArrayList<String>();
private BluetoothAdapter BA;
Button openbtn,closebtn,searchbtn,senbtn;
ArrayList<BluetoothDevice>mmPairedDevicesList;
BluetoothDevice mmDevice;
BluetoothSocket mmSocket;
EditText entry;
String msg;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
lv = (ListView)findViewById(R.id.list_devices);
openbtn = (Button)findViewById(R.id.button_open);
closebtn = (Button)findViewById(R.id.button_close);
searchbtn = (Button)findViewById(R.id.button_search);
senbtn = (Button)findViewById(R.id.button4);
entry = (EditText)findViewById(R.id.editText_entry);
msg = entry.getText().toString();
BA = BluetoothAdapter.getDefaultAdapter();
openbtn.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
if(BA == null){
Toast.makeText(MainActivity.this,"No connection!!",Toast.LENGTH_LONG).show();
}else{
if(!BA.isEnabled()){
Intent turnOn = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);
startActivityForResult(turnOn, 0);
Toast.makeText(getApplicationContext(), "Turned on",Toast.LENGTH_LONG).show();
}else{
Toast.makeText(getApplicationContext(), "Already on", Toast.LENGTH_LONG).show();
}
}
}
});
closebtn.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
BA.disable();
Toast.makeText(getApplicationContext(), "Turned off" ,Toast.LENGTH_LONG).show();
}
});
searchbtn.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
BA.startDiscovery();
IntentFilter filter = new IntentFilter(BluetoothDevice.ACTION_FOUND);
registerReceiver(mReceiver,filter);
}
});
lv.setOnItemClickListener(new AdapterView.OnItemClickListener() {
@Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
ConnectThread mConnectThread = new ConnectThread(mmPairedDevicesList.get(position));
mConnectThread.start();
}
});
}
private final BroadcastReceiver mReceiver = new BroadcastReceiver() {
public void onReceive(Context context, Intent intent) {
String action = intent.getAction();
if (BluetoothDevice.ACTION_FOUND.equals(action)) {
BluetoothDevice device = intent
.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE);
mDeviceList.add(device.getName() + "\n" + device.getAddress());
mmPairedDevicesList.add(device);
Log.i("BT", device.getName() + "\n" + device.getAddress());
ArrayAdapter adp = new ArrayAdapter(context,android.R.layout.simple_list_item_1,mDeviceList);
lv.setAdapter(adp);
adp.notifyDataSetChanged();
}
}
};
public class ConnectThread extends Thread{
UUID uuid = UUID.fromString("00001101-0000-1000-8000-00805F9B34FB");
public ConnectThread(BluetoothDevice device){
BluetoothSocket tmp = null;
mmDevice = device;
try{
tmp = device.createRfcommSocketToServiceRecord(uuid);
} catch (IOException e) {
e.printStackTrace();
}
mmSocket = tmp;
}
public void run(){
BA.cancelDiscovery();
try{
mmSocket.connect();
} catch (IOException e) {
try{
mmSocket.close();
} catch (IOException e1) {
e1.printStackTrace();
}
return;
}
final ConnectedThread mConnectedThread = new ConnectedThread(mmSocket);
mConnectedThread.start();
senbtn.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
msg += "\n";
mConnectedThread.write(msg.getBytes());
Toast.makeText(MainActivity.this,"Data sent!!!",Toast.LENGTH_LONG).show();
}
});
}
public void cancel(){
try{
mmSocket.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
这是ConnectedThread.java:
package com.example.admin.bluetooth_demo;
import android.bluetooth.BluetoothSocket;
import android.os.Handler;
import android.os.Message;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
public class ConnectedThread extends Thread {
private BluetoothSocket mmBluetoothsocket;
private InputStream mInputStream;
private OutputStream mOutputStream;
public ConnectedThread(BluetoothSocket socket){
mmBluetoothsocket = socket;
InputStream tmpIN = null;
OutputStream tmpOUT = null;
try{
tmpIN = socket.getInputStream();
tmpOUT = socket.getOutputStream();
} catch (IOException e) {
e.printStackTrace();
}
mInputStream = tmpIN;
mOutputStream = tmpOUT;
}
public void run(){
byte[] buffer = new byte[1024];
int begin = 0;
int bytes = 0;
Handler mHandler = new Handler(){
@Override
public void handleMessage(Message msg){
byte [] writeBuff = (byte[]) msg.obj;
int begin = (int) msg.arg1;
int end = (int) msg.arg2;
switch(msg.what){
case 1:
String writeMessage = new String (writeBuff);
writeMessage = writeMessage.substring(begin,end);
break;
}
}
};
while(true){
try{
bytes += mInputStream.read(buffer, bytes, buffer.length-bytes);
for (int i = begin; i < bytes; i++){
if(buffer[i] == "#".getBytes()[0]){
mHandler.obtainMessage(1,begin,i,buffer).sendToTarget();
begin = i + 1;
if(i == bytes-1){
bytes = 0;
begin = 0;
}
}
}
} catch (IOException e) {
e.printStackTrace();
}
}
}
public void write(byte[] bytes){
try{
mOutputStream.write(bytes);
} catch (IOException e) {
e.printStackTrace();
}
}
public void cancel(){
try{
mmBluetoothsocket.close();
mOutputStream.close();
mInputStream.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
这是Main.xml
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:id="@+id/activity_main"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:paddingBottom="@dimen/activity_vertical_margin"
android:paddingLeft="@dimen/activity_horizontal_margin"
android:paddingRight="@dimen/activity_horizontal_margin"
android:paddingTop="@dimen/activity_vertical_margin"
tools:context="com.example.admin.bluetooth_demo.MainActivity">
<EditText
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:inputType="textPersonName"
android:text="Type here:"
android:ems="10"
android:layout_above="@+id/button_open"
android:layout_alignParentLeft="true"
android:layout_alignParentStart="true"
android:id="@+id/editText_entry"
android:layout_alignParentRight="true"
android:layout_alignParentEnd="true" />
<ListView
android:layout_width="match_parent"
android:layout_height="match_parent"
android:id="@+id/list_devices"
android:layout_above="@+id/editText_entry"
android:layout_alignParentLeft="true"
android:layout_alignParentStart="true" />
<Button
android:text="Open"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="@+id/button_open"
android:layout_alignParentBottom="true"
android:layout_alignParentLeft="true"
android:layout_alignParentStart="true" />
<Button
android:text="Close"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="@+id/button_close"
android:layout_alignParentBottom="true"
android:layout_toRightOf="@+id/button_open"
android:layout_toEndOf="@+id/button_open" />
<Button
android:text="Send"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="@+id/button4"
android:layout_alignParentBottom="true"
android:layout_toRightOf="@+id/button_close"
android:layout_toEndOf="@+id/button_close" />
<Button
android:text="Search"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="@+id/button_search"
android:layout_alignParentBottom="true"
android:layout_alignParentRight="true"
android:layout_alignParentEnd="true" />
</RelativeLayout>