Android學習之----藍牙

藍牙

一.藍牙介紹:
二.藍牙的作用:
三 .藍牙工作原理以及涉及到的類:
四.代碼
服務端線程

一.藍牙介紹:

是一種無線技術標準,可實現固定設備、移動設備和樓宇個人域網之間的短距離數據交換,我們主要掌握這幾項技能:

在這裏插入圖片描述

package com.example.bluetooth;

import android.Manifest;
import android.bluetooth.BluetoothAdapter;
import android.bluetooth.BluetoothDevice;
import android.bluetooth.BluetoothManager;
import android.bluetooth.BluetoothServerSocket;
import android.bluetooth.BluetoothSocket;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.pm.PackageManager;
import android.os.Build;
import android.os.Environment;
import android.support.annotation.NonNull;
import android.support.v4.app.ActivityCompat;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.AdapterView;
import android.widget.Button;
import android.widget.ListView;

import java.io.BufferedOutputStream;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.ArrayList;
import java.util.List;
import java.util.UUID;

public class MainActivity extends AppCompatActivity implements View.OnClickListener {
    private BluetoothAdapter adapter;
    private ArrayList<BluetoothDevice> devices=new ArrayList<>();
    private ListView listView;
    private MyReceiver myReceiver;
    private static final String TAG = "MainActivity";
    private MyAdapter myAdapter;
    private BluetoothDevice device2;





    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        findViewById(R.id.start).setOnClickListener(this);
        findViewById(R.id.stop).setOnClickListener(this);
        findViewById(R.id.find).setOnClickListener(this);
        findViewById(R.id.cp).setOnClickListener(this);
        listView = (ListView) findViewById(R.id.lv);

