package com.blue;import java.io.IOException;
import java.io.InputStream;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.util.ArrayList;
import java.util.List;
import java.util.UUID;import com.blue.R;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.Intent;
import android.content.IntentFilter;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ArrayAdapter;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;public class BlueToothTestActivity extends Activity implements
OnItemClickListener {
private static final String TAG = "BlueToothTestActivity";
private BluetoothAdapter bluetoothAdapter;
private ListView listView;
private TextView textView;
private List<String> list;
private ArrayAdapter<String> arrayAdapter;
private BluetoothSocket bluetoothSocket;
private ProgressDialog progressDialog;// 开始搜索进度框
private static final String MYUUID = "00001101-0000-1000-8000-00805F9B34FB";
private String string = "", a = "";
private GetString getString; private Handler myHandler = new Handler() {
@Override
public void handleMessage(Message msg) {
super.handleMessage(msg);
switch (msg.what) {
case 0:
string = new String((byte[]) msg.obj, 0, msg.arg1);// 此处要根据条码的结束符来判断一次扫描是否完成,不然会出现断码
if (string.indexOf("\r") != -1) {
string = a + string;
textView.setText(string);
string = "";
a = "";
} else {
a = string;
}
break; default:
break;
}
}
}; /** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
bluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
list = new ArrayList<String>();
textView = (TextView) findViewById(R.id.text);
listView = (ListView) findViewById(R.id.listview);
arrayAdapter = new ArrayAdapter<String>(this,
android.R.layout.simple_list_item_1, list);
listView.setAdapter(arrayAdapter);
listView.setOnItemClickListener(this);
setListener();
} private void setListener() {
// 设置广播过滤
IntentFilter intentFilter = new IntentFilter();
intentFilter.addAction(BluetoothAdapter.ACTION_DISCOVERY_STARTED);
intentFilter.addAction(BluetoothAdapter.ACTION_DISCOVERY_FINISHED);
intentFilter.addAction(BluetoothDevice.ACTION_FOUND);
intentFilter.addAction(BluetoothDevice.ACTION_BOND_STATE_CHANGED);
// 注册广播并且接收处理广播
registerReceiver(broadcastReceiver, intentFilter);
} @Override
public boolean onCreateOptionsMenu(Menu menu) {
// TODO Auto-generated method stub
MenuInflater menuInflater = new MenuInflater(this);
menuInflater.inflate(R.menu.menu, menu);
return super.onCreateOptionsMenu(menu);
} @Override
public boolean onOptionsItemSelected(MenuItem item) {
// TODO Auto-generated method stub
switch (item.getItemId()) {
case R.id.query:
// if (bluetoothAdapter.isEnabled()) {
if (bluetoothAdapter.getState() == BluetoothAdapter.STATE_OFF) {
Toast.makeText(this, "蓝牙没打开", 0).show();
Intent intent = new Intent(
BluetoothAdapter.ACTION_REQUEST_ENABLE);
startActivityForResult(intent, 0);
} else {
// 查找设备,找到后以广播形式发送
bluetoothAdapter.startDiscovery();
}
/*
 * } else { Toast.makeText(this, "设备不可用", 0).show(); }
 */
break;
case R.id.exit:
finish();
Toast.makeText(getApplicationContext(), "已退出", Toast.LENGTH_SHORT)
.show();
break;
default:
break;
}
return super.onOptionsItemSelected(item);
} @Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
// TODO Auto-generated method stub
super.onActivityResult(requestCode, resultCode, data);
if (resultCode == RESULT_OK) {
if (requestCode == 0) {
bluetoothAdapter.startDiscovery();
}
}
} /*
 * private void querydevice() { // TODO Auto-generated method stub
 * Set<BluetoothDevice> bluetoothDevices = bluetoothAdapter
 * .getBondedDevices(); for (BluetoothDevice bluetoothDevice :
 * bluetoothDevices) { String device = bluetoothDevice.getName() + "|" +
 * bluetoothDevice.getAddress(); arrayAdapter.add(device);
 * arrayAdapter.notifyDataSetChanged(); } }
 */ private BroadcastReceiver broadcastReceiver = new BroadcastReceiver() { @Override
public void onReceive(Context context, Intent intent) {
// TODO Auto-generated method stub
String action = intent.getAction();
if (action.equals(BluetoothDevice.ACTION_FOUND)) {
Toast.makeText(BlueToothTestActivity.this, "发现设备", 0).show();
BluetoothDevice bluetoothDevice = intent
.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE);
String device = bluetoothDevice.getName() + "|"
+ bluetoothDevice.getAddress();
if (list.indexOf(device) == -1) {
list.add(device);
arrayAdapter.notifyDataSetChanged();
}
} else if (action.equals(BluetoothDevice.ACTION_BOND_STATE_CHANGED)) {
BluetoothDevice bluetoothDevice = intent
.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE);
switch (bluetoothDevice.getBondState()) {
case BluetoothDevice.BOND_BONDING:
Toast.makeText(BlueToothTestActivity.this, "正在配对...", 0)
.show();
break;
case BluetoothDevice.BOND_BONDED:
Toast.makeText(BlueToothTestActivity.this, "已配对", 0).show();
break;
default:
break;
}
} else if (action.equals(BluetoothAdapter.ACTION_DISCOVERY_STARTED)) {
progressDialog = ProgressDialog.show(
BlueToothTestActivity.this, null, "正在搜索,请稍后...", true,
true);
} else if (action
.equals(BluetoothAdapter.ACTION_DISCOVERY_FINISHED)) {
progressDialog.cancel();
Toast.makeText(BlueToothTestActivity.this, "搜索结束", 0).show();
}
}
}; @Override
protected void onDestroy() {
// TODO Auto-generated method stub
super.onDestroy();
if (bluetoothSocket != null) {
try {
bluetoothSocket.close();
} catch (IOException e) {
e.printStackTrace();
}
}
if (getString != null) {
if (getString.isAlive()) {
getString.stop();
}
}
unregisterReceiver(broadcastReceiver);
android.os.Process.killProcess(android.os.Process.myPid());
Toast.makeText(getApplicationContext(), "~~~~~", Toast.LENGTH_SHORT)
.show();
} public void onItemClick(AdapterView<?> arg0, View arg1, int arg2, long arg3) {
// TODO Auto-generated method stub
if (bluetoothAdapter.isDiscovering()) {
bluetoothAdapter.cancelDiscovery();
}
String string = list.get(arg2);
String[] value = string.split("\\|");
Log.i(TAG, "value=" + value);
String address = value[1];
Log.i(TAG, "address=" + address);
BluetoothDevice bluetoothDevice = bluetoothAdapter
.getRemoteDevice(address);
if (BluetoothDevice.BOND_NONE == bluetoothDevice.getBondState()) {
try {
Method method = BluetoothDevice.class.getMethod("createBond");
try {
method.invoke(bluetoothDevice);
} catch (IllegalArgumentException e) {
e.printStackTrace();
} catch (IllegalAccessException e) {
e.printStackTrace();
} catch (InvocationTargetException e) {
e.printStackTrace();
}
} catch (SecurityException e) {
e.printStackTrace();
} catch (NoSuchMethodException e) {
e.printStackTrace();
}
} else if (BluetoothDevice.BOND_BONDED == bluetoothDevice
.getBondState()) {
connect(bluetoothDevice);
}
} private void connect(BluetoothDevice bluetoothDevice) {
UUID uuid = UUID.fromString(MYUUID);
try {
bluetoothSocket = bluetoothDevice
.createRfcommSocketToServiceRecord(uuid);
bluetoothSocket.connect();
Toast.makeText(BlueToothTestActivity.this, "已连接", 0).show();
getString = new GetString(bluetoothSocket);
getString.start();
} catch (IOException e) {
Toast.makeText(BlueToothTestActivity.this, "连接失败", 0).show();
try {
bluetoothSocket.close();
} catch (IOException e1) {
e1.printStackTrace();
}
e.printStackTrace();
}
} private class GetString extends Thread {
private BluetoothSocket Socket;
private InputStream inputStream;
byte[] buffer = new byte[1024];
int bytes; public GetString(BluetoothSocket bluetoothSocket) {
super();
this.Socket = bluetoothSocket;
try {
inputStream = Socket.getInputStream();
} catch (IOException e) {
e.printStackTrace();
}
} public void run() {
while (true) {
try {
bytes = inputStream.read(buffer);
System.out.println("bytes=" + bytes);
myHandler.sendMessage(myHandler.obtainMessage(0, bytes, -1,
buffer));
} catch (IOException e) {
Toast.makeText(BlueToothTestActivity.this, "设备失去了连接", 0)
.show();
if (inputStream != null) {
try {
inputStream.close();
} catch (IOException e1) {
e1.printStackTrace();
}
}
if (Socket != null) {
try {
Socket.close();
} catch (IOException e1) {
e1.printStackTrace();
}
}
break;
}
}
}
}
}上面的代码中,我用是从上一个页面Intent到这个页面来的,上个页面也没有finish(),但是我在这个页面退出了以后,把我上个Activity也关了,我找不到是那句代码的问题,你们帮我找找哈,不胜感激啦...