第9章实验    Android近距离通信

一、实验目的

  1. 掌握手机WiFi的使用和Android对WiFi的支持
  2. 掌握手机Bluetooth的使用和Android对Bluetooth的支持
  3. 掌握手机NFC的使用和Android对NFC的支持

二、项目及其源代码

主控模块APP

(一)example9_1模块(WiFi基本操作)

1. 清单文件注册权限

<!--下面2个是普通权限,只需要在清单文件里注册,不需要在程序里动态申请-->
<uses-permission android:name="android.permission.CHANGE_WIFI_STATE" />
<uses-permission android:name="android.permission.ACCESS_WIFI_STATE" />

<!--搜索WiFi,需要定位权限,它是危险权限,在此声明外,还需要在程序里动态申请-->
<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION"/>

2. 布局 activity_main.xml

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:id="@+id/mScrollView"
    android:layout_width="fill_parent"
    android:layout_height="wrap_content"
    android:scrollbars="vertical">

    <LinearLayout
        android:layout_width="fill_parent"
        android:layout_height="fill_parent"
        android:orientation="vertical">

        <LinearLayout
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:orientation="horizontal">

            <Button
                android:id="@+id/btn_check"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:text="检查WiFi" />

            <Button
                android:id="@+id/btn_open"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:text="打开WiFi" />

            <Button
                android:id="@+id/btn_close"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:text="关闭WiFi" />

            <Button
                android:id="@+id/btn_search"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:text="扫描WiFi" />
        </LinearLayout>

        <!--ScrollView是中间容器控件,当它包含的内容超过屏幕的容量时,会产生卷动效果-->
        <ScrollView
            android:layout_width="wrap_content"
            android:layout_height="wrap_content">
            <TextView
                android:id="@+id/textView"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:text="wifi列表"
                android:visibility="gone" />
        </ScrollView>
    </LinearLayout>
</LinearLayout>

2. 界面程序MainActivity.java

/*
    本程序演示了 WiFi操作
    WiFi权限是普通权限,对应于WiFI的打开、关闭和状态读取。
    WiFi扫描,需要定位权限,因此,除了在清单文件里注册外,还需要在程序里动态注册
 */
public class MainActivity extends AppCompatActivity implements  OnClickListener{

    WifiManager wifiManager;
    WifiInfo wifiInfo;
    ScanResult scanResult;
    List<ScanResult> WifiList;
    Button btn_check, btn_open, btn_close, btn_search;
    TextView textView;

    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT); //设定竖屏,不会切换成横屏
        setContentView(R.layout.activity_main);

        if (ContextCompat.checkSelfPermission(this, Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
            ActivityCompat.requestPermissions(this,new String[]{Manifest.permission.ACCESS_COARSE_LOCATION}, 1);
        }
        fun();
    }
    private void fun() {
        btn_check =  findViewById(R.id.btn_check);btn_check.setOnClickListener(this);
        btn_open = findViewById(R.id.btn_open);btn_open.setOnClickListener(this);
        btn_close = findViewById(R.id.btn_close);btn_close.setOnClickListener(this);
        btn_search =  findViewById(R.id.btn_search);btn_search.setOnClickListener(this);
        textView =  findViewById(R.id.textView);
        //创建WiFi管理器对象
        wifiManager = (WifiManager) getApplicationContext().getSystemService(Context.WIFI_SERVICE);
    }
    @Override
    public void onClick(View v) {  //内部接口View.OnClickListener要实现的方法
        int ItemId = v.getId();//获取控件的id值
        switch (ItemId) {
            case R.id.btn_check:
                textView.setVisibility(View.INVISIBLE); //隐藏先前扫描的结果
                Toast.makeText(MainActivity.this, "当前WiFi状态为:" + getWiFiState(), Toast.LENGTH_LONG).show();
                Log.i("wifiTest", "wifi state --->" + wifiManager.getWifiState());
                break;
            case R.id.btn_open:
                textView.setVisibility(View.INVISIBLE);
                wifiManager.setWifiEnabled(true);  //打开WiFi
                Toast.makeText(MainActivity.this, "当前WiFi状态为:" + getWiFiState(), Toast.LENGTH_LONG).show();
                Log.i("wifiTest", "wifi state --->" + wifiManager.getWifiState());
                break;
            case R.id.btn_close:
                textView.setVisibility(View.INVISIBLE);
                wifiManager.setWifiEnabled(false);   //关闭WiFi
                //关闭WiFi存在延时,所以需要休眠,否则,出现逻辑错误
                try {
                    Thread.sleep(1000);  //主线程休眠1秒
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
                Log.i("wifiTest", "wifi state --->" + wifiManager.getWifiState());
                Toast.makeText(MainActivity.this, "当前WiFi状态为:" + getWiFiState(), Toast.LENGTH_LONG).show();
                break;
            case R.id.btn_search:
                wifiManager.startScan();
                WifiList = wifiManager.getScanResults();
                wifiInfo = wifiManager.getConnectionInfo();
                StringBuffer stringBuffer = new StringBuffer();
                stringBuffer
                        .append("Wifi名").append("             ")
                        .append("Wifi地址").append("                   ")
                        .append("Wifi频率").append("     ")
                        .append("Wifi信号\n");
                if (WifiList != null) {
                    for (int i = 0; i < WifiList.size(); i++) {
                        scanResult = WifiList.get(i);
                        stringBuffer
                                .append(scanResult.SSID).append("  ")
                                .append(scanResult.BSSID).append("  ")
                                .append(scanResult.frequency).append(" ")
                                .append(scanResult.level).append("\n");
                    }
                    stringBuffer
                            .append("-----------------------------------------------\n")
                            .append("本机使用的WiFi的相关指标:\n")
                            .append("BSSID:").append(wifiInfo.getBSSID()).append("\n")
                            .append("Hidden SSID:").append(wifiInfo.getHiddenSSID()).append("\n")
                            .append("IP Address:").append(wifiInfo.getIpAddress()).append("\n")
                            .append("Link Speed:").append(wifiInfo.getLinkSpeed()).append("\n")
                            .append("MAC Address:").append(wifiInfo.getMacAddress()).append("\n")
                            .append("Network ID:").append(wifiInfo.getNetworkId()).append("\n")
                            .append("RSSI:").append(wifiInfo.getRssi()).append("\n")
                            .append("SSID:").append(wifiInfo.getSSID()).append("\n");
                    stringBuffer
                            .append("-----------------------------------------------\n")
                            .append("本机使用的WiFi的信息:\n")
                            .append(wifiInfo.toString());
                    textView.setVisibility(View.VISIBLE);
                    textView.setText(stringBuffer.toString());
                }
        }
    }
    public String getWiFiState(){   //获取WiFi状态
        String temp=null;
        switch (wifiManager.getWifiState()) {
            case 0:
                temp="Wifi正在关闭...";
                break;
            case 1:
                temp="Wifi已经关闭";
                break;
            case 2:
                temp="Wifi正在打开...";
                break;
            case 3:
                temp="Wifi已经打开";
                break;
            default:
                break;
        }
        return temp;
    }
    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        if(grantResults.length>0){
            if(grantResults[0]!=PackageManager.PERMISSION_GRANTED){
                Toast.makeText(this, "未授权,WiFi搜索功能将不可用!", Toast.LENGTH_SHORT).show();
            }else{
                fun();
            }
        }
    }
}

