实例介绍
【实例简介】
这是一个蓝牙连接通信的demo
【实例截图】
【核心代码】
package com.example.bluetoothconn; import java.util.ArrayList; import java.util.Set; import android.app.Activity; import android.app.AlertDialog; import android.bluetooth.BluetoothAdapter; import android.bluetooth.BluetoothDevice; import android.content.BroadcastReceiver; import android.content.Context; import android.content.DialogInterface; import android.content.Intent; import android.content.IntentFilter; import android.os.Bundle; import android.view.View; import android.view.View.OnClickListener; import android.widget.AdapterView; import android.widget.AdapterView.OnItemClickListener; import android.widget.Button; import android.widget.ListView; import android.widget.Toast; public class MainActivity extends Activity { static enum ServerOrCilent { NONE, SERVICE, CLIENT }; static String BlueToothAddress = "null"; static ServerOrCilent serviceOrCilent = ServerOrCilent.NONE; static boolean isOpen = false; private ListView mListView; private ArrayList<MyListItem> list; private Button seachButton, serviceButton, open, close; ListAdapter mAdapter; Context mContext; // 取得默认的蓝牙适配器 private BluetoothAdapter mBtAdapter = BluetoothAdapter.getDefaultAdapter(); boolean isBTOpen; @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); getActionBar().setTitle("扫描到的设备"); setContentView(R.layout.activity_main); mContext = this; init(); } private void init() { list = new ArrayList<MyListItem>(); mAdapter = new ListAdapter(this, list); mListView = (ListView) findViewById(android.R.id.list); mListView.setAdapter(mAdapter); mListView.setFastScrollEnabled(true); mListView.setOnItemClickListener(mDeviceClickListener); // Register for broadcasts when a device is discovered IntentFilter discoveryFilter = new IntentFilter( BluetoothDevice.ACTION_FOUND); this.registerReceiver(mReceiver, discoveryFilter); // Get a set of currently paired devices Set<BluetoothDevice> pairedDevices = mBtAdapter.getBondedDevices(); // If there are paired devices, add each one to the ArrayAdapter if (pairedDevices.size() > 0) { for (BluetoothDevice device : pairedDevices) { list.add(new MyListItem(device.getName() "\n" device.getAddress(), true)); mAdapter.notifyDataSetChanged(); mListView.setSelection(list.size() - 1); } } else { list.add(new MyListItem("没有设备已经配对", true)); mAdapter.notifyDataSetChanged(); mListView.setSelection(list.size() - 1); } open = (Button) findViewById(R.id.open); open.setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { // TODO Auto-generated method stub isBTOpen = mBtAdapter.isEnabled(); if (!isBTOpen) { boolean open = mBtAdapter.enable(); if (open) { Toast.makeText(MainActivity.this, "蓝牙已打开", 1000).show(); } else { Toast.makeText(MainActivity.this, "打开蓝牙失败", 1000) .show(); } } else { Toast.makeText(MainActivity.this, "蓝牙已经处于开启状态,不需要再打开了", 1000).show(); } } }); close = (Button) findViewById(R.id.close); close.setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { // TODO Auto-generated method stub isBTOpen = mBtAdapter.isEnabled(); if (isBTOpen) { boolean close = mBtAdapter.disable(); if (close) { Toast.makeText(MainActivity.this, "蓝牙已关闭", 1000).show(); } else { Toast.makeText(MainActivity.this, "关闭蓝牙失败", 1000) .show(); } } else { Toast.makeText(MainActivity.this, "蓝牙已经处于关闭状态,不需要再关闭了", 1000).show(); } } }); serviceButton = (Button) findViewById(R.id.startService); serviceButton.setOnClickListener(new OnClickListener() { @Override public void onClick(View arg0) { // TODO Auto-generated method stub isBTOpen = mBtAdapter.isEnabled(); if (isBTOpen) { serviceOrCilent = ServerOrCilent.SERVICE; Intent intent = new Intent(); intent.setClass(MainActivity.this, ChatActivity.class); startActivity(intent); } else { Toast.makeText(MainActivity.this, "蓝牙未开启,无法开启服务,请先开启蓝牙再开启服务。", 1000).show(); } } }); seachButton = (Button) findViewById(R.id.startSearch); seachButton.setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { // TODO Auto-generated method stub isBTOpen = mBtAdapter.isEnabled(); if (isBTOpen) { if (mBtAdapter.isDiscovering()) { mBtAdapter.cancelDiscovery(); seachButton.setText("重新搜索"); } else { list.clear(); mAdapter.notifyDataSetChanged(); Set<BluetoothDevice> pairedDevices = mBtAdapter .getBondedDevices(); if (pairedDevices.size() > 0) { for (BluetoothDevice device : pairedDevices) { list.add(new MyListItem(device.getName() "\n" device.getAddress(), true)); mAdapter.notifyDataSetChanged(); mListView.setSelection(list.size() - 1); } } else { list.add(new MyListItem( "No devices have been paired", true)); mAdapter.notifyDataSetChanged(); mListView.setSelection(list.size() - 1); } // 开始搜索 mBtAdapter.startDiscovery(); seachButton.setText("停止搜索"); } } else { Toast.makeText(MainActivity.this, "蓝牙处于关闭状态,请开启蓝牙再进行搜索", 1000).show(); } } }); } private OnItemClickListener mDeviceClickListener = new OnItemClickListener() { public void onItemClick(AdapterView<?> av, View v, int arg2, long arg3) { MyListItem item = list.get(arg2); String info = item.message; String address = info.substring(info.length() - 17); BlueToothAddress = address; AlertDialog.Builder StopDialog = new AlertDialog.Builder(mContext); StopDialog.setTitle("连接");// 标题 StopDialog.setMessage(item.message); StopDialog.setPositiveButton("连接", new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int which) { // TODO Auto-generated method stub isBTOpen = mBtAdapter.isEnabled(); if (isBTOpen) { mBtAdapter.cancelDiscovery(); seachButton.setText("重新搜索"); serviceOrCilent = ServerOrCilent.CLIENT; Intent intent = new Intent(); intent.setClass(MainActivity.this, ChatActivity.class); startActivity(intent); } else { Toast.makeText(MainActivity.this, "蓝牙未打开,无法连接至服务端,请先打开蓝牙再进行连接", 1000) .show(); } } }); StopDialog.setNegativeButton("取消", new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int which) { BlueToothAddress = null; } }); StopDialog.show(); } }; private final 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) { list.add(new MyListItem(device.getName() "\n" device.getAddress(), false)); mAdapter.notifyDataSetChanged(); mListView.setSelection(list.size() - 1); } // When discovery is finished, change the Activity title } else if (BluetoothAdapter.ACTION_DISCOVERY_FINISHED .equals(action)) { setProgressBarIndeterminateVisibility(false); if (mListView.getCount() == 0) { list.add(new MyListItem("没有发现蓝牙设备", false)); mAdapter.notifyDataSetChanged(); mListView.setSelection(list.size() - 1); } seachButton.setText("重新搜索"); } } }; @Override protected void onDestroy() { super.onDestroy(); // Make sure we're not doing discovery anymore if (mBtAdapter != null) { mBtAdapter.cancelDiscovery(); } // Unregister broadcast listeners } }
小贴士
感谢您为本站写下的评论,您的评论对其它用户来说具有重要的参考价值,所以请认真填写。
- 类似“顶”、“沙发”之类没有营养的文字,对勤劳贡献的楼主来说是令人沮丧的反馈信息。
- 相信您也不想看到一排文字/表情墙,所以请不要反馈意义不大的重复字符,也请尽量不要纯表情的回复。
- 提问之前请再仔细看一遍楼主的说明,或许是您遗漏了。
- 请勿到处挖坑绊人、招贴广告。既占空间让人厌烦,又没人会搭理,于人于己都无利。
关于好例子网
本站旨在为广大IT学习爱好者提供一个非营利性互相学习交流分享平台。本站所有资源都可以被免费获取学习研究。本站资源来自网友分享,对搜索内容的合法性不具有预见性、识别性、控制性,仅供学习研究,请务必在下载后24小时内给予删除,不得用于其他任何用途,否则后果自负。基于互联网的特殊性,平台无法对用户传输的作品、信息、内容的权属或合法性、安全性、合规性、真实性、科学性、完整权、有效性等进行实质审查;无论平台是否已进行审查,用户均应自行承担因其传输的作品、信息、内容而可能或已经产生的侵权或权属纠纷等法律责任。本站所有资源不代表本站的观点或立场,基于网友分享,根据中国法律《信息网络传播权保护条例》第二十二与二十三条之规定,若资源存在侵权或相关问题请联系本站客服人员,点此联系我们。关于更多版权及免责申明参见 版权及免责申明
网友评论
我要评论