智能家电之蓝牙控制

这不是广告

首先得需要一个蓝牙控制器 然后再操作

我在某宝发现了这样的 附地址

https://item.taobao.com/item.htm?spm=a230r.1.14.45.YzSGuI&id=42767906785&ns=1&abbucket=1#detail

butterknife的使用在我别的博客上有



这个是布局图 因为要在真机测试 很麻烦 

不过我这是完美运行后的代码

多说无益 代码才是最好的老师

MainActivity

package com.example.lanya;

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.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.BaseAdapter;
import android.widget.Button;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;

import java.io.IOException;
import java.io.OutputStream;
import java.util.ArrayList;
import java.util.UUID;

import butterknife.Bind;
import butterknife.ButterKnife;
import butterknife.OnClick;

public class MainActivity extends AppCompatActivity {

    @Bind(R.id.bt_open)
    Button btOpen;
    @Bind(R.id.bt_close)
    Button btClose;
    @Bind(R.id.bt_scannle)
    Button btScannle;
    @Bind(R.id.bt_closescannle)
    Button btClosescannle;
    @Bind(R.id.bt_open_light)
    Button btOpenLight;
    @Bind(R.id.bt_close_light)
    Button btCloseLight;
    @Bind(R.id.bt_close_time)
    Button btCloseTime;
    @Bind(R.id.lv_result)
    ListView lvResult;
    @Bind(R.id.activity_main)
    LinearLayout activityMain;
    private BluetoothAdapter mBluetoothAdapter;
    private MyReceiver mReceiver;
    private IntentFilter mFilter;
    private ArrayList<BluetoothDevice> mList = new ArrayList<>();
    private MyAdapter myAdapter;
    private OutputStream outputStream;
    private  int OPEN=0x10;
    private  int CLOASE=0x11;
    private  int OPEN4S=0x19;
    private BluetoothSocket bluetoothSocket;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        ButterKnife.bind(this);
        //蓝牙入口类对象 如果没有则返回空
        mBluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
        //注册接受蓝牙设备的广播
        mReceiver = new MyReceiver();
        mFilter = new IntentFilter();
        mFilter.addAction(BluetoothAdapter.ACTION_DISCOVERY_STARTED);
        mFilter.addAction(BluetoothAdapter.ACTION_DISCOVERY_FINISHED);
        mFilter.addAction(BluetoothDevice.ACTION_FOUND);
        registerReceiver(mReceiver, mFilter);
        lvResult.setOnItemClickListener(new MyOnItemClick());

    }

    @OnClick({R.id.bt_open, R.id.bt_close, R.id.bt_scannle, R.id.bt_closescannle, R.id.bt_open_light, R.id.bt_close_light, R.id.bt_close_time})
    public void onClick(View view) {
        if (mBluetoothAdapter == null) {
            Toast.makeText(this, "蓝牙不可用", Toast.LENGTH_SHORT).show();
            return;
        }
        switch (view.getId()) {
            case R.id.bt_open:
                //打开蓝牙
                mBluetoothAdapter.enable();
                break;
            case R.id.bt_close:
                mBluetoothAdapter.disable();
                break;
            case R.id.bt_scannle:
                if(mList.size()>0){
                    mList.clear();
                }
                if (mBluetoothAdapter.isEnabled()) {
                    mBluetoothAdapter.startDiscovery();

                }

                break;
            case R.id.bt_closescannle:
                if (mBluetoothAdapter.isEnabled()) {
                    mBluetoothAdapter.cancelDiscovery();

                }
                break;
            case R.id.bt_open_light:
                sendCMD(OPEN);
                break;
            case R.id.bt_close_light:
                sendCMD(CLOASE);
                break;
            case R.id.bt_close_time:
                sendCMD(OPEN4S);
                break;
        }
    }

    class MyReceiver extends BroadcastReceiver {
        @Override
        public void onReceive(Context context, Intent intent) {
            switch (intent.getAction()) {
                //扫描开始
                case BluetoothAdapter.ACTION_DISCOVERY_STARTED:
                    Toast.makeText(context, "扫描开始", Toast.LENGTH_SHORT).show();
                    break;
                //扫描结束
                case BluetoothAdapter.ACTION_DISCOVERY_FINISHED:
                    Toast.makeText(context, "扫描结束", Toast.LENGTH_SHORT).show();

                    break;
                //找到设备
                case BluetoothDevice.ACTION_FOUND:
                    BluetoothDevice device = intent.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE);
//                    Toast.makeText(context, "找到设备" + device.getName(), Toast.LENGTH_SHORT).show();
                    mList.add(device);
                    if(myAdapter==null) {
                        myAdapter = new MyAdapter();
                    }
                    lvResult.setAdapter(myAdapter);

                    break;
            }
        }
    }

    class MyAdapter extends BaseAdapter {
        @Override
        public int getCount() {
            return mList.size();
        }

        @Override
        public Object getItem(int position) {
            return null;
        }

        @Override
        public long getItemId(int position) {
            return 0;
        }

        @Override
        public View getView(int position, View convertView, ViewGroup parent) {
            if (convertView == null) {
                convertView = View.inflate(getApplicationContext(), R.layout.listview_item, null);
            }
            TextView name = (TextView)convertView.findViewById(R.id.tv_name);
            TextView adress = (TextView)convertView.findViewById(R.id.tv_adress);
            name.setText(mList.get(position).getName());
            adress.setText(mList.get(position).getAddress());
            return convertView;
        }


    }
    class MyOnItemClick implements AdapterView.OnItemClickListener{
        @Override
        public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
            BluetoothDevice device = mList.get(position);
            connect(device);

        }
    }

    private  void sendCMD(int cmd){
        if(outputStream!=null){
            try {
            byte[] bytes = new byte[5];
            bytes[0]=(byte)0x01;
            bytes[1]=(byte)0x99;

            bytes[2]=(byte)cmd;
            bytes[3]=(byte)cmd;

            bytes[4]=(byte)0x99;

                outputStream.write(bytes);
                outputStream.flush();
            } catch (IOException e) {
                e.printStackTrace();
            }

        }
    }

    private void connect(final BluetoothDevice device) {
        new Thread(){



            @Override
            public void run() {
                try {
                    bluetoothSocket = device.createRfcommSocketToServiceRecord(UUID.fromString("00001101-0000-1000-8000-00805f9b34fb"));
                    bluetoothSocket.connect();;//耗时操作
                    //获取输出流
                    MainActivity.this.outputStream = outputStream;
                    outputStream = bluetoothSocket.getOutputStream();

                    runOnUiThread(new Runnable() {
                        @Override
                        public void run() {
                            Toast.makeText(MainActivity.this, "连接成功", Toast.LENGTH_SHORT).show();
                        }
                    });

                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }.start();


    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        if(outputStream!=null){
            try {
                outputStream.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
            outputStream=null;


        }
        if(bluetoothSocket!=null&&bluetoothSocket.isConnected()){
            try {
                bluetoothSocket.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
            bluetoothSocket=null;

        }
        unregisterReceiver(mReceiver);
    }
}

activity_main.xml

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:id="@+id/activity_main"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
android:orientation="vertical"
    tools:context="com.example.lanya.MainActivity">

  <LinearLayout
      android:layout_margin="7dp"
      android:layout_width="match_parent"
      android:orientation="horizontal"
      android:layout_height="wrap_content">
      <Button
          android:id="@+id/bt_open"
          android:text="打开蓝牙"
          android:layout_weight="1"
          android:layout_width="0dp"
          android:layout_height="wrap_content" />
      <Button
          android:id="@+id/bt_close"
          android:text="打开蓝牙"
          android:layout_weight="1"
          android:layout_width="0dp"
          android:layout_height="wrap_content" />


  </LinearLayout>
    <LinearLayout
        android:layout_margin="7dp"
        android:layout_width="match_parent"
        android:orientation="horizontal"
        android:layout_height="wrap_content">
        <Button
            android:id="@+id/bt_scannle"
            android:text="扫描设备"
            android:layout_weight="1"
            android:layout_width="0dp"
            android:layout_height="wrap_content" />
        <Button
            android:id="@+id/bt_closescannle"
            android:text="关闭扫描"
            android:layout_weight="1"
            android:layout_width="0dp"
            android:layout_height="wrap_content" />


    </LinearLayout>
    <LinearLayout
        android:layout_margin="7dp"
        android:layout_width="match_parent"
        android:orientation="horizontal"
        android:layout_height="wrap_content">
        <Button
            android:id="@+id/bt_open_light"
            android:text="开灯"
            android:layout_weight="1"
            android:layout_width="0dp"
            android:layout_height="wrap_content" />
        <Button
            android:id="@+id/bt_close_light"
            android:text="关灯"
            android:layout_weight="1"
            android:layout_width="0dp"
            android:layout_height="wrap_content" />
        <Button
            android:id="@+id/bt_close_time"
            android:text="定时关闭(点动)"
            android:layout_weight="1"
            android:layout_width="0dp"
            android:layout_height="wrap_content" />


    </LinearLayout>
    <ListView
        android:id="@+id/lv_result"
        android:layout_width="match_parent"
        android:layout_height="match_parent"/>
</LinearLayout>


listview_item.xml

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

    <TextView
        android:id="@+id/tv_name"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_margin="5dp"
        android:textColor="#F00"
        android:textSize="15sp" />

    <TextView
        android:id="@+id/tv_adress"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:textColor="#F00"
        android:textSize="15sp" />

</LinearLayout>


额 少了俩权限 尴尬


<uses-permission android:name="android.permission.BLUETOOTH"/>
<uses-permission android:name="android.permission.BLUETOOTH_ADMIN"/>




  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

安果移不动

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值