【Return Top】

(二)example9_2模块(Bluetooth聊天)

1. 清单文件注册权限

<!--下面2个是普通权限,只需要在清单文件里注册,不需要在程序里动态申请-->
<uses-permission android:name="android.permission.BLUETOOTH_ADMIN" />
<uses-permission android:name="android.permission.BLUETOOTH" />

2. 在文件res/values/strings.xml里,添加程序运行过程中的状态描述文本及配色代码等,其代码如下:

<?xml version="1.0" encoding="utf-8"?>
<resources>
    <string name="app_name">蓝牙Demo</string> 
    <string name="send">发送</string>
    <string name="not_connected">你没有链接一个设备</string>
    <string name="bt_not_enabled_leaving">蓝牙不可用,离开聊天室</string>
    <string name="title_connecting">链接中...</string>
    <string name="title_connected_to">连接到:</string>
    <string name="title_not_connected">无链接</string> 
    <string name="scanning">蓝牙设备搜索中...</string>
    <string name="select_device">选择一个好友链接</string>
    <string name="none_paired">没有配对好友</string>
    <string name="none_found">附近没有发现好友</string>
    <string name="title_paired_devices">已配对好友</string>
    <string name="title_other_devices">其它可连接好友</string>
    <string name="button_scan">搜索好友</string>
    <string name="connect">我的好友</string>
    <string name="discoverable">设置在线</string>
    <string name="back">退出</string>
    <string name="startVideo">开始聊天</string>
    <string name="stopVideo">结束聊天</string>  
</resources>

3. 在默认的主布局文件activity_main.xml里,添加1个Toolbar控件,其内包含2个水平的TextView控件;在Toolbar控件的下方添加1个ListView控件,用于显示聊天内容;最后在ListView控件的下方添加水平放置的1个EditText控件和一个Button控件。使用垂直线性布局并嵌套水平线性布局实现的代码如下:

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="vertical"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:background="@color/bg01">

    <!--新版Android支持的Toolbar,对标题栏布局-->
    <android.support.v7.widget.Toolbar
        android:id="@+id/toolbar"
        android:layout_width="match_parent"
        android:layout_height="wrap_content">
        <LinearLayout
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            android:orientation="horizontal">
            <TextView
                android:id="@+id/title_left_text"
                style="?android:attr/windowTitleStyle"
                android:layout_width="0dp"
                android:layout_height="match_parent"
                android:layout_alignParentLeft="true"
                android:layout_weight="1"
                android:gravity="left"
                android:ellipsize="end"
                android:singleLine="true" />
            <TextView
                android:id="@+id/title_right_text"
                android:layout_width="0dp"
                android:layout_height="match_parent"
                android:layout_alignParentRight="true"
                android:layout_weight="1"
                android:ellipsize="end"
                android:gravity="right"
                android:singleLine="true"
                android:textColor="#fff" />
        </LinearLayout>
    </android.support.v7.widget.Toolbar>

    <ListView android:id="@+id/in"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:stackFromBottom="true"
        android:transcriptMode="alwaysScroll"
        android:layout_weight="1" />
    <LinearLayout
        android:orientation="horizontal"
        android:layout_width="match_parent"
        android:layout_height="wrap_content" >
        <EditText android:id="@+id/edit_text_out"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_weight="1"
            android:layout_gravity="bottom" />
        <Button android:id="@+id/button_send"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="@string/send"/>
    </LinearLayout>
</LinearLayout>

4. 编写用于蓝牙会话的服务组件ChatService,本质上是一个工具类,其文件代码如下:

