note 38-Bluetooth

1. get a BluetoothAdapter instance by BluetoothAdapter.getDefaultAdapter();

2. use an intent with uri BluetoothAdapter.ACTION_REQUEST_ENABLE to open the blue tooth

3. get a devices Set by adapter.getBondedDevices();

Or:

1. get a BluetoothAdapter instance by BluetoothAdapter.getDefaultAdapter();

2. new a BroadcastReceiver Child to receive the  intentFilter.addAction(BluetoothDevice.ACTION_FOUND);

3.  use bluetoothAdapter.startDiscovery() to search surounding bluetooth device . It is an asynchronous

function and will send the intent with BluetoothDevice.EXTRA_DEVICE

BluetoothDevice device=intent.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE);
                Log.i("l","address:"+device.getAddress());

Make your device discoverable:

Intent discoverableIntent=new Intent(BluetoothAdapter.ACTION_REQUEST_DISCOVERABLE);
            discoverableIntent.putExtra(BluetoothAdapter.EXTRA_DISCOVERABLE_DURATION, 500);
            startActivity(discoverableIntent);

Don't forget the permission:

 

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

 Full code:

 

package com.blue_tooth_test;

import android.app.Activity;
import android.bluetooth.BluetoothAdapter;
import android.bluetooth.BluetoothDevice;
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.view.View.OnClickListener;
import android.widget.Button;
import android.widget.LinearLayout;
import java.util.Iterator;
import java.util.Set;

public class BlueToothTest extends Activity
{
    
    private Button btn;
    private Button btn2;
    private Button btn3;
    private LinearLayout ll;
    
    private BluetoothAdapter bluetoothAdapter;
    
    private BluetoothReceiver bluetoothReceiver;
    
    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState)
    {
        super.onCreate(savedInstanceState);
        
        ll=new LinearLayout(this);
        ll.setOrientation(LinearLayout.VERTICAL);
        
        LinearLayout.LayoutParams params=new 
                LinearLayout.LayoutParams(
                LinearLayout.LayoutParams.FILL_PARENT,
                LinearLayout.LayoutParams.WRAP_CONTENT);
        
        btn=new Button(this);
        btn.setText("Bluetooth Scan");
        btn.setOnClickListener(clickListener);
        
        btn2=new Button(this);
        btn2.setText("Set visible");
        btn2.setOnClickListener(clickListener2);
        
        btn3=new Button(this);
        btn3.setText("Scan device");
        btn3.setOnClickListener(clickListener3);
        
        ll.addView(btn,params);
        ll.addView(btn2,params);
        ll.addView(btn3,params);
        
        setContentView(ll);
        
        bluetoothAdapter=BluetoothAdapter.getDefaultAdapter();
        
        bluetoothReceiver=new BluetoothReceiver();
        
        IntentFilter intentFilter=new IntentFilter();
        intentFilter.addAction(BluetoothDevice.ACTION_FOUND);
        
        this.registerReceiver(bluetoothReceiver, intentFilter);
        
    }
    
    
    private OnClickListener clickListener=new OnClickListener(){

        public void onClick(View arg0) {
//            throw new UnsupportedOperationException("Not supported yet.");
            
            //1. get a BluetoothAdapter instance;
            BluetoothAdapter adapter=BluetoothAdapter.getDefaultAdapter();
            
            if(adapter!=null){
                Log.i("l","Bluetooth device OK");
                
                //2. if current bluetooth enable
                if(!adapter.isEnabled()){
                    Intent intent=new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);
                    BlueToothTest.this.startActivity(intent);
                }
                
                //3. get all the paired bluetooth device
                //that means the remote device list;
                Set<BluetoothDevice> devices=adapter.getBondedDevices();
                
                if(devices.size()>0){
                    
                    Iterator iter=devices.iterator();
                    
                    while(iter.hasNext()){
                        BluetoothDevice bluetoothDevice=(BluetoothDevice)iter.next();
                        Log.i("l","address:"+bluetoothDevice.getAddress());
                    }
                    
                }
            }
            else{
                Log.i("l","No bluetooth device");
            }
            
        }
        
    };
    
    
    
    
    private OnClickListener clickListener2=new OnClickListener(){

        public void onClick(View arg0) {
//            throw new UnsupportedOperationException("Not supported yet.");
            
            Intent discoverableIntent=new Intent(BluetoothAdapter.ACTION_REQUEST_DISCOVERABLE);
            discoverableIntent.putExtra(BluetoothAdapter.EXTRA_DISCOVERABLE_DURATION, 500);
            startActivity(discoverableIntent);
            
        }    
        
    };
    
    private OnClickListener clickListener3=new OnClickListener(){

        public void onClick(View arg0) {
//            throw new UnsupportedOperationException("Not supported yet.");
            
            
//              The discovery process usually involves an inquiry scan of about 12 seconds, followed by a page scan of each new device to retrieve its Bluetooth name.
//              This is an asynchronous call, it will return immediately. Register for ACTION_DISCOVERY_STARTED and ACTION_DISCOVERY_FINISHED intents to determine exactly 
//              when the discovery starts and completes. Register for ACTION_FOUND to be notified as remote Bluetooth devices are found.
//              Device discovery is a heavyweight procedure. New connections to remote Bluetooth devices should not be attempted while discovery is in progress, and existing 
//              connections will experience limited bandwidth and high latency. Use cancelDiscovery() to cancel an ongoing discovery. Discovery is not managed by the Activity, 
//              but is run as a system service, so an application should always call cancelDiscovery() even if it did not directly request a discovery, just to be sure.
//              Device discovery will only find remote devices that are currently discoverable (inquiry scan enabled). Many Bluetooth devices are not discoverable by default, 
//              and need to be entered into a special mode.
//              If Bluetooth state is not STATE_ON, this API will return false. After turning on Bluetooth, wait for ACTION_STATE_CHANGED with STATE_ON to get the updated value.
            boolean result=bluetoothAdapter.startDiscovery();
            Log.i("l","is any connectable device?:"+result);
            
        }    
        
    };

    @Override
    protected void onDestroy() {
        super.onDestroy();
        this.unregisterReceiver(bluetoothReceiver);
    }
    
    
    
    private class BluetoothReceiver extends BroadcastReceiver{

        @Override
        public void onReceive(Context context, Intent intent) {
//            throw new UnsupportedOperationException("Not supported yet.");
            Log.i("l","received device");
            String action=intent.getAction();
            if(BluetoothDevice.ACTION_FOUND.equals(action)){
                BluetoothDevice device=intent.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE);
                Log.i("l","address:"+device.getAddress());
            }
        }
        
    }
    
    
    
    
}

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
      package="com.blue_tooth_test"
      android:versionCode="1"
      android:versionName="1.0">
          
    
    <uses-permission android:name="android.permission.BLUETOOTH"/>
    <uses-permission android:name="android.permission.BLUETOOTH_ADMIN"/>
          
          
    <application android:label="@string/app_name" >
        <activity android:name="BlueToothTest"
                  android:label="@string/app_name">
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />
                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
    </application>
</manifest> 

猜你喜欢

转载自julianjulian8.iteye.com/blog/1741634