我发布了完整的代码以正确理解它。代码运行良好,但是当我通过单击菜单项连接新的搜索设备时,应用程序崩溃...问题出在方法中:
listViewPairedDevices.setOnItemClickListener(new OnItemClickListener() 请帮帮我
package com.example.bluetoothcheck5;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.Set;
import java.util.UUID;
import android.os.AsyncTask;
import android.os.Bundle;
import android.app.Activity;
import android.app.ProgressDialog;
import android.bluetooth.BluetoothAdapter;
import android.bluetooth.BluetoothDevice;
import android.bluetooth.BluetoothSocket;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.DialogInterface.OnCancelListener;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.FrameLayout;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;
public class MainActivity extends Activity {
private static final int REQUEST_ENABLE_BT = 0;
private BluetoothSocket mmSocket=null;
private InputStream mmInStream;
private OutputStream mmOutStream;
private static final UUID MY_UUID = UUID.fromString("fa87c0d0-afac-11de-8a39- 0800200c9a66");
private static final int REQUEST_DISCOVERABLE_BT = 0;
protected ArrayAdapter<String> mArrayAdapter;
BluetoothDevice mDevice ;
protected BluetoothAdapter mBluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
@Override
protected void onCreate(Bundle savedInstanceState) {
mArrayAdapter=new ArrayAdapter<String>(this,android.R.layout.simple_list_item_1,0);
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
final TextView out=(TextView)findViewById(R.id.out);
final Button button = (Button) findViewById(R.id.scan);
final Button button1 = (Button) findViewById(R.id.button2);
final Button button2 = (Button) findViewById(R.id.button3);
final Button buttonSearch = (Button) findViewById(R.id.buttonSearch);
final ListView listViewPairedDevices = (ListView) findViewById(R.id.listViewneww);
listViewPairedDevices.setAdapter(mArrayAdapter);
final Button buttonnewdev = (Button) findViewById(R.id.buttonnew);
IntentFilter filter = new IntentFilter(BluetoothDevice.ACTION_FOUND);
this.registerReceiver(mReceiver, filter);
// Register for broadcasts when discovery has finished
filter = new IntentFilter(BluetoothAdapter.ACTION_DISCOVERY_FINISHED);
this.registerReceiver(mReceiver, filter);
if (mBluetoothAdapter == null) {
out.append("device not supported");
}
button.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
if (!mBluetoothAdapter.isEnabled()) {
Intent enableBtIntent = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);
startActivityForResult(enableBtIntent, REQUEST_ENABLE_BT);
}
}
});
button1.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View arg0) {
if (!mBluetoothAdapter.isDiscovering()) {
Context context = getApplicationContext();
CharSequence text = "MAKING YOUR DEVICE DISCOVERABLE";
int duration = Toast.LENGTH_SHORT;
Toast toast = Toast.makeText(context, text, duration);
toast.show();
Intent enableBtIntent = new Intent(BluetoothAdapter.ACTION_REQUEST_DISCOVERABLE);
startActivityForResult(enableBtIntent, REQUEST_DISCOVERABLE_BT);
}
}
});
button2.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View arg0) {
mBluetoothAdapter.disable();
Context context = getApplicationContext();
CharSequence text = "TURNING_OFF BLUETOOTH";
Toast toast = Toast.makeText(context, text, Toast.LENGTH_LONG);
toast.show();
}
});
buttonSearch.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Set<BluetoothDevice> mPairedDevices = mBluetoothAdapter.getBondedDevices();
if (mPairedDevices.size() > 0)
{
for ( BluetoothDevice mDevice : mPairedDevices)
{
Log.v("Title", "PairedDevices: " + mDevice.getName() + " " + mDevice.getAddress());
//Toast.makeText(v.getContext(), mDevice.getName(), Toast.LENGTH_LONG).show();
//Toast.makeText(v.getContext(), mDevice.getAddress(), Toast.LENGTH_LONG).show();
mArrayAdapter.add(mDevice.getName());
mArrayAdapter. notifyDataSetChanged();
}
}
//Intent myIntent= new Intent(v.getContext(),Activity2.class);
//startActivity(myIntent);
}
});
buttonnewdev.setOnClickListener(new OnClickListener(){
@Override
public void onClick(View v) {
if (mBluetoothAdapter.isDiscovering()) {
mBluetoothAdapter.cancelDiscovery();
}
// Request discover from BluetoothAdapter
mBluetoothAdapter.startDiscovery();
}
});
listViewPairedDevices.setOnItemClickListener(new OnItemClickListener() {
@Override
public void onItemClick(AdapterView<?> arg0, View arg1, int arg2,
long arg3) {
mBluetoothAdapter.cancelDiscovery();
Toast.makeText(arg1.getContext(), "Clicked", T Toast.LENGTH_LONG).show();
ConnectThread(mDevice);
}
});
}
private BroadcastReceiver mReceiver = new BroadcastReceiver() {
@Override
public void onReceive(Context context, Intent intent) {
String action = intent.getAction();
// When discovery finds a device
if (BluetoothDevice.ACTION_FOUND.equals(action)) {
// Get the BluetoothDevice object from the Intent
BluetoothDevice device = intent.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE);
// If it's already paired, skip it, because it's been listed already
if (device.getBondState() != BluetoothDevice.BOND_BONDED) {
mArrayAdapter.add(device.getName() + "\n" + device.getAddress());
}
// When discovery is finished, change the Activity title
} else if (BluetoothAdapter.ACTION_DISCOVERY_FINISHED.equals(action)) {
setProgressBarIndeterminateVisibility(false);
setTitle(R.string.select_device);
if (mArrayAdapter.getCount() == 0) {
String noDevices = getResources().getText(R.string.none_found).toString();
mArrayAdapter.add(noDevices);
}
}
}
};
public void ConnectThread(BluetoothDevice device) {
// Use a temporary object that is later assigned to mmSocket,
// because mmSocket is final
BluetoothSocket tmp = null;
mDevice = device;
// 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) { }
mmSocket = tmp;
try {
// Connect the device through the socket. This will block
// until it succeeds or throws an exception
mmSocket.connect();
} catch (IOException connectException) {
// 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)
manageConnectedSocket(mmSocket);
}
/** Will cancel an in-progress connection, and close the socket
* @return */
public void manageConnectedSocket(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 = 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) {
try {
// Read from the InputStream
bytes = mmInStream.read(buffer);
// Send the obtained bytes to the UI activity
// mHandler.obtainMessage("hhg", 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) { }
}
}