首页

android 蓝牙聊天通信Demo源码(发消息、开启、关闭蓝牙)

java

2020-7-30

这是一个蓝牙连接通信的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

	}
}
资源下载此资源下载价格为2D币(VIP免费),请先
资源文件列表
BluetoothConn/.classpath , 475
BluetoothConn/.project , 849
BluetoothConn/.settings/org.eclipse.jdt.core.prefs , 177
BluetoothConn/AndroidManifest.xml , 1039
BluetoothConn/bin/AndroidManifest.xml , 1039
BluetoothConn/bin/BluetoothConn.apk , 341395
BluetoothConn/bin/classes/com/example/bluetoothconn/BuildConfig.class , 359
BluetoothConn/bin/classes/com/example/bluetoothconn/ChatActivity$1.class , 1477
BluetoothConn/bin/classes/com/example/bluetoothconn/ChatActivity$2.class , 1976
BluetoothConn/bin/classes/com/example/bluetoothconn/ChatActivity$3.class , 1472
BluetoothConn/bin/classes/com/example/bluetoothconn/ChatActivity$4.class , 2049
BluetoothConn/bin/classes/com/example/bluetoothconn/ChatActivity$5.class , 1742
BluetoothConn/bin/classes/com/example/bluetoothconn/ChatActivity$clientThread.class , 2822
BluetoothConn/bin/classes/com/example/bluetoothconn/ChatActivity$readThread.class , 1897
BluetoothConn/bin/classes/com/example/bluetoothconn/ChatActivity$serverThread.class , 2732
BluetoothConn/bin/classes/com/example/bluetoothconn/ChatActivity.class , 8561
BluetoothConn/bin/classes/com/example/bluetoothconn/ListAdapter$ViewHolder.class , 724
BluetoothConn/bin/classes/com/example/bluetoothconn/ListAdapter.class , 2599
BluetoothConn/bin/classes/com/example/bluetoothconn/MainActivity$1$1.class , 2396
BluetoothConn/bin/classes/com/example/bluetoothconn/MainActivity$1$2.class , 1041
BluetoothConn/bin/classes/com/example/bluetoothconn/MainActivity$1.class , 2777
BluetoothConn/bin/classes/com/example/bluetoothconn/MainActivity$2.class , 2698
BluetoothConn/bin/classes/com/example/bluetoothconn/MainActivity$3.class , 1430
BluetoothConn/bin/classes/com/example/bluetoothconn/MainActivity$4.class , 1432
BluetoothConn/bin/classes/com/example/bluetoothconn/MainActivity$5.class , 1804
BluetoothConn/bin/classes/com/example/bluetoothconn/MainActivity$6.class , 3314
BluetoothConn/bin/classes/com/example/bluetoothconn/MainActivity$ServerOrCilent.class , 1304
BluetoothConn/bin/classes/com/example/bluetoothconn/MainActivity.class , 5667
BluetoothConn/bin/classes/com/example/bluetoothconn/MyListItem.class , 467
BluetoothConn/bin/classes/com/example/bluetoothconn/R$attr.class , 361
BluetoothConn/bin/classes/com/example/bluetoothconn/R$dimen.class , 482
BluetoothConn/bin/classes/com/example/bluetoothconn/R$drawable.class , 525
BluetoothConn/bin/classes/com/example/bluetoothconn/R$id.class , 728
BluetoothConn/bin/classes/com/example/bluetoothconn/R$layout.class , 485
BluetoothConn/bin/classes/com/example/bluetoothconn/R$menu.class , 409
BluetoothConn/bin/classes/com/example/bluetoothconn/R$string.class , 493
BluetoothConn/bin/classes/com/example/bluetoothconn/R$style.class , 452
BluetoothConn/bin/classes/com/example/bluetoothconn/R.class , 743
BluetoothConn/bin/classes.dex , 841008
BluetoothConn/bin/dexedLibs/android-support-v4-49d3d5a270b7b0fbe142628ae79e8c8d.jar , 273766
BluetoothConn/bin/dexedLibs/android-support-v4-a0903e2be8c4461ab182b978ed93a5e1.jar , 273788
BluetoothConn/bin/jarlist.cache , 120
BluetoothConn/bin/res/crunch/drawable-hdpi/ic_launcher.png , 5964
BluetoothConn/bin/res/crunch/drawable-hdpi/msgbox_rec.9.png , 1903
BluetoothConn/bin/res/crunch/drawable-hdpi/msgbox_send.9.png , 1943
BluetoothConn/bin/res/crunch/drawable-mdpi/ic_launcher.png , 3112
BluetoothConn/bin/res/crunch/drawable-xhdpi/ic_launcher.png , 9355
BluetoothConn/bin/res/crunch/drawable-xxhdpi/ic_launcher.png , 17889
BluetoothConn/bin/resources.ap_ , 55055
BluetoothConn/gen/com/example/bluetoothconn/BuildConfig.java , 167
BluetoothConn/gen/com/example/bluetoothconn/R.java , 3408
BluetoothConn/ic_launcher-web.png , 51394
BluetoothConn/libs/android-support-v4.jar , 758727
BluetoothConn/lint.xml , 200
BluetoothConn/proguard-project.txt , 781
BluetoothConn/project.properties , 563
BluetoothConn/res/drawable-hdpi/icon.jpg , 7245
BluetoothConn/res/drawable-hdpi/ic_launcher.png , 7658
BluetoothConn/res/drawable-hdpi/msgbox_rec.9.png , 1836
BluetoothConn/res/drawable-hdpi/msgbox_send.9.png , 1553
BluetoothConn/res/drawable-mdpi/ic_launcher.png , 3777
BluetoothConn/res/drawable-xhdpi/ic_launcher.png , 12516
BluetoothConn/res/drawable-xxhdpi/ic_launcher.png , 24777
BluetoothConn/res/layout/activity_main.xml , 1862
BluetoothConn/res/layout/chat.xml , 1571
BluetoothConn/res/layout/list_item.xml , 682
BluetoothConn/res/menu/main.xml , 375
BluetoothConn/res/values/dimens.xml , 220
BluetoothConn/res/values/strings.xml , 229
BluetoothConn/res/values/styles.xml , 697
BluetoothConn/res/values-v11/styles.xml , 334
BluetoothConn/res/values-v14/styles.xml , 391
BluetoothConn/res/values-w820dp/dimens.xml , 381
BluetoothConn/src/com/example/bluetoothconn/ChatActivity.java , 9397
BluetoothConn/src/com/example/bluetoothconn/ListAdapter.java , 1720
BluetoothConn/src/com/example/bluetoothconn/MainActivity.java , 8595
BluetoothConn/src/com/example/bluetoothconn/MyListItem.java , 194
没有账号? 忘记密码?

社交账号快速登录