        init();
    }

    public void init(){
        String[] strings=new String[]{
                Manifest.permission.BLUETOOTH,
                Manifest.permission.BLUETOOTH_ADMIN,
                Manifest.permission.ACCESS_FINE_LOCATION
        };

        if (Build.VERSION.SDK_INT>=Build.VERSION_CODES.M){
            if (ActivityCompat.checkSelfPermission(this,Manifest.permission.ACCESS_FINE_LOCATION)!= PackageManager.PERMISSION_GRANTED){
                requestPermissions(strings,101);
            }
        }

        initMyBlueTooth();

        //註冊廣播接收者
        IntentFilter filter=new IntentFilter();
        filter.addAction(BluetoothDevice.ACTION_FOUND);//註冊搜索
        filter.addAction(BluetoothAdapter.ACTION_DISCOVERY_FINISHED);//結束搜索
        myReceiver = new MyReceiver();
        registerReceiver(myReceiver,filter);

        listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                BluetoothDevice device=devices.get(position);
                device.createBond();
            }
        });

    }

    public void initMyBlueTooth(){
        BluetoothManager manager= (BluetoothManager) getSystemService(BLUETOOTH_SERVICE);
        adapter = manager.getAdapter();
    }


    @Override
    public void onClick(View v) {
        switch (v.getId()){
            case R.id.start:
                open();
                break;
            case R.id.stop:
                close();
                break;
            case R.id.find:
                serch();
                break;
        }
    }


    /**
     * 打開
     */
    public void open(){
        Intent intent = new Intent();
        intent.setAction(BluetoothAdapter.ACTION_REQUEST_ENABLE);
        intent.setAction(BluetoothAdapter.ACTION_REQUEST_DISCOVERABLE);
//        intent.putExtra(BluetoothAdapter.EXTRA_DISCOVERABLE_DURATION,200);
        startActivityForResult(intent,100);

    }

    /**
     * 關閉
     */
    public void close(){
        adapter.disable();
    }

    /**
     * 搜索
     */
    public void serch(){
        adapter.startDiscovery();
    }


    class MyReceiver extends BroadcastReceiver{

        @Override
        public void onReceive(Context context, Intent intent) {
            //收其他搜索到的牙

            if (intent.getAction().equals(BluetoothDevice.ACTION_FOUND)){
                BluetoothDevice device=intent.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE);
                devices.add(device);

                device.getName();
                Log.i(TAG, "66666: "+device);
            }else if (intent.getAction().equals(BluetoothAdapter.ACTION_DISCOVERY_FINISHED)){
                //將所有藍牙設備顯示到界面上
                myAdapter = new MyAdapter(MainActivity.this, devices);
                listView.setAdapter(myAdapter);
            }else if (intent.getAction().equals(BluetoothDevice.ACTION_BOND_STATE_CHANGED)){
                device2=intent.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE);
                int state = device2.getBondState();
              //  if (state==BluetoothDevice.BOND_BONDED){
                    //發送文件
                    new ClientThread().start();

             //   }
            }

        }
    }

    class ClientThread extends Thread{
        @Override
        public void run() {
            super.run();
            UUID uuid=UUID.fromString("00001106-0000-1000-8000-00805F9B34FB");
            try {
                BluetoothSocket socket=device2.createInsecureRfcommSocketToServiceRecord(uuid);
                socket.connect();
                Log.i(TAG, "11111111111111");

                BufferedOutputStream outputStream=new BufferedOutputStream(socket.getOutputStream());
                FileInputStream fileInputStream = new FileInputStream(Environment.getExternalStorageDirectory()+ "/http.txt");
                int len=0;
                byte[] bytes=new byte[1024];
                while ((len=fileInputStream.read(bytes))!=-1){
                    outputStream.write(bytes,0,len);
                }
                outputStream.flush();
                outputStream.close();
                fileInputStream.close();

                ReveFromServer(socket);


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

        public void ReveFromServer(BluetoothSocket socket){
            try {
                Log.i(TAG, "22222222222222");
                InputStream inputStream = socket.getInputStream();
                FileOutputStream outputStream=new FileOutputStream(Environment.getExternalStorageDirectory()+"/aaa.txt");
                int len=0;
                byte[] bytes=new byte[1024];
                while ((len=inputStream.read(bytes))!=-1){
                    outputStream.write(bytes,0,len);
                }

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



    }

}

package com.example.bluetooth;

import android.bluetooth.BluetoothDevice;
import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.TextView;

import java.util.ArrayList;

public class MyAdapter extends BaseAdapter {
    private Context context;
    private ArrayList<BluetoothDevice> list;
    private LayoutInflater layoutInflater;


    public MyAdapter(Context context, ArrayList<BluetoothDevice> list) {
        this.context = context;
        this.list = list;
        layoutInflater=LayoutInflater.from(context);
    }

    @Override
    public int getCount() {
        return list.size();
    }

    @Override
    public Object getItem(int position) {
        return list.get(position);
    }

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

    @Override
    public View getView(int position, View convertView, ViewGroup parent) {
        MyHolder myHolder;
        if (convertView==null){
            myHolder=new MyHolder();
            convertView=layoutInflater.inflate(R.layout.item,parent,false);
            myHolder.tv=(TextView) convertView.findViewById(R.id.text1);
            convertView.setTag(myHolder);
        }else {
            myHolder=(MyHolder) convertView.getTag();
        }
        myHolder.tv.setText(list.get(position).getName());

        return convertView;
    }

    class MyHolder {
        TextView tv;
    }

}

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.example.bluetooth">

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

    <application
        android:allowBackup="true"
        android:icon="@mipmap/ic_launcher"
        android:label="@string/app_name"
        android:roundIcon="@mipmap/ic_launcher_round"
        android:supportsRtl="true"
        android:theme="@style/AppTheme">
        <activity android:name=".MainActivity">
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />

                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
    </application>

</manifest>
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:orientation="vertical"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context=".MainActivity">

    <Button
        android:id="@+id/start"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="打開藍牙"
         />

    <Button
        android:id="@+id/stop"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="關閉藍牙"
        />

    <Button
        android:id="@+id/find"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="搜索附近的藍牙"
         />

    <Button
        android:id="@+id/cp"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="發送文件"
      />

    <TextView
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="搜索到的設備:"
        android:textSize="25sp"
        />

    <ListView
        android:id="@+id/lv"
        android:layout_width="match_parent"
        android:layout_height="wrap_content">

    </ListView>

    <TextView
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="已配對的設備:"
        android:textSize="25sp"
        />

    <ListView
        android:id="@+id/lv2"
        android:layout_width="match_parent"
        android:layout_height="wrap_content">

    </ListView>


</LinearLayout>
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章