藍芽原理Android代碼實現_Android

來源:互聯網
上載者:User

本文執行個體為大家分享了Android實現藍芽原理代碼,供大家參考,具體內容如下

package com.example.se7en.testbluetooth;import android.app.Activity;import android.bluetooth.BluetoothAdapter;import android.bluetooth.BluetoothDevice;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.os.Bundle;import android.util.Log;import android.view.View;import android.widget.AdapterView;import android.widget.EditText;import android.widget.ListView;import android.widget.Toast;import java.io.IOException;import java.util.ArrayList;import java.util.List;import java.util.UUID;public class MainActivity extends Activity{  private BluetoothAdapter adapter;  private MyReceiver receiver;  private ListView mListView;  private List<BluetoothDevice> mDevices;  private com.example.se7en.testbluetooth.DeviceAdapter mDeviceAdapter;  private BluetoothSocket mSocket;  private EditText et;  @Override  protected void onCreate(Bundle savedInstanceState)  {    super.onCreate(savedInstanceState);    setContentView(R.layout.activity_main);    mListView = (ListView) findViewById(R.id.lv);    et = (EditText) findViewById(R.id.et);    adapter = BluetoothAdapter.getDefaultAdapter();    BlueToothHandler.getInstance().setContext(this);    init();  }  private void init()  {    initListView();    // 判斷是否支援藍芽功能    if (adapter == null)    {      Toast.makeText(this, "該手機不支援藍芽功能", Toast.LENGTH_LONG).show();      return;    }    // 判斷藍芽功能是否開啟    if (!adapter.isEnabled())    {      // 強行開啟//      adapter.enable();      Intent intent=new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);      startActivity(intent);    }    IntentFilter filter = new IntentFilter();    // 註冊掃描開始的廣播    filter.addAction(BluetoothAdapter.ACTION_DISCOVERY_STARTED);    // 註冊掃描結束的廣播    filter.addAction(BluetoothAdapter.ACTION_DISCOVERY_FINISHED);    // 註冊掃描已經找到裝置的廣播    filter.addAction(BluetoothDevice.ACTION_FOUND);    receiver = new MyReceiver();    registerReceiver(receiver, filter);    startBlueServer();  }  /**   * 啟動藍芽服務   */  private void startBlueServer()  {    new Thread()    {      @Override      public void run()      {        while (true)        {          try          {            BluetoothServerSocket serverSocket = adapter                .listenUsingRfcommWithServiceRecord(                    "藍芽服務",                    UUID.fromString("997f1b20-b4a0-45ea-a7dd-b2097299b1f6"));            mSocket = serverSocket.accept();//阻塞            BlueToothHandler.getInstance().setSocket(mSocket);          }          catch (IOException e)          {            e.printStackTrace();          }        }      }    }.start();  }  public void doClick(View view)  {    switch (view.getId())    {      case R.id.btn:        mDevices.clear();        mDeviceAdapter.notifyDataSetChanged();        // 判斷是否正在掃描,如果沒在掃描那麼就開始掃描        if (!adapter.isDiscovering() && adapter.startDiscovery())        {          Toast.makeText(this, "開始掃描周圍的藍牙裝置", Toast.LENGTH_LONG)              .show();        }        break;      case R.id.send:        if ("".equals(et.getText().toString()))        {          Toast.makeText(this, "內容不可為空", Toast.LENGTH_SHORT).show();          return;        }        if (BlueToothHandler.getInstance().getSocket() == null)        {          Toast.makeText(this, "還未串連裝置", Toast.LENGTH_SHORT).show();          return;        }        new Thread()        {          @Override          public void run()          {            BlueToothHandler.getInstance().sendMessage(                et.getText().toString());          }        }.start();        break;      case R.id.dis:        BlueToothHandler.getInstance().closeSocket();        break;    }  }  @Override  protected void onDestroy()  {    super.onDestroy();    if (receiver != null)    {      // 登出廣播      unregisterReceiver(receiver);    }  }  private void initListView()  {    mDevices = new ArrayList<BluetoothDevice>();    mDeviceAdapter = new com.example.se7en.testbluetooth.DeviceAdapter(this, mDevices);    mListView.setAdapter(mDeviceAdapter);    mListView.setOnItemClickListener(new AdapterView.OnItemClickListener()    {      @Override      public void onItemClick(AdapterView<?> parent, View view,          int position, long id)      {        try        {          mSocket = mDevices              .get(position)              .createRfcommSocketToServiceRecord(                  UUID.fromString("997f1b20-b4a0-45ea-a7dd-b2097299b1f6"));          mSocket.connect();//阻塞          Toast.makeText(MainActivity.this, "串連成功",              Toast.LENGTH_SHORT).show();          BlueToothHandler.getInstance().setSocket(mSocket);        }        catch (IOException e)        {          e.printStackTrace();        }      }    });  }  public class MyReceiver extends BroadcastReceiver  {    @Override    public void onReceive(Context context, Intent intent)    {      String action = intent.getAction();      if (action.equals(BluetoothAdapter.ACTION_DISCOVERY_STARTED))      {        Log.i("info", "開始掃描");      }      else if (action.equals(BluetoothAdapter.ACTION_DISCOVERY_FINISHED))      {        Log.i("info", "掃描結束");      }      else if (action.equals(BluetoothDevice.ACTION_FOUND))      {        BluetoothDevice device = intent            .getParcelableExtra(BluetoothDevice.EXTRA_DEVICE);        Log.i("info", device.getName() + ":" + device.getAddress());        if (mDevices != null)        {          for (int i = 0; i < mDevices.size(); i++)          {            if (device.getAddress()                .equals(mDevices.get(i).getAddress()))            {              return;            }          }          mDevices.add(device);          mDeviceAdapter.notifyDataSetChanged();        }      }    }  }}

以上就是本文的全部內容,希望對大家的學習有所協助,也希望大家多多支援雲棲社區。

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.