实例介绍
【实例简介】

【核心代码】
package com.example.administrator.new_dianzixitongzonghesheji; import android.bluetooth.BluetoothAdapter; import android.bluetooth.BluetoothDevice; import android.bluetooth.BluetoothServerSocket; import android.bluetooth.BluetoothSocket; import android.content.BroadcastReceiver; import android.content.ClipData; import android.content.ClipboardManager; import android.content.Context; import android.content.Intent; import android.content.IntentFilter; import android.os.Bundle; import android.provider.Settings; import android.support.v7.app.ActionBarActivity; import android.telephony.TelephonyManager; import android.view.View; import android.widget.AdapterView; import android.widget.ArrayAdapter; import android.widget.Button; import android.widget.ListView; import android.widget.TextView; import android.widget.Toast; import com.example.administrator.new_dianzixitongzonghesheji.BlueToothDeviceAdapter; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import java.security.PublicKey; import java.util.ArrayList; import java.util.List; import java.util.Set; import java.util.UUID; import com.example.administrator.new_dianzixitongzonghesheji.R; /** * Created by 56305 on 2018/6/28. */ public class bluetooth_lianjie extends ActionBarActivity implements View.OnClickListener { public MainActivity a; private BluetoothAdapter bTAdatper; private ListView listView; private ListView listView1; //省赛补充-周泽鑫 2018/7/31 private BlueToothDeviceAdapter adapter; String androidId = null; static String androidId_data; static String new_androidId_data; //省赛补充-周泽鑫 2018/7/31 Toast tst; TextView text_state; TextView textView1; //省赛补充-周泽鑫 2018/7/31 private TextView text_msg; boolean kaimenorguanmen=true; boolean kaidengorguandeng=true; //省赛补充-周泽鑫 2018/7/31 boolean kaifengshanorguanfengshan=true; //省赛补充-周泽鑫 2018/7/31 boolean switch_bluetooth=true; private final int BUFFER_SIZE = 1024; byte[] buffer = new byte[BUFFER_SIZE]; int bytes; private static final String NAME = "BT_DEMO"; private static final UUID BT_UUID = UUID.fromString("00001101-0000-1000-8000-00805F9B34FB"); boolean lianjie_state=false; ConnectThread connectThread; private ListenerThread listenerThread; Button btn_kaimen,btn_openBT,btn_kaideng,btn_kaifengshan; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.bluetooth_lianjie); initView(); bTAdatper = BluetoothAdapter.getDefaultAdapter(); initReceiver(); listenerThread = new ListenerThread(); listenerThread.start(); btn_kaimen=(Button)findViewById(R.id.btn_kaimen); btn_kaimen.setOnClickListener(this); //省赛补充-周泽鑫 2018/7/31 btn_kaideng=(Button)findViewById(R.id.btn_kaideng); btn_kaideng.setOnClickListener(this); btn_kaifengshan=(Button)findViewById(R.id.btn_kaifengshan); btn_kaifengshan.setOnClickListener(this); //省赛补充-周泽鑫 2018/7/31 btn_openBT=(Button)findViewById(R.id.btn_openBT); btn_openBT.setOnClickListener(this); listView1 = new ListView(this); androidId_data="7659483c763e8649"; if (!bTAdatper.isEnabled()) {btn_openBT.setText("打开蓝牙"); switch_bluetooth=true; } else {btn_openBT.setText("关闭蓝牙"); switch_bluetooth=false; } } private void initView() { // findViewById(R.id.btn_openBT).setOnClickListener(this); findViewById(R.id.btn_search).setOnClickListener(this); findViewById(R.id.btn_send).setOnClickListener(this); findViewById(R.id.btn_dengji).setOnClickListener(this); // findViewById(R.id.btn_kaimen).setOnClickListener(this); findViewById(R.id.btn_tianjia).setOnClickListener(this); findViewById(R.id.btn_shanchu).setOnClickListener(this); findViewById(R.id.btn_record).setOnClickListener(this); //省赛补充-周泽鑫 2018/7/31 findViewById(R.id.btn_user).setOnClickListener(this); //省赛补充-周泽鑫 2018/7/31 // findViewById(R.id.btn_kaideng).setOnClickListener(this); // findViewById(R.id.btn_kaifengshan).setOnClickListener(this); text_state = (TextView) findViewById(R.id.text_state); text_msg = (TextView) findViewById(R.id.text_msg); textView1=(TextView) findViewById(R.id.textView1); androidId = Settings.Secure.getString(getContentResolver(), Settings.Secure.ANDROID_ID); listView = (ListView) findViewById(R.id.listView); adapter = new BlueToothDeviceAdapter(getApplicationContext(), R.layout.device_list); listView.setAdapter(adapter); listView.setOnItemClickListener(new AdapterView.OnItemClickListener() { @Override public void onItemClick(AdapterView<?> parent, View view, int position, long id) { if (bTAdatper.isDiscovering()) { bTAdatper.cancelDiscovery(); } BluetoothDevice device = (BluetoothDevice) adapter.getItem(position); //连接设备 connectDevice(device); } }); } private void initReceiver() { //注册广播 IntentFilter filter = new IntentFilter(); filter.addAction(BluetoothDevice.ACTION_FOUND); filter.addAction(BluetoothAdapter.ACTION_DISCOVERY_STARTED); filter.addAction(BluetoothAdapter.ACTION_DISCOVERY_FINISHED); registerReceiver(mReceiver, filter); } @Override public void onClick(View v) { switch (v.getId()) { case R.id.btn_openBT: if(switch_bluetooth) { openBlueTooth(); btn_openBT.setText("关闭蓝牙"); switch_bluetooth=false; } else { bTAdatper.disable(); btn_openBT.setText("打开蓝牙"); Toast.makeText(getApplicationContext(), "蓝牙已关闭", Toast.LENGTH_LONG); switch_bluetooth=true; } break; case R.id.btn_search: if( bTAdatper.isEnabled()) { searchDevices(); textView1.setText("房间名 \t\t \t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tMAC"); } else { Toast.makeText(bluetooth_lianjie.this, "请先打开蓝牙!", Toast.LENGTH_SHORT).show(); } break; case R.id.btn_send: if (connectThread != null) { connectThread.sendMsg("111"); } break; /* case R.id.fanhui: { Intent intent =new Intent(bluetooth_lianjie.this,com.example.administrator.new_dianzixitongzonghesheji.MainActivity.class); startActivity(intent); // finish(); } break;*/ case R.id.btn_dengji: { if( lianjie_state) { tst = Toast.makeText(bluetooth_lianjie.this, androidId, Toast.LENGTH_SHORT); tst.show(); // CopyToClipboard(context,androidId); ClipboardManager cm = (ClipboardManager) getSystemService(Context.CLIPBOARD_SERVICE); // 创建普通字符型ClipData ClipData mClipData = ClipData.newPlainText("本机Android_ID是", androidId); cm.setPrimaryClip(mClipData); // connectThread.sendMsg(getPhoneNumber() androidId); //省赛补充-周泽鑫 2018/7/31 登记时发送 手机号码 AndroidID, connectThread.sendMsg(androidId); } //即添加用户时发送 手机号码 AndroidID 给stm32 else Toast.makeText(bluetooth_lianjie.this, "请先连接蓝牙!", Toast.LENGTH_SHORT).show(); } break; case R.id.btn_kaimen: //开门 { if( lianjie_state) { if (kaimenorguanmen) { connectThread.sendMsg("D" androidId "1"); kaimenorguanmen = false; btn_kaimen.setText("关门"); } else { connectThread.sendMsg("D" androidId "0"); kaimenorguanmen = true; btn_kaimen.setText("开门"); } } else Toast.makeText(bluetooth_lianjie.this, "请先连接蓝牙!", Toast.LENGTH_SHORT).show(); } break; //省赛补充-周泽鑫 2018/7/31 case R.id.btn_kaideng: { if( lianjie_state) { if (kaidengorguandeng) { connectThread.sendMsg("L" androidId "1"); //开灯 kaidengorguandeng = false; btn_kaideng.setText("关灯"); } else { connectThread.sendMsg("L" androidId "0"); //关灯 kaidengorguandeng = true; btn_kaideng.setText("开灯"); } } else Toast.makeText(bluetooth_lianjie.this, "请先连接蓝牙!", Toast.LENGTH_SHORT).show(); } break; //省赛补充-周泽鑫 2018/7/31 //省赛补充-周泽鑫 2018/7/31 case R.id.btn_kaifengshan: { if( lianjie_state) { if (kaifengshanorguanfengshan) { connectThread.sendMsg("F" androidId "1"); //开风扇 kaifengshanorguanfengshan = false; btn_kaifengshan.setText("关风扇"); } else { connectThread.sendMsg("F" androidId "0"); //关风扇 kaifengshanorguanfengshan = true; btn_kaifengshan.setText("开风扇"); } } else Toast.makeText(bluetooth_lianjie.this, "请先连接蓝牙!", Toast.LENGTH_SHORT).show(); } break; //省赛补充-周泽鑫 2018/7/31 //省赛补充-周泽鑫 2018/7/31 case R.id.btn_user: //返回用户 { if( lianjie_state) { connectThread.sendMsg("U" androidId ); } else Toast.makeText(bluetooth_lianjie.this, "请先连接蓝牙!", Toast.LENGTH_SHORT).show(); } break; //省赛补充-周泽鑫 2018/7/31 case R.id.btn_record: //返回开门记录 { if( lianjie_state) { connectThread.sendMsg("J" androidId ); ; } else Toast.makeText(bluetooth_lianjie.this, "请先连接蓝牙!", Toast.LENGTH_SHORT).show(); } break; //省赛补充-周泽鑫 2018/7/31 case R.id.btn_tianjia: { if(text_msg.getText().toString()!=null) { if((returnResultMultiple(text_msg.getText().toString()).length()==16)||(returnResultMultiple(text_msg.getText().toString()).length()==15)) { connectThread.sendMsg( androidId "T" returnResultMultiple(text_msg.getText().toString())); Toast.makeText(bluetooth_lianjie.this, "添加权限成功", Toast.LENGTH_SHORT).show(); } else//添加 { Toast.makeText(bluetooth_lianjie.this, "请录入正确的要添加的身份码", Toast.LENGTH_SHORT).show(); } } else { Toast.makeText(bluetooth_lianjie.this, "请录入要添加的身份码", Toast.LENGTH_SHORT).show(); } // finish(); } break; case R.id.btn_shanchu: { if(text_msg.getText().toString()!=null) { if((returnResultMultiple(text_msg.getText().toString()).length()==16)||(returnResultMultiple(text_msg.getText().toString()).length()==15)) { connectThread.sendMsg( androidId "S" returnResultMultiple(text_msg.getText().toString())); Toast.makeText(bluetooth_lianjie.this, "删除权限成功", Toast.LENGTH_SHORT).show(); } else { Toast.makeText(bluetooth_lianjie.this, "请录入正确的要删除的身份码", Toast.LENGTH_SHORT).show(); } //删除 } // finish(); else { Toast.makeText(bluetooth_lianjie.this, "请录入要添加的身份码", Toast.LENGTH_SHORT).show(); } } break; } } /** * 开启蓝牙 */ private void openBlueTooth() { if (bTAdatper == null) { Toast.makeText(this, "当前设备不支持蓝牙功能", Toast.LENGTH_SHORT).show(); } if (!bTAdatper.isEnabled()) { /* Intent i = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE); startActivity(i);*/ bTAdatper.enable(); } else Toast.makeText(bluetooth_lianjie.this, "蓝牙已打开", Toast.LENGTH_SHORT).show(); //开启被其它蓝牙设备发现的功能 if (bTAdatper.getScanMode() != BluetoothAdapter.SCAN_MODE_CONNECTABLE_DISCOVERABLE) { Intent i = new Intent(BluetoothAdapter.ACTION_REQUEST_DISCOVERABLE); //设置为一直开启 i.putExtra(BluetoothAdapter.EXTRA_DISCOVERABLE_DURATION, 0); startActivity(i); } } /** * 搜索蓝牙设备 */ private void searchDevices() { if (!bTAdatper.isEnabled()) { /* Intent i = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE); startActivity(i);*/ Toast.makeText(bluetooth_lianjie.this, "蓝牙未打开,请打开蓝牙", Toast.LENGTH_SHORT).show(); } if (bTAdatper.isDiscovering()) { bTAdatper.cancelDiscovery(); } getBoundedDevices(); bTAdatper.startDiscovery(); } /** * 获取已经配对过的设备 */ private void getBoundedDevices() { //获取已经配对过的设备 Set<BluetoothDevice> pairedDevices = bTAdatper.getBondedDevices(); //将其添加到设备列表中 if (pairedDevices.size() > 0) { adapter.clear(); for (BluetoothDevice device : pairedDevices) { adapter.add(device); } } } /** * 连接蓝牙设备 */ private void connectDevice(BluetoothDevice device) { text_state.setText(getResources().getString(R.string.connecting)); try { //创建Socket BluetoothSocket socket = device.createRfcommSocketToServiceRecord(BT_UUID); //启动连接线程 connectThread = new ConnectThread(socket, true); connectThread.start(); } catch (IOException e) { e.printStackTrace(); } } @Override protected void onDestroy() { super.onDestroy(); //取消搜索 if (bTAdatper != null && bTAdatper.isDiscovering()) { bTAdatper.cancelDiscovery(); } //注销BroadcastReceiver,防止资源泄露 unregisterReceiver(mReceiver); } private final BroadcastReceiver mReceiver = new BroadcastReceiver() { @Override public void onReceive(Context context, Intent intent) { String action = intent.getAction(); if (BluetoothDevice.ACTION_FOUND.equals(action)) { BluetoothDevice device = intent.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE); //避免重复添加已经绑定过的设备 if (device.getBondState() != BluetoothDevice.BOND_BONDED) { adapter.add(device); adapter.notifyDataSetChanged(); } } else if (BluetoothAdapter.ACTION_DISCOVERY_STARTED.equals(action)) { Toast.makeText(bluetooth_lianjie.this, "开始搜索", Toast.LENGTH_SHORT).show(); } else if (BluetoothAdapter.ACTION_DISCOVERY_FINISHED.equals(action)) { Toast.makeText(bluetooth_lianjie.this, "搜索完毕", Toast.LENGTH_SHORT).show(); } } }; /** * 连接线程 */ public class ConnectThread extends Thread { private BluetoothSocket socket; private boolean activeConnect; InputStream inputStream; OutputStream outputStream; public ConnectThread(BluetoothSocket socket, boolean connect) { this.socket = socket; this.activeConnect = connect; } @Override public void run() { try { //如果是自动连接 则调用连接方法 if (activeConnect) { socket.connect(); } text_state.post(new Runnable() { @Override public void run() { text_state.setText(getResources().getString(R.string.connect_success)); lianjie_state=true; } }); inputStream = socket.getInputStream(); outputStream = socket.getOutputStream(); //byte[] buffer = new byte[BUFFER_SIZE]; //int bytes; while (true) { //读取数据 bytes = inputStream.read(buffer); if (bytes > 0) { final byte[] data = new byte[bytes]; System.arraycopy(buffer, 0, data, 0, bytes); text_msg.post(new Runnable() { @Override public void run() { //省赛补充-周泽鑫 2018/7/31 text_msg.setText(getResources().getString(R.string.get_msg) new String(data)); } }); } } } catch (IOException e) { e.printStackTrace(); text_state.post(new Runnable() { @Override public void run() { text_state.setText(getResources().getString(R.string.connect_error)); lianjie_state=false; } }); } } /** * 发送数据 * * @param msg */ public void sendMsg(final String msg) { byte[] bytes = msg.getBytes(); if (outputStream != null) { try { //发送数据 outputStream.write(bytes); text_msg.post(new Runnable() { @Override public void run() { text_msg.setText(getResources().getString(R.string.send_msgs) msg); } }); } catch (IOException e) { e.printStackTrace(); text_msg.post(new Runnable() { @Override public void run() { text_msg.setText(getResources().getString(R.string.send_msg_error) msg); } }); } } } } /** * 监听线程 */ private class ListenerThread extends Thread { private BluetoothServerSocket serverSocket; private BluetoothSocket socket; @Override public void run() { try { serverSocket = bTAdatper.listenUsingRfcommWithServiceRecord( NAME, BT_UUID); while (true) { //线程阻塞,等待别的设备连接 socket = serverSocket.accept(); text_state.post(new Runnable() { @Override public void run() { text_state.setText(getResources().getString(R.string.connecting)); } }); connectThread = new ConnectThread(socket, false); connectThread.start(); } } catch (IOException e) { e.printStackTrace(); } } } private static String returnResultMultiple(String str) { String string = ""; if (str.equals("")) { return ""; } for (int i = 0; i < str.length(); i ) { char ch = str.charAt(i); if ((ch>=65&&ch<=122)||(ch>=48&&ch<=57)){ string = string ch; } } return string; } ////省赛补充-周泽鑫 2018/7/31 boolean shifouhanyouwenzi(String str) { //判断字符串第一个字符是不是为文字 if (str.equals("")) { return false; } char ch = str.charAt(0); if ((ch>=65&&ch<=122)||(ch>=48&&ch<=57)) { return false; } else return true; } ////省赛补充-周泽鑫 2018/7/31 private List<String> getData(String str){ String string = ""; List<String> data = new ArrayList<String>(); for(int i=0; i < str.length()/20;i=i 20) { for (int j = i; j < i 20; j ) { //读取第一个开门记录,假如返回的字符长度为20 char ch = str.charAt(i); if ((ch >= 65 && ch <= 122) || (ch >= 48 && ch <= 57)) { string = string ch; } } data.add(string); } return data; } private String getPhoneNumber(){ TelephonyManager mTelephonyMgr; mTelephonyMgr = (TelephonyManager) getSystemService(Context.TELEPHONY_SERVICE); return mTelephonyMgr.getLine1Number(); } }
好例子网口号:伸出你的我的手 — 分享!
小贴士
感谢您为本站写下的评论,您的评论对其它用户来说具有重要的参考价值,所以请认真填写。
- 类似“顶”、“沙发”之类没有营养的文字,对勤劳贡献的楼主来说是令人沮丧的反馈信息。
- 相信您也不想看到一排文字/表情墙,所以请不要反馈意义不大的重复字符,也请尽量不要纯表情的回复。
- 提问之前请再仔细看一遍楼主的说明,或许是您遗漏了。
- 请勿到处挖坑绊人、招贴广告。既占空间让人厌烦,又没人会搭理,于人于己都无利。
关于好例子网
本站旨在为广大IT学习爱好者提供一个非营利性互相学习交流分享平台。本站所有资源都可以被免费获取学习研究。本站资源来自网友分享,对搜索内容的合法性不具有预见性、识别性、控制性,仅供学习研究,请务必在下载后24小时内给予删除,不得用于其他任何用途,否则后果自负。基于互联网的特殊性,平台无法对用户传输的作品、信息、内容的权属或合法性、安全性、合规性、真实性、科学性、完整权、有效性等进行实质审查;无论平台是否已进行审查,用户均应自行承担因其传输的作品、信息、内容而可能或已经产生的侵权或权属纠纷等法律责任。本站所有资源不代表本站的观点或立场,基于网友分享,根据中国法律《信息网络传播权保护条例》第二十二与二十三条之规定,若资源存在侵权或相关问题请联系本站客服人员,点此联系我们。关于更多版权及免责申明参见 版权及免责申明
网友评论
我要评论