/*
    本程序ChatService是蓝牙会话的服务程序
    定义了3个内部类:AcceptThread(接受新连接)、ConnectThread(发出连接)和ConnectedThread (已连接)
*/
public class ChatService {
    //本应用的主Activity组件名称
    private static final String NAME = "BluetoothChat";
    // UUID:通用唯一识别码,是一个128位长的数字,一般用十六进制表示
    //算法的核心思想是结合机器的网卡、当地时间、一个随机数来生成
    //在创建蓝牙连接
    private static final UUID MY_UUID = UUID.fromString("fa87c0d0-afac-11de-8a39-0800200c9a66");
    private final BluetoothAdapter mAdapter;
    private final Handler mHandler;
    private AcceptThread mAcceptThread;
    private ConnectThread mConnectThread;
    private ConnectedThread mConnectedThread;
    private int mState;
    public static final int STATE_NONE = 0;
    public static final int STATE_LISTEN = 1;
    public static final int STATE_CONNECTING = 2;
    public static final int STATE_CONNECTED = 3;

    //构造方法,接收UI主线程传递的对象
    public ChatService(Context context, Handler handler) {
        //构造方法完成蓝牙对象的创建
        mAdapter = BluetoothAdapter.getDefaultAdapter();
        mState = STATE_NONE;
        mHandler = handler;
    }

    private synchronized void setState(int state) {
        mState = state;
        mHandler.obtainMessage(BluetoothChat.MESSAGE_STATE_CHANGE, state, -1).sendToTarget();
    }

    public synchronized int getState() {
        return mState;
    }

    public synchronized void start() {
        if (mConnectThread != null) {
            mConnectThread.cancel();
            mConnectThread = null;
        }
        if (mConnectedThread != null) {
            mConnectedThread.cancel();
            mConnectedThread = null;
        }
        if (mAcceptThread == null) {
            mAcceptThread = new AcceptThread();
            mAcceptThread.start();
        }
        setState(STATE_LISTEN);
    }

    //取消 CONNECTING 和 CONNECTED 状态下的相关线程,然后运行新的 mConnectThread 线程
    public synchronized void connect(BluetoothDevice device) {
        if (mState == STATE_CONNECTING) {
            if (mConnectThread != null) {
                mConnectThread.cancel();
                mConnectThread = null;
            }
        }
        if (mConnectedThread != null) {
            mConnectedThread.cancel();
            mConnectedThread = null;
        }
        mConnectThread = new ConnectThread(device);
        mConnectThread.start();
        setState(STATE_CONNECTING);
    }

    /*
        开启一个 ConnectedThread 来管理对应的当前连接。之前先取消任意现存的 mConnectThread 、
        mConnectedThread 、 mAcceptThread 线程,然后开启新 mConnectedThread ,传入当前刚刚接受的
        socket 连接。最后通过 Handler来通知UI连接
     */
    public synchronized void connected(BluetoothSocket socket, BluetoothDevice device) {
        if (mConnectThread != null) {
            mConnectThread.cancel();
            mConnectThread = null;
        }
        if (mConnectedThread != null) {
            mConnectedThread.cancel();
            mConnectedThread = null;
        }
        if (mAcceptThread != null) {
            mAcceptThread.cancel();
            mAcceptThread = null;
        }
        mConnectedThread = new ConnectedThread(socket);
        mConnectedThread.start();
        Message msg = mHandler.obtainMessage(BluetoothChat.MESSAGE_DEVICE_NAME);
        Bundle bundle = new Bundle();
        bundle.putString(BluetoothChat.DEVICE_NAME, device.getName());
        msg.setData(bundle);
        mHandler.sendMessage(msg);
        setState(STATE_CONNECTED);
    }

    // 停止所有相关线程,设当前状态为 NONE
    public synchronized void stop() {
        if (mConnectThread != null) {
            mConnectThread.cancel();
            mConnectThread = null;
        }
        if (mConnectedThread != null) {
            mConnectedThread.cancel();
            mConnectedThread = null;
        }
        if (mAcceptThread != null) {
            mAcceptThread.cancel();
            mAcceptThread = null;
        }
        setState(STATE_NONE);
    }

    // 在 STATE_CONNECTED 状态下,调用 mConnectedThread 里的 write 方法,写入 byte
    public void write(byte[] out) {
        ConnectedThread r;
        synchronized (this) {
            if (mState != STATE_CONNECTED)
                return;
            r = mConnectedThread;
        }
        r.write(out);
    }

    // 连接失败的时候处理,通知 ui ,并设为 STATE_LISTEN 状态
    private void connectionFailed() {
        setState(STATE_LISTEN);
        Message msg = mHandler.obtainMessage(BluetoothChat.MESSAGE_TOAST);
        Bundle bundle = new Bundle();
        bundle.putString(BluetoothChat.TOAST, "链接不到设备");
        msg.setData(bundle);
        mHandler.sendMessage(msg);
    }

    // 当连接失去的时候,设为 STATE_LISTEN 状态并通知 ui
    private void connectionLost() {
        setState(STATE_LISTEN);
        Message msg = mHandler.obtainMessage(BluetoothChat.MESSAGE_TOAST);
        Bundle bundle = new Bundle();
        bundle.putString(BluetoothChat.TOAST, "设备链接中断");
        msg.setData(bundle);
        mHandler.sendMessage(msg);
    }

    // 创建监听线程,准备接受新连接。使用阻塞方式,调用 BluetoothServerSocket.accept()
    private class AcceptThread extends Thread {
        private final BluetoothServerSocket mmServerSocket;

        public AcceptThread() {
            BluetoothServerSocket tmp = null;
            try {
                //使用射频端口(RF comm)监听
                tmp = mAdapter.listenUsingRfcommWithServiceRecord(NAME, MY_UUID);
            } catch (IOException e) {
            }
            mmServerSocket = tmp;
        }

