|
package com.ch.day15_bluetooth;
import java.io.FileInputStream; import java.io.IOException; import java.io.OutputStream; import java.lang.reflect.InvocationTargetException; import java.lang.reflect.Method; import java.util.ArrayList; import java.util.Set; import java.util.UUID;
import android.os.Bundle; import android.os.Handler; import android.os.Looper; import android.app.Activity; 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.view.Menu; 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.EditText; import android.widget.ListView; import android.widget.TextView; import android.widget.Toast;
public class MainActivity extends Activity implements OnItemClickListener{ public static UUID uuid = UUID.fromString("00001001-0000-1000-8000-00805F9B34FB"); private Button check,open,scan; private EditText msg; private Button send; private TextView showmsg; //蓝牙显示的列表 private ListView pdbluetooth,unpdbluetooth; //蓝牙显示的列表的适配器 private ArrayAdapter<String> pdAdapter,unpdAdapter; private BluetoothAdapter bluetoothAdapter; private Context mcontext; //声明集合,保存配对过的蓝牙,和没有配对过 private ArrayList<BluetoothDevice> pdbluetoothDevices,unpdbluetoothDevices; //定义一个蓝牙的输出流 OutputStream output; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); mcontext = this; init(); } //接收其他的蓝牙给本手机发送的信息的线程,传递信息到这个handler,显示在主线程的ui上 Handler handler = new Handler(){ public void handleMessage(android.os.Message msg) { showmsg.setText((String)msg.obj); }; }; public void init(){ check = (Button) findViewById(R.id.check_bluetooth); open = (Button) findViewById(R.id.open_bluetooth); scan = (Button) findViewById(R.id.scan_bluetooth); //添加单击监听 check.setOnClickListener(clickLis); open.setOnClickListener(clickLis); scan.setOnClickListener(clickLis); //获得发送信息区域 msg = (EditText) findViewById(R.id.msg); send = (Button) findViewById(R.id.send); showmsg = (TextView) findViewById(R.id.showmsg1); send.setOnClickListener(clickLis); //获得listview pdbluetooth = (ListView) findViewById(R.id.pdbluetooth); unpdbluetooth = (ListView) findViewById(R.id.unpdbluetooth); //创建listview的适配器 pdAdapter = new ArrayAdapter<String>(mcontext, android.R.layout.simple_list_item_1); unpdAdapter = new ArrayAdapter<String>(mcontext, android.R.layout.simple_list_item_1); //把适配器,添加给Listview pdbluetooth.setAdapter(pdAdapter); unpdbluetooth.setAdapter(unpdAdapter); //给listview添加点击事件 pdbluetooth.setOnItemClickListener(this); unpdbluetooth.setOnItemClickListener(this); //创建保存蓝牙的集合 pdbluetoothDevices = new ArrayList<BluetoothDevice>(); unpdbluetoothDevices = new ArrayList<BluetoothDevice>(); //开启接收蓝牙信息的线程 new BlueAcceptThread(mcontext, handler).start(); } OnClickListener clickLis = new OnClickListener() { @Override public void onClick(View v) { switch (v.getId()) { //检查蓝牙设置是否有 case R.id.check_bluetooth: //获得蓝牙适配器,没有表示没有蓝牙设备 bluetoothAdapter = BluetoothAdapter.getDefaultAdapter(); if(bluetoothAdapter != null){ Toast.makeText(mcontext, "支持蓝牙!", 0).show(); }else{ Toast.makeText(mcontext, "没有蓝牙设备!", 0).show(); } break; case R.id.open_bluetooth: if(bluetoothAdapter != null){ if(!bluetoothAdapter.enable()){//蓝牙设备可不用,未打开 bluetoothAdapter.enable();//打开蓝牙 // 通过启动相关Activity打开 // Intent it = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE); // startActivity(it); } //设置蓝牙可见的时间长度为300秒 Intent it = new Intent(BluetoothAdapter.ACTION_REQUEST_DISCOVERABLE); it.putExtra(BluetoothAdapter.EXTRA_DISCOVERABLE_DURATION, 600); startActivity(it); }else{ Toast.makeText(mcontext, "检查是否支持蓝牙!", 0).show(); } break; case R.id.scan_bluetooth: pdbluetoothDevices.clear();//清空就得配对蓝牙 unpdbluetoothDevices.clear();//再一次扫描蓝牙,清空旧的未配对蓝牙列表信息 pdAdapter.clear(); unpdAdapter.clear(); if(bluetoothAdapter != null){ //如果正在扫描,关闭扫描,重新扫描 if(bluetoothAdapter.isDiscovering()){ bluetoothAdapter.cancelDiscovery(); } //获得已经配对过得蓝牙设备 Set<BluetoothDevice> devices = bluetoothAdapter.getBondedDevices(); if(devices.size() > 0){//有配对的蓝牙 //遍历配对过得蓝牙 for(BluetoothDevice device:devices){ pdbluetoothDevices.add(device);//收集配对的蓝牙 pdAdapter.add(device.getName()+"---"+device.getAddress());//把蓝牙的信息给listview的适配器 } } //注册接收扫描到蓝牙的广播,从中获得扫描到的蓝牙 IntentFilter filter1 = new IntentFilter(BluetoothDevice.ACTION_FOUND); registerReceiver(receiver, filter1); //注册扫描完成的广播 IntentFilter filter2 = new IntentFilter(BluetoothAdapter.ACTION_DISCOVERY_FINISHED); registerReceiver(receiver, filter2); //重新扫描所以蓝牙 bluetoothAdapter.startDiscovery(); }else{ Toast.makeText(mcontext, "检查是否支持蓝牙!", 0).show(); } break; case R.id.send: if(output != null){ String msgdata = msg.getText().toString(); FileInputStream fis = null; try { //发送信息到刚刚连接的蓝牙 output.write(msgdata.getBytes()); fis = new FileInputStream("/nmt/sdcard/360sicheck.txt"); int length = fis.available(); byte[] buffer = new byte[length]; fis.read(buffer); output.write(buffer); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); }finally{ try { fis.close(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } } }else{ Toast.makeText(mcontext, "请先选择一个蓝牙!", 0).show(); } break; default: break; } } }; /** * 此广播用来接收扫描到蓝牙的广播 */ BroadcastReceiver receiver = new BroadcastReceiver(){
@Override public void onReceive(Context context, Intent intent) { //接受扫描到的蓝牙 String action = intent.getAction();//得到广播的动作(类型) if(action.equals(BluetoothDevice.ACTION_FOUND)){//扫描到蓝牙的广播 //获得扫描到的蓝牙 BluetoothDevice device = intent.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE); //此蓝牙没有绑定过(配对过) if(device.getBondState() != BluetoothDevice.BOND_BONDED){ unpdbluetoothDevices.add(device);//收集未绑定的蓝牙 unpdAdapter.add(device.getName()+"---"+device.getAddress());//未绑定的蓝牙的listview的适配器 } }else if(action.equals(BluetoothAdapter.ACTION_DISCOVERY_FINISHED)){ Toast.makeText(mcontext, "扫描完成!", 0).show(); } } };
/** * lisrview的点击事件监听器 */ @Override public void onItemClick(AdapterView<?> parent, View view, int position, long id) { switch (parent.getId()) { case R.id.pdbluetooth://点击的是配对过的listview pairOrConnectionDevice(pdbluetoothDevices.get(position));//操作配对过的蓝牙 break; case R.id.unpdbluetooth://点击的是没有配对过的listview pairOrConnectionDevice(unpdbluetoothDevices.get(position));//操作没有配对过的蓝牙 break;
default: break; } } /** * 此方法负责处理蓝牙,配对或直接连接 * @param bluetoothDevice */ private void pairOrConnectionDevice(BluetoothDevice bluetoothDevice) { int state = bluetoothDevice.getBondState();//获得 if(state == BluetoothDevice.BOND_NONE){//还没有配对,进行配对 try { //通过反射,设置此蓝牙为绑定状态 Method method = BluetoothDevice.class.getMethod("createBond"); method.invoke(bluetoothDevice); Toast.makeText(mcontext, bluetoothDevice.getName()+",配对成功!", 0).show(); } catch (Exception e) { e.printStackTrace(); Toast.makeText(mcontext, bluetoothDevice.getName()+",配对失败!", 0).show(); } }else if(state == BluetoothDevice.BOND_BONDED){//配对过的,进行连接 new BlueToothConnection(bluetoothDevice).start(); } } /** * 此线程用于为蓝牙建立连接,发送信息 * @author hchen * */ class BlueToothConnection extends Thread{ BluetoothDevice device; BluetoothSocket bluetoothSocket; public BlueToothConnection(BluetoothDevice device) { super(); this.device = device; }
@Override public void run() { Looper.prepare();//发送信息前的准备 try { //创建此蓝牙的客户端,通过客户端可以向它传递数据 bluetoothSocket = device.createRfcommSocketToServiceRecord(uuid); //连接 System.out.println("000000000000000"); bluetoothSocket.connect(); System.out.println("1111111111111111111"); //创建此蓝牙的具体的输出流 output = bluetoothSocket.getOutputStream(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } Looper.loop(); } }
}
|