Bluetooth principle Android Code Implementation _android

Source: Internet
Author: User
Tags gettext uuid

This example for you to share the Android Bluetooth principle code, for your reference, the specific contents are as follows

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 ();
      Determine if Bluetooth is supported if (adapter = null) {Toast.maketext (this, "the phone does not support Bluetooth", Toast.length_long). Show ();
    Return
      //Determine if Bluetooth features open if (!adapter.isenabled ()) {//forcibly open//adapter.enable ();
      Intent intent=new Intent (bluetoothadapter.action_request_enable);
    StartActivity (Intent);
    } intentfilter filter = new Intentfilter ();
    Registers a scanning start broadcast filter.addaction (bluetoothadapter.action_discovery_started);
    Registering the scan end of the broadcast filter.addaction (bluetoothadapter.action_discovery_finished); Register sweepTrace has found the device's broadcast filter.addaction (Bluetoothdevice.action_found);
    Receiver = new Myreceiver ();
    Registerreceiver (receiver, filter);
  Startblueserver (); /** * Start bluetooth service * * private void Startblueserver () {new Thread () {@Override public void R Un () {while (true) {try {bluetoothserversocket serversocket = Ada Pter. Listenusingrfcommwithservicerecord ("Bluetooth Service", uuid.fromstring (
            "997f1b20-b4a0-45ea-a7dd-b2097299b1f6"));
          Msocket = Serversocket.accept ();//Blocking 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 (); Determine whether you areScan if it's not scanning then start scanning if (!adapter.isdiscovering () && adapter.startdiscovery ()) {Toast.maket
        Ext (This, "Start scanning around Bluetooth devices", Toast.length_long). Show ();
      } break; Case R.id.send:if ("". Equals (Et.gettext (). toString ())} {Toast.maketext (this, "content cannot be empty", TOAST.L
          Ength_short). Show ();
        Return } if (Bluetoothhandler.getinstance (). Getsocket () = null) {Toast.maketext (this, "Device not Connected", 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) {    Cancellation of Broadcast 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). Createrfcommsockettoservi
          Cerecord (uuid.fromstring ("997f1b20-b4a0-45ea-a7dd-b2097299b1f6"));
          Msocket.connect ()//Blocking Toast.maketext (mainactivity.this, "Connection succeeded", Toast.length_short). Show ();
        Bluetoothhandler.getinstance (). Setsocket (Msocket);
        catch (IOException e) {e.printstacktrace ();
  }

      }
    }); } publiC Class Myreceiver extends Broadcastreceiver {@Override public void onreceive (context, Intent Intent)
      {String action = intent.getaction ();
      if (Action.equals (bluetoothadapter.action_discovery_started)) {log.i ("info", "start scanning");
      else if (action.equals (bluetoothadapter.action_discovery_finished)) {log.i ("info", "scan End");
            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 ();
   }   }
    }

  }
}


 

The above is the entire content of this article, I hope to help you learn, but also hope that we support the cloud habitat community.

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

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.