        @Override
        public void run() {
            setName("AcceptThread");
            BluetoothSocket socket = null;
            while (mState != STATE_CONNECTED) {
                try {
                    socket = mmServerSocket.accept();
                } catch (IOException e) {
                    break;
                }
                if (socket != null) {
                    synchronized (ChatService.this) {
                        switch (mState) {
                            case STATE_LISTEN:
                            case STATE_CONNECTING:
                                connected(socket, socket.getRemoteDevice());
                                break;
                            case STATE_NONE:
                            case STATE_CONNECTED:
                                try {
                                    socket.close();
                                } catch (IOException e) {
                                    e.printStackTrace();
                                }
                                break;
                        }
                    }
                }
            }
        }

        public void cancel() {
            try {
                mmServerSocket.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

    /*
        连接线程,专门用来对外发出连接对方蓝牙的请求和处理流程。
        构造函数里通过 BluetoothDevice.createRfcommSocketToServiceRecord() ,
        从待连接的 device 产生 BluetoothSocket. 然后在 run 方法中 connect ,
        成功后调用 BluetoothChatSevice 的 connected() 方法。定义 cancel() 在关闭线程时能够关闭相关socket 。
     */
    private class ConnectThread extends Thread {
        private final BluetoothSocket mmSocket;
        private final BluetoothDevice mmDevice;

        public ConnectThread(BluetoothDevice device) {
            mmDevice = device;
            BluetoothSocket tmp = null;
            try {
                tmp = device.createRfcommSocketToServiceRecord(MY_UUID);
            } catch (IOException e) {
                e.printStackTrace();
            }
            mmSocket = tmp;
        }

        @Override
        public void run() {
            setName("ConnectThread");
            mAdapter.cancelDiscovery();
            try {
                mmSocket.connect();
            } catch (IOException e) {
                connectionFailed();
                try {
                    mmSocket.close();
                } catch (IOException e2) {
                    e.printStackTrace();
                }
                ChatService.this.start();
                return;
            }
            synchronized (ChatService.this) {
                mConnectThread = null;
            }
            connected(mmSocket, mmDevice);
        }

        public void cancel() {
            try {
                mmSocket.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

    /*
        双方蓝牙连接后一直运行的线程;构造函数中设置输入输出流。
        run()方法中使用阻塞模式的 InputStream.read()循环读取输入流,然后发送到 UI 线程中更新聊天消息。
        本线程也提供了 write() 将聊天消息写入输出流传输至对方,传输成功后回写入 UI 线程。最后使用cancel()关闭连接的 socket
     */
    private class ConnectedThread extends Thread {
        private final BluetoothSocket mmSocket;
        private final InputStream mmInStream;
        private final OutputStream mmOutStream;

        public ConnectedThread(BluetoothSocket socket) {
            mmSocket = socket;
            InputStream tmpIn = null;
            OutputStream tmpOut = null;
            try {
                tmpIn = socket.getInputStream();
                tmpOut = socket.getOutputStream();
            } catch (IOException e) {
                e.printStackTrace();
            }
            mmInStream = tmpIn;
            mmOutStream = tmpOut;
        }

        @Override
        public void run() {
            byte[] buffer = new byte[1024];
            int bytes;
            while (true) {
                try {
                    bytes = mmInStream.read(buffer);
                    mHandler.obtainMessage(BluetoothChat.MESSAGE_READ, bytes, -1, buffer).sendToTarget();
                } catch (IOException e) {
                    connectionLost();
                    break;
                }
            }
        }

        public void write(byte[] buffer) {
            try {
                mmOutStream.write(buffer);
                mHandler.obtainMessage(BluetoothChat.MESSAGE_WRITE, -1, -1, buffer).sendToTarget();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }

        public void cancel() {
            try {
                mmSocket.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
}

5. 分别建立供主Activity使用的菜单文件res/menu/optionmenu.xml、选择好友(即已经配对过的蓝牙设备)的界面布局文件devicelist.xml。

6. 新建Activity组件DeviceList,实现选取与之会话的蓝牙设备,其文件代码如下:

    /*
        本程序供菜单项主界面的选项菜单“我的友好”调用,用于:
        (1)显示已配对的好友列表;
        (2)搜索可配对的好友进行配对
        (3)新选择并配对的蓝牙设备将刷新好友列表
        注意:发现新的蓝牙设备并请求配对时,需要对应接受
        关键技术:动态注册一个广播接收者,处理蓝牙设备扫描的结果
    */
    public class DeviceList extends AppCompatActivity{
        private BluetoothAdapter mBtAdapter;
        private ArrayAdapter<String> mPairedDevicesArrayAdapter;
        private ArrayAdapter<String> mNewDevicesArrayAdapter;
        public static String EXTRA_DEVICE_ADDRESS = "device_address";  //Mac地址
        //定义广播接收者,用于处理扫描蓝牙设备后的结果
        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) {
                        mNewDevicesArrayAdapter.add(device.getName() + "\n" + device.getAddress());
                    }
                } else if (BluetoothAdapter.ACTION_DISCOVERY_FINISHED.equals(action)) {
                    if (mNewDevicesArrayAdapter.getCount() == 0) {
                        String noDevices = getResources().getText(R.string.none_found).toString();
                        mNewDevicesArrayAdapter.add(noDevices);
                    }
                }
            }
        };
        @Override
        protected void onCreate(Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
            setContentView(R.layout.device_list);
            //在被调用活动里,设置返回结果码
            setResult(Activity.RESULT_CANCELED);
            init();  //活动界面
        }
        private void init() {
            Button scanButton = findViewById(R.id.button_scan);
            scanButton.setOnClickListener(new OnClickListener() {
                public void onClick(View v) {
                    Toast.makeText(DeviceList.this, R.string.scanning, Toast.LENGTH_LONG).show();
                    doDiscovery();  //搜索蓝牙设备
                }
            });
            mPairedDevicesArrayAdapter = new ArrayAdapter<String>(this, R.layout.device_name);
            mNewDevicesArrayAdapter = new ArrayAdapter<String>(this, R.layout.device_name);
            //已配对蓝牙设备列表
            ListView pairedListView =findViewById(R.id.paired_devices);
            pairedListView.setAdapter(mPairedDevicesArrayAdapter);
            pairedListView.setOnItemClickListener(mPaireDeviceClickListener);
            //未配对蓝牙设备列表
            ListView newDevicesListView = findViewById(R.id.new_devices);
            newDevicesListView.setAdapter(mNewDevicesArrayAdapter);
            newDevicesListView.setOnItemClickListener(mNewDeviceClickListener);
            //动态注册广播接收者
            IntentFilter filter = new IntentFilter(BluetoothDevice.ACTION_FOUND);
            registerReceiver(mReceiver, filter);
            filter = new IntentFilter(BluetoothAdapter.ACTION_DISCOVERY_FINISHED);
            registerReceiver(mReceiver, filter);
            mBtAdapter = BluetoothAdapter.getDefaultAdapter();
            Set<BluetoothDevice> pairedDevices = mBtAdapter.getBondedDevices();
            if (pairedDevices.size() > 0) {
                findViewById(R.id.title_paired_devices).setVisibility(View.VISIBLE);
                for (BluetoothDevice device : pairedDevices) {
                    mPairedDevicesArrayAdapter.add(device.getName() + "\n" + device.getAddress());
                }
            } else {
                String noDevices = getResources().getText(R.string.none_paired).toString();
                mPairedDevicesArrayAdapter.add(noDevices);
            }
        }
        @Override
        protected void onDestroy() {
            super.onDestroy();
            if (mBtAdapter != null) {
                mBtAdapter.cancelDiscovery();
            }
            this.unregisterReceiver(mReceiver);
        }
        private void doDiscovery() {
            findViewById(R.id.title_new_devices).setVisibility(View.VISIBLE);
            if (mBtAdapter.isDiscovering()) {
                mBtAdapter.cancelDiscovery();
            }
            mBtAdapter.startDiscovery();  //开始搜索蓝牙设备并产生广播
             //startDiscovery是一个异步方法
            //找到一个设备时就发送一个BluetoothDevice.ACTION_FOUND的广播
        }
        private OnItemClickListener mPaireDeviceClickListener = new OnItemClickListener() {
            public void onItemClick(AdapterView<?> av, View v, int arg2, long arg3) {
                mBtAdapter.cancelDiscovery();
                String info = ((TextView) v).getText().toString();
                String address = info.substring(info.length() - 17);
                Intent intent = new Intent();
                intent.putExtra(EXTRA_DEVICE_ADDRESS, address);  //Mac地址
                setResult(Activity.RESULT_OK, intent);
                finish();
            }
        };
        private OnItemClickListener mNewDeviceClickListener = new OnItemClickListener() {
            public void onItemClick(AdapterView<?> av, View v, int arg2, long arg3) {
                mBtAdapter.cancelDiscovery();
                Toast.makeText(DeviceList.this, "请在蓝牙设置界面手动连接设备",Toast.LENGTH_SHORT).show();
                Intent intent = new Intent(Settings.ACTION_BLUETOOTH_SETTINGS);
                startActivityForResult(intent,1);
            }
        };
        //回调方法:进入蓝牙配对设置界面返回后执行
        @Override
        protected void onActivityResult(int requestCode, int resultCode, Intent data) {
            super.onActivityResult(requestCode, resultCode, data);
            init();  //刷新好友列表
        }
    }

7. 使用菜单File→Refactor→Rename,重命名模块的MainActivity为BluetoothChat,它是蓝牙会话的主Activity组件程序,其文件代码如下:

/*
    本例演示了使用手机蓝牙实现会话功能
    实验步骤:
    (1)在两个手机分别安装、运行本应用。如果未打开手机蓝牙,则进入打开蓝牙设置界面;
    (2)在OptionMenu(选项菜单)里,选择“我的好友”,即可直接连接,再进行会话;
    (3)新建好友前,需要先使用选项菜单“设置在线”,即要求对方可见(能被扫描到)。
    然后,单击“搜索好友”按钮。
*/
public class BluetoothChat extends AppCompatActivity{
    public static final int MESSAGE_STATE_CHANGE = 1;
    public static final int MESSAGE_READ = 2;
    public static final int MESSAGE_WRITE = 3;
    public static final int MESSAGE_DEVICE_NAME = 4;
    public static final int MESSAGE_TOAST = 5;
    public static final String DEVICE_NAME = "device_name";
    public static final String TOAST = "toast";
    private static final int REQUEST_CONNECT_DEVICE = 1;  //请求连接设备
    private static final int REQUEST_ENABLE_BT = 2;
    private TextView mTitle;
    private ListView mConversationView;
    private EditText mOutEditText;
    private Button mSendButton;
    private String mConnectedDeviceName = null;
    private ArrayAdapter<String> mConversationArrayAdapter;
    private StringBuffer mOutStringBuffer;
    private BluetoothAdapter mBluetoothAdapter = null;
    private ChatService mChatService = null;
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        getSupportActionBar().hide();  //隐藏标题栏
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
            if (ContextCompat.checkSelfPermission(this,Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
                ActivityCompat.requestPermissions(this,new String[]{Manifest.permission.ACCESS_COARSE_LOCATION}, 1);
            }
        }
        Toolbar toolbar = findViewById(R.id.toolbar);
         //创建选项菜单
        toolbar.inflateMenu(R.menu.option_menu);
         //选项菜单监听
        toolbar.setOnMenuItemClickListener(new MyMenuItemClickListener());
        mTitle = findViewById(R.id.title_left_text);
        mTitle.setText(R.string.app_name);
        mTitle = findViewById(R.id.title_right_text);
        // 得到本地蓝牙适配器
        mBluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
        if (mBluetoothAdapter == null) {
            Toast.makeText(this, "蓝牙不可用", Toast.LENGTH_LONG).show();
            finish();
            return;
        }
        if (!mBluetoothAdapter.isEnabled()) { //若当前设备蓝牙功能未开启
            Intent enableIntent = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);
            startActivityForResult(enableIntent, REQUEST_ENABLE_BT); //
        } else {
            if (mChatService == null) {
                setupChat();  //创建会话
            }
        }
    }
    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        if(grantResults.length>0){
            if(grantResults[0]!=PackageManager.PERMISSION_GRANTED){
                Toast.makeText(this, "未授权,蓝牙搜索功能将不可用!", Toast.LENGTH_SHORT).show();
            }
        }
    }
    @Override
    public synchronized void onResume() {  //synchronized:同步方法实现排队调用
        super.onResume();
        if (mChatService != null) {
            if (mChatService.getState() == ChatService.STATE_NONE) {
                mChatService.start();
            }
        }
    }
    private void setupChat() {
        mConversationArrayAdapter = new ArrayAdapter<String>(this, R.layout.message);
        mConversationView = findViewById(R.id.in);
        mConversationView.setAdapter(mConversationArrayAdapter);
        mOutEditText = findViewById(R.id.edit_text_out);
        mOutEditText.setOnEditorActionListener(mWriteListener);
        mSendButton = findViewById(R.id.button_send);
        mSendButton.setOnClickListener(new OnClickListener() {
            public void onClick(View v) {
                TextView view = findViewById(R.id.edit_text_out);
                String message = view.getText().toString();
                sendMessage(message);
            }
        });
         //创建服务对象
        mChatService = new ChatService(this, mHandler);
        mOutStringBuffer = new StringBuffer("");
    }
    @Override
    public void onDestroy() {
        super.onDestroy();
        if (mChatService != null)
            mChatService.stop();
    }
    private void ensureDiscoverable() { //修改本机蓝牙设备的可见性
        //打开手机蓝牙后,能被其它蓝牙设备扫描到的时间不是永久的
        if (mBluetoothAdapter.getScanMode() != BluetoothAdapter.SCAN_MODE_CONNECTABLE_DISCOVERABLE) {
            Intent discoverableIntent = new Intent(BluetoothAdapter.ACTION_REQUEST_DISCOVERABLE);
            //设置在300秒内可见(能被扫描)
            discoverableIntent.putExtra(BluetoothAdapter.EXTRA_DISCOVERABLE_DURATION, 300);
            startActivity(discoverableIntent);
            Toast.makeText(this, "已经设置本机蓝牙设备的可见性,对方可搜索了。", Toast.LENGTH_SHORT).show();
        }
    }
    private void sendMessage(String message) {
        if (mChatService.getState() != ChatService.STATE_CONNECTED) {
            Toast.makeText(this, R.string.not_connected, Toast.LENGTH_SHORT).show();
            return;
        }
        if (message.length() > 0) {
            byte[] send = message.getBytes();
            mChatService.write(send);
            mOutStringBuffer.setLength(0);
            mOutEditText.setText(mOutStringBuffer);
        }
    }
    private TextView.OnEditorActionListener mWriteListener = new TextView.OnEditorActionListener() {
        @Override
        public boolean onEditorAction(TextView view, int actionId, KeyEvent event) {
            if (actionId == EditorInfo.IME_NULL && event.getAction() == KeyEvent.ACTION_UP) {
                //软键盘里的回车也能发送消息
                String message = view.getText().toString();
                sendMessage(message);
            }
            return true;
        }
    };
    //使用Handler对象在UI主线程与子线程之间传递消息
    private final Handler mHandler = new Handler() {   //消息处理
        @Override
        public void handleMessage(Message msg) {
            switch (msg.what) {
            case MESSAGE_STATE_CHANGE:
                switch (msg.arg1) {
                case ChatService.STATE_CONNECTED:
                    mTitle.setText(R.string.title_connected_to);
                    mTitle.append(mConnectedDeviceName);
                    mConversationArrayAdapter.clear();
                    break;
                case ChatService.STATE_CONNECTING:
                    mTitle.setText(R.string.title_connecting);
                    break;
                case ChatService.STATE_LISTEN:
                case ChatService.STATE_NONE:
                    mTitle.setText(R.string.title_not_connected);
                    break;
                }
                break;
            case MESSAGE_WRITE:
                byte[] writeBuf = (byte[]) msg.obj;
                String writeMessage = new String(writeBuf);
                mConversationArrayAdapter.add("我:  " + writeMessage);
                break;
            case MESSAGE_READ:
                byte[] readBuf = (byte[]) msg.obj;
                String readMessage = new String(readBuf, 0, msg.arg1);
                mConversationArrayAdapter.add(mConnectedDeviceName + ":  "
                        + readMessage);
                break;
            case MESSAGE_DEVICE_NAME:
                mConnectedDeviceName = msg.getData().getString(DEVICE_NAME);
                Toast.makeText(getApplicationContext(),"链接到 " + mConnectedDeviceName, Toast.LENGTH_SHORT).show();
                break;
            case MESSAGE_TOAST:
                Toast.makeText(getApplicationContext(),
                        msg.getData().getString(TOAST), Toast.LENGTH_SHORT).show();
                break;
            }
        }
    };
    //返回进入好友列表操作后的数回调方法
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        switch (requestCode) {
        case REQUEST_CONNECT_DEVICE:
            if (resultCode == Activity.RESULT_OK) {
                String address = data.getExtras().getString(DeviceList.EXTRA_DEVICE_ADDRESS);
                BluetoothDevice device = mBluetoothAdapter.getRemoteDevice(address);
                mChatService.connect(device);
            }else if(resultCode==Activity.RESULT_CANCELED){
                Toast.makeText(this, "未选择任何好友!", Toast.LENGTH_SHORT).show();
            }
            break;
        case REQUEST_ENABLE_BT:
            if (resultCode == Activity.RESULT_OK) {
                setupChat();
            } else {
                Toast.makeText(this, R.string.bt_not_enabled_leaving, Toast.LENGTH_SHORT).show();
                finish();
            }
        }
    }
    //内部类,选项菜单的单击事件处理
    private class MyMenuItemClickListener implements Toolbar.OnMenuItemClickListener {
        @Override
        public boolean onMenuItemClick(MenuItem item) {
            switch (item.getItemId()) {
                case R.id.scan:
                    //启动DeviceList这个Activity
                    Intent serverIntent = new Intent(BluetoothChat.this, DeviceList.class);
                    startActivityForResult(serverIntent, REQUEST_CONNECT_DEVICE);
                    return true;
                case R.id.discoverable:
                    ensureDiscoverable();
                    return true;
                case R.id.back:
                    finish();
                    System.exit(0);
                    return true;
            }
            return false;
        }
    }
}

【Return Top】

(三)example9_3模块(手机NFC功能程序设计)

NFC读写模块的运行界面

1. 新建名为exaple9_3的模块。在模块清单文件里,添加注册本应用所需要的相关权限:

<uses-permission android:name="android.permission.NFC" />
<!--从Google应用商店下载安装NFC应用时,没有NFC功能的手机将不被安装-->
<uses-feature
    android:name="android.hardware.nfc"
    android:required="true" />

2. 编写Activity组件ReadTag,它没有包含危险权限,调用Activity组件WriteTag,其文件代码如下:

/*
    本活动用于读出Tag标签里的内容:非接触式,NFC线圈靠近芯片卡的中央
    如果读取其它已经加密卡,程序会闪退
*/
public class ReadTag extends AppCompatActivity {
    private NfcAdapter nfcAdapter;
    private TextView resultText;
    private PendingIntent pendingIntent;
    private IntentFilter[] mFilters;
    private String[][] mTechLists;
    private Button mJumpTagBtn;
    private boolean isFirst = true;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        // 获取NFC适配器,判断设备是否支持NFC功能
        nfcAdapter = NfcAdapter.getDefaultAdapter(this);
        if (nfcAdapter == null) {
              ////提示文本在资源文件res/values/strings.xml里,R.string.no_nfc是文本资源的id值
            Toast.makeText(this, getResources().getString(R.string.no_nfc), Toast.LENGTH_SHORT).show();
            finish();
            return;
        } else if (!nfcAdapter.isEnabled()) {
              //NFC未打开时
            Toast.makeText(this, getResources().getString(R.string.open_nfc), Toast.LENGTH_SHORT).show();
            finish();
            return;
        }
        setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);  //设定竖屏           setContentView(R.layout.read_tag);  //进入ReadTag活动,在清单文件里配置作为主活动
        resultText = findViewById(R.id.resultText); // 显示结果Text
        mJumpTagBtn = findViewById(R.id.jump); // 写入标签按钮
        mJumpTagBtn.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View v) {
                switch (v.getId()) {
                    case R.id.jump:
                        Intent intent = new Intent(ReadTag.this, WriteTag.class);
                        startActivity(intent);  //调用WiteTag这个Activity
                    default:
                        break;
                }
            }
        });
        /*
            创建一个PendingIntent对象,在扫描到NFC标签时,用它来封装NFC标签的详细信息。
            Intent.FLAG_ACTIVITY_SINGLE_TOP:如果当前栈顶的activity就是要启动的activity,则不会再启动一个新的activity
        */
        pendingIntent = PendingIntent.getActivity(this, 0, new Intent(this,getClass()).addFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP), 0);
        //使用IntentFilter过滤想要的action
        IntentFilter ndef = new IntentFilter(NfcAdapter.ACTION_TECH_DISCOVERED);
        ndef.addCategory("*/*");
        mFilters = new IntentFilter[] { ndef };    //过滤器
        mTechLists = new String[][] {
                //如果android设备支持MIFARE,提供对MIFARE Classic目标的属性和I/O操作
                new String[] { MifareClassic.class.getName() },
                new String[] { NfcA.class.getName() } };   // 允许扫描的标签类型
    }
    //重写Activity组件的onNewIntent()方法(不是生命周期方法)来获取扫描到的NFC标签的数据
    @Override
    protected void onNewIntent(Intent intent) {  //配合延期意图使用
        super.onNewIntent(intent);
         /*当系统检测到TAG标签中含有NDEF格式的数据时,且系统中有Activity声明可以接受包含NDEF数据的Intent的时候,系统会优先发出这个action的intent*/
        if (NfcAdapter.ACTION_TECH_DISCOVERED.equals(intent.getAction())) {
            String result = processIntent(intent);
            resultText.setText(result);
        }
    }
    @Override
    protected void onResume() {  //Activity组件的生命周期方法,配合延期意图使用
        super.onResume();
        nfcAdapter.enableForegroundDispatch(this, pendingIntent, mFilters,mTechLists);
        if (isFirst) {
            if (NfcAdapter.ACTION_TECH_DISCOVERED.equals(getIntent().getAction())) {
                String result = processIntent(getIntent());
                resultText.setText(result);
            }
            isFirst = false;
        }
    }
    //获取标签中的内容
    private String processIntent(Intent intent) {
        String resultStr=getResources().getString(R.string.message);
        try {
            Parcelable[] rawmsgs = intent.getParcelableArrayExtra(NfcAdapter.EXTRA_NDEF_MESSAGES);
            NdefMessage msg = (NdefMessage) rawmsgs[0];
            NdefRecord[] records = msg.getRecords();
            resultStr = new String(records[0].getPayload());
        }catch (Exception e){
            Toast.makeText(this, "无法识别的卡!", Toast.LENGTH_SHORT).show();
        }
        return resultStr;
    }
}

3.写Tag标签的Activity组件WriteTag的文件代码如下:

//本Activity组件WriteTag供本Activity组件ReadTag调用
public class WriteTag extends AppCompatActivity {
    private IntentFilter[] mWriteTagFilters;
    private NfcAdapter nfcAdapter;
    PendingIntent pendingIntent;
    String[][] mTechLists;
    Button writeBtn;
    boolean isWrite = false;
    EditText mContentEditText;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT); //设定竖屏
        setContentView(R.layout.write_tag);
        writeBtn = findViewById(R.id.writeBtn);
        writeBtn.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View v) {
                isWrite = true;
                AlertDialog.Builder builder = new AlertDialog.Builder(WriteTag.this).setTitle("请将标签靠近!");
                builder.setNegativeButton("确定", new DialogInterface.OnClickListener() {
                            @Override
                            public void onClick(DialogInterface dialog, int which) {
                                dialog.dismiss();
                                mContentEditText.setText("");
                                isWrite = false;
                                WriteTag.this.finish();
                            }
                        });
                builder.setPositiveButton("取消", new DialogInterface.OnClickListener() {
                            @Override
                            public void onClick(DialogInterface dialog, int which) {
                                dialog.dismiss();
                                isWrite = false;
                            }
                        });
                builder.create();
                builder.show();
            }
        });
        mContentEditText = findViewById(R.id.content_edit);
        nfcAdapter = NfcAdapter.getDefaultAdapter(this);
        if (nfcAdapter == null) {
            Toast.makeText(this, getResources().getString(R.string.no_nfc), Toast.LENGTH_SHORT).show();
            finish();
            return;
        } else if (!nfcAdapter.isEnabled()) {
            Toast.makeText(this, getResources().getString(R.string.open_nfc),
                    Toast.LENGTH_SHORT).show();
            finish();
            return;
        }
        pendingIntent = PendingIntent.getActivity(this, 0, new Intent(this, getClass()).addFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP), 0);
        IntentFilter writeFilter = new IntentFilter(NfcAdapter.ACTION_TECH_DISCOVERED);
        mWriteTagFilters = new IntentFilter[] { writeFilter };
        mTechLists = new String[][] {
                new String[] { MifareClassic.class.getName() },
                new String[] { NfcA.class.getName() } };// 允许扫描的标签类型
    }
     //重写Activity组件的onNewIntent()方法(不是生命周期方法)来获取扫描到的NFC标签的数据
    @Override
    protected void onNewIntent(Intent intent) {  //配合延期意图使用
        super.onNewIntent(intent);
        if (isWrite == true && NfcAdapter.ACTION_TECH_DISCOVERED.equals(intent.getAction())) {
            Tag tag = intent.getParcelableExtra(NfcAdapter.EXTRA_TAG);
            NdefMessage ndefMessage = getNoteAsNdef();
            if (ndefMessage != null) {
                writeTag(getNoteAsNdef(), tag);
            } else {
                showToast("请输入您要写入标签的内容");
            }
        }
    }
    @Override
    protected void onResume() {  //Activity组件的生命周期方法,配合延期意图使用
        super.onResume();
        nfcAdapter.enableForegroundDispatch(this, pendingIntent,mWriteTagFilters, mTechLists);
    }
    // 根据文本生成一个NdefRecord
    private NdefMessage getNoteAsNdef() {
        String text = mContentEditText.getText().toString();
        if (text.equals("")) {
            return null;
        } else {
            byte[] textBytes = text.getBytes();
            NdefRecord textRecord = new NdefRecord(NdefRecord.TNF_MIME_MEDIA,"image/jpeg".getBytes(), new byte[] {}, textBytes);
            return new NdefMessage(new NdefRecord[] { textRecord });
        }
    }
    // 写入Tag标签
    boolean writeTag(NdefMessage message, Tag tag) {
        int size = message.toByteArray().length;
        try {
            Ndef ndef = Ndef.get(tag);
            if (ndef != null) {
                ndef.connect();
                if (!ndef.isWritable()) {
                    showToast("Tag不允许写入");
                    return false;
                }
                if (ndef.getMaxSize() < size) {
                    showToast("文件大小超出容量");
                    return false;
                }
                ndef.writeNdefMessage(message);
                showToast("写入数据成功.");
                return true;
            } else {
                NdefFormatable format = NdefFormatable.get(tag);
                if (format != null) {
                    try {
                        format.connect();
                        format.format(message);
                        showToast("格式化并且写入message");
                        return true;
                    } catch (IOException e) {
                        showToast("无法识别的卡!");
                        return false;
                    }
                } else {
                    showToast("Tag不支持NDEF");
                    return false;
                }
            }
        } catch (Exception e) {
            showToast("写入数据失败");
        }
        return false;
    }
    private void showToast(String text) {
        Toast.makeText(this, text, Toast.LENGTH_SHORT).show();
    }
}

【Return Top】