Android Bluetooth 4.0の開発詳細に基づいて、ハードウェアとの通信史上最も強力で、最も詳細です.

24000 ワード

1. , Android , :Service 。 4.0 , !  , , 。

public class BluetoothService extends Service {


	@Override
	public IBinder onBind(Intent intent) {
		// TODO Auto-generated method stub
		return null;
	}
}

, AndroidManifest , ( , )  

startService(new Intent(this,BluetoothService.class));

   


2. , (2B , ), onCreate , , : ,

    
    
, , , Activity

import android.annotation.SuppressLint;
import android.app.Service;
import android.bluetooth.BluetoothAdapter;
import android.bluetooth.BluetoothManager;
import android.content.Intent;
import android.os.IBinder;

public class BluetoothService extends Service {
	
	private BluetoothManager bluetoothManager;
	private BluetoothAdapter bluetoothAdapter;
	@Override
	public IBinder onBind(Intent intent) {
		// TODO Auto-generated method stub
		return null;
	}
	@SuppressLint("NewApi") 
	@Override
	public void onCreate() {
		// TODO Auto-generated method stub
		bluetoothManager=(BluetoothManager)getSystemService(Service.BLUETOOTH_SERVICE);
		
		//        API,  eclipse    , eclipse    
		bluetoothAdapter=bluetoothManager.getAdapter();
		
		//       ,            
		if (bluetoothAdapter == null || !bluetoothAdapter.isEnabled()) {
            Intent enableBtIntent = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);
            enableBtIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
            startActivity(enableBtIntent);
            return;
        }
		super.onCreate();
	}
}




3. , , , 。 , , , 。bluetoothAdapter.startLeScan(callback) callBack , BluetoothAdapter.LeScanCallback , , , objective-c ,objective-c , , startLeScan() LeScanCallback 。

import android.annotation.SuppressLint;
import android.annotation.TargetApi;
import android.app.Service;
import android.bluetooth.BluetoothAdapter;
import android.bluetooth.BluetoothDevice;
import android.bluetooth.BluetoothManager;
import android.content.Intent;
import android.os.Build;
import android.os.Handler;
import android.os.IBinder;

@TargetApi(Build.VERSION_CODES.JELLY_BEAN_MR2) public class BluetoothService extends Service {
	
	private BluetoothManager bluetoothManager;
	private BluetoothAdapter bluetoothAdapter;
	private Handler handler;
	 
	private boolean scanning;
	@Override
	public IBinder onBind(Intent intent) {
		// TODO Auto-generated method stub
		return null;
	}
	@SuppressLint("NewApi") 
	@Override
	public void onCreate() {
		// TODO Auto-generated method stub
		bluetoothManager=(BluetoothManager)getSystemService(Service.BLUETOOTH_SERVICE);
		
		//        API,  eclipse    , eclipse    
		bluetoothAdapter=bluetoothManager.getAdapter();
		
		//       ,            
		if (bluetoothAdapter == null || !bluetoothAdapter.isEnabled()) {
            Intent enableBtIntent = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);
            enableBtIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
            startActivity(enableBtIntent);
            return;
        }
		
		handler=new Handler();
		super.onCreate();
	}
	private void startFindDevice() {
		if (!bluetoothAdapter.isDiscovering()) {
			scanLeDevice(true);
		}
	}
	public void stopFindDevice() {
		scanLeDevice(false);
	}
	private void scanLeDevice(final boolean enable) {
		if (enable) {
			// Stops scanning after a pre-defined scan period.
			handler.postDelayed(new Runnable() {
				@Override
				public void run() {
					scanning = false;
					bluetoothAdapter.stopLeScan(leScanCallback);
				}
			}, 10000);
			scanning = true;
			bluetoothAdapter.startLeScan(leScanCallback);
		} else {
			scanning = false;
			bluetoothAdapter.stopLeScan(leScanCallback);
		}
	}
	
	BluetoothAdapter.LeScanCallback leScanCallback=new BluetoothAdapter.LeScanCallback(){
		@Override
		public void onLeScan(BluetoothDevice device, int rssi, byte[] arg2) {
			// TODO Auto-generated method stub
			//			device        
			//			rssi    rssi              
		}
	};
}
, ? , Activity , , , 。



4. , , , MAC , bluetoothDevice.connectGatt(context, autoConnect, callback), , false, true , BluetoothGattCallback( , ), rssi , , , gatt.readRemoteRssi() rssi ,

import java.util.HashMap;
import java.util.Map;
import java.util.Timer;
import java.util.TimerTask;


import android.annotation.SuppressLint;
import android.annotation.TargetApi;
import android.app.Service;
import android.bluetooth.BluetoothAdapter;
import android.bluetooth.BluetoothDevice;
import android.bluetooth.BluetoothGatt;
import android.bluetooth.BluetoothGattCallback;
import android.bluetooth.BluetoothManager;
import android.bluetooth.BluetoothProfile;
import android.content.Intent;
import android.os.Build;
import android.os.Handler;
import android.os.IBinder;
import android.util.Log;

@TargetApi(Build.VERSION_CODES.JELLY_BEAN_MR2) public class BluetoothService extends Service {
	
	private BluetoothManager bluetoothManager;
	private BluetoothAdapter bluetoothAdapter;
	private Handler handler;
	 
	private boolean scanning;
	
	private Map bluetoothGattMap;
	
	private Timer mRssiTimer;
	@Override
	public IBinder onBind(Intent intent) {
		// TODO Auto-generated method stub
		return null;
	}
	@SuppressLint("NewApi") 
	@Override
	public void onCreate() {
		// TODO Auto-generated method stub
		bluetoothManager=(BluetoothManager)getSystemService(Service.BLUETOOTH_SERVICE);
		
		//        API,  eclipse    , eclipse    
		bluetoothAdapter=bluetoothManager.getAdapter();
		
		//       ,            
		if (bluetoothAdapter == null || !bluetoothAdapter.isEnabled()) {
            Intent enableBtIntent = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);
            enableBtIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
            startActivity(enableBtIntent);
            return;
        }
		
		bluetoothGattMap=new HashMap();
		handler=new Handler();
		super.onCreate();
	}
	private void startFindDevice() {
		if (!bluetoothAdapter.isDiscovering()) {
			scanLeDevice(true);
		}
	}
	public void stopFindDevice() {
		scanLeDevice(false);
	}
	private void scanLeDevice(final boolean enable) {
		if (enable) {
			// Stops scanning after a pre-defined scan period.
			handler.postDelayed(new Runnable() {
				@Override
				public void run() {
					scanning = false;
					bluetoothAdapter.stopLeScan(leScanCallback);
				}
			}, 10000);
			scanning = true;
			bluetoothAdapter.startLeScan(leScanCallback);
		} else {
			scanning = false;
			bluetoothAdapter.stopLeScan(leScanCallback);
		}
	}
	
	BluetoothAdapter.LeScanCallback leScanCallback=new BluetoothAdapter.LeScanCallback(){
		@Override
		public void onLeScan(BluetoothDevice device, int rssi, byte[] arg2) {
			// TODO Auto-generated method stub
			//			device        
			//			rssi    rssi              
		}
	};
	
	private boolean connect(String address) {
		stopFindDevice();
		if ((bluetoothAdapter == null) || (address == null)) {
			return false;
		}
		BluetoothGatt gatt = (BluetoothGatt) bluetoothGattMap.get(address);
		if (gatt != null) {
			gatt.close();
		}
		BluetoothDevice device = bluetoothAdapter.getRemoteDevice(address);
		if (device == null) {
			return false;
		}
		gatt = device.connectGatt(this, false, bluetoothGattCallback);
		bluetoothGattMap.put(address, gatt);
		return true;
	}
	public boolean disconnect(String address) {
		BluetoothGatt gatt = (BluetoothGatt) bluetoothGattMap.get(address);
		if (gatt != null) {
			gatt.close();
		}
		bluetoothGattMap.remove(address);
		return true;
	}
	
	BluetoothGattCallback bluetoothGattCallback=new BluetoothGattCallback(){
		@Override
		public void onConnectionStateChange(final BluetoothGatt gatt,
				int status, int newState) {
			// TODO Auto-generated method stub
			super.onConnectionStateChange(gatt, status, newState);
			if (newState == BluetoothProfile.STATE_CONNECTED) {
				TimerTask task = new TimerTask() {
					@Override
					public void run() {
//						      ,     ,          
						gatt.readRemoteRssi();
					}
				};
				mRssiTimer = new Timer();
				mRssiTimer.schedule(task, 1000, 1000);
			} else if (newState == BluetoothProfile.STATE_DISCONNECTED) {
				if (mRssiTimer != null) {
					mRssiTimer.cancel();
				}
			}
		}
		
		@Override
		public void onReadRemoteRssi(BluetoothGatt gatt, int rssi, int status) {
			//      rssi  
		}
	};
}
rssi ,


5. , , gatt.discoverServices();

import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Timer;
import java.util.TimerTask;


import android.annotation.SuppressLint;
import android.annotation.TargetApi;
import android.app.Service;
import android.bluetooth.BluetoothAdapter;
import android.bluetooth.BluetoothDevice;
import android.bluetooth.BluetoothGatt;
import android.bluetooth.BluetoothGattCallback;
import android.bluetooth.BluetoothGattCharacteristic;
import android.bluetooth.BluetoothGattService;
import android.bluetooth.BluetoothManager;
import android.bluetooth.BluetoothProfile;
import android.content.Intent;
import android.os.Build;
import android.os.Handler;
import android.os.IBinder;

@TargetApi(Build.VERSION_CODES.JELLY_BEAN_MR2) public class BluetoothService extends Service {
	
	private BluetoothManager bluetoothManager;
	private BluetoothAdapter bluetoothAdapter;
	private Handler handler;
	 
	private boolean scanning;
	
	private Map bluetoothGattMap;
	
	private Timer mRssiTimer;
	@Override
	public IBinder onBind(Intent intent) {
		// TODO Auto-generated method stub
		return null;
	}
	@SuppressLint("NewApi") 
	@Override
	public void onCreate() {
		// TODO Auto-generated method stub
		bluetoothManager=(BluetoothManager)getSystemService(Service.BLUETOOTH_SERVICE);
		
		//        API,  eclipse    , eclipse    
		bluetoothAdapter=bluetoothManager.getAdapter();
		
		//       ,            
		if (bluetoothAdapter == null || !bluetoothAdapter.isEnabled()) {
            Intent enableBtIntent = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);
            enableBtIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
            startActivity(enableBtIntent);
            return;
        }
		
		bluetoothGattMap=new HashMap();
		handler=new Handler();
		super.onCreate();
	}
	private void startFindDevice() {
		if (!bluetoothAdapter.isDiscovering()) {
			scanLeDevice(true);
		}
	}
	public void stopFindDevice() {
		scanLeDevice(false);
	}
	private void scanLeDevice(final boolean enable) {
		if (enable) {
			// Stops scanning after a pre-defined scan period.
			handler.postDelayed(new Runnable() {
				@Override
				public void run() {
					scanning = false;
					bluetoothAdapter.stopLeScan(leScanCallback);
				}
			}, 10000);
			scanning = true;
			bluetoothAdapter.startLeScan(leScanCallback);
		} else {
			scanning = false;
			bluetoothAdapter.stopLeScan(leScanCallback);
		}
	}
	
	BluetoothAdapter.LeScanCallback leScanCallback=new BluetoothAdapter.LeScanCallback(){
		@Override
		public void onLeScan(BluetoothDevice device, int rssi, byte[] arg2) {
			// TODO Auto-generated method stub
			//			device        
			//			rssi    rssi              
		}
	};
	
	private boolean connect(String address) {
		stopFindDevice();
		if ((bluetoothAdapter == null) || (address == null)) {
			return false;
		}
		BluetoothGatt gatt = (BluetoothGatt) bluetoothGattMap.get(address);
		if (gatt != null) {
			gatt.close();
		}
		BluetoothDevice device = bluetoothAdapter.getRemoteDevice(address);
		if (device == null) {
			return false;
		}
		gatt = device.connectGatt(this, false, bluetoothGattCallback);
		bluetoothGattMap.put(address, gatt);
		return true;
	}
	public boolean disconnect(String address) {
		BluetoothGatt gatt = (BluetoothGatt) bluetoothGattMap.get(address);
		if (gatt != null) {
			gatt.close();
		}
		bluetoothGattMap.remove(address);
		return true;
	}
	
	BluetoothGattCallback bluetoothGattCallback=new BluetoothGattCallback(){
		@Override
		public void onConnectionStateChange(final BluetoothGatt gatt,
				int status, int newState) {
			// TODO Auto-generated method stub
			super.onConnectionStateChange(gatt, status, newState);
			if (newState == BluetoothProfile.STATE_CONNECTED) {
//				          
				gatt.discoverServices();
				TimerTask task = new TimerTask() {
					@Override
					public void run() {
//						      ,     ,          
						gatt.readRemoteRssi();
					}
				};
				mRssiTimer = new Timer();
				mRssiTimer.schedule(task, 1000, 1000);
			} else if (newState == BluetoothProfile.STATE_DISCONNECTED) {
				if (mRssiTimer != null) {
					mRssiTimer.cancel();
				}
			}
		}
		@Override
		public void onReadRemoteRssi(BluetoothGatt gatt, int rssi, int status) {
			//      rssi  
		}
		@Override
        // New services discovered
        public void onServicesDiscovered(BluetoothGatt gatt, int status) {
            if (status == BluetoothGatt.GATT_SUCCESS) {
            	showService(gatt.getServices());
            } else {
            }
        }
		
	};
	private void showService(List list){
		if (list == null) return;
		 for (BluetoothGattService gattService : list) {
			 List gattCharacteristics =gattService.getCharacteristics();
			  for ( final BluetoothGattCharacteristic  gattCharacteristic: gattCharacteristics) {
				  if(gattCharacteristic.getUuid().toString().equalsIgnoreCase("0000fff1-0000-1000-8000-00805f9b34fb")){
//					         
				  }
			}
			 
		 }
	}
}

, ,

6. , ....

import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Timer;
import java.util.TimerTask;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;


import android.annotation.SuppressLint;
import android.annotation.TargetApi;
import android.app.Service;
import android.bluetooth.BluetoothAdapter;
import android.bluetooth.BluetoothDevice;
import android.bluetooth.BluetoothGatt;
import android.bluetooth.BluetoothGattCallback;
import android.bluetooth.BluetoothGattCharacteristic;
import android.bluetooth.BluetoothGattService;
import android.bluetooth.BluetoothManager;
import android.bluetooth.BluetoothProfile;
import android.content.Intent;
import android.os.Build;
import android.os.Handler;
import android.os.IBinder;

@TargetApi(Build.VERSION_CODES.JELLY_BEAN_MR2) public class BluetoothService extends Service {
	
	private BluetoothManager bluetoothManager;
	private BluetoothAdapter bluetoothAdapter;
	private Handler handler;
	 
	private boolean scanning;
	
	private Map bluetoothGattMap;
	
	private Timer mRssiTimer;
	
	private ExecutorService readWriteWorker = Executors.newSingleThreadExecutor();
	private volatile BluetoothGattCharacteristic bluetoothGattCharacteristic;
	private volatile BluetoothGatt bluetoothGatt;
	
	@Override
	public IBinder onBind(Intent intent) {
		// TODO Auto-generated method stub
		return null;
	}
	@SuppressLint("NewApi") 
	@Override
	public void onCreate() {
		// TODO Auto-generated method stub
		bluetoothManager=(BluetoothManager)getSystemService(Service.BLUETOOTH_SERVICE);
		
		//        API,  eclipse    , eclipse    
		bluetoothAdapter=bluetoothManager.getAdapter();
		
		//       ,            
		if (bluetoothAdapter == null || !bluetoothAdapter.isEnabled()) {
            Intent enableBtIntent = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);
            enableBtIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
            startActivity(enableBtIntent);
            return;
        }
		
		bluetoothGattMap=new HashMap();
		handler=new Handler();
		super.onCreate();
	}
	private void startFindDevice() {
		if (!bluetoothAdapter.isDiscovering()) {
			scanLeDevice(true);
		}
	}
	public void stopFindDevice() {
		scanLeDevice(false);
	}
	private void scanLeDevice(final boolean enable) {
		if (enable) {
			// Stops scanning after a pre-defined scan period.
			handler.postDelayed(new Runnable() {
				@Override
				public void run() {
					scanning = false;
					bluetoothAdapter.stopLeScan(leScanCallback);
				}
			}, 10000);
			scanning = true;
			bluetoothAdapter.startLeScan(leScanCallback);
		} else {
			scanning = false;
			bluetoothAdapter.stopLeScan(leScanCallback);
		}
	}
	
	BluetoothAdapter.LeScanCallback leScanCallback=new BluetoothAdapter.LeScanCallback(){
		@Override
		public void onLeScan(BluetoothDevice device, int rssi, byte[] arg2) {
			// TODO Auto-generated method stub
			//			device        
			//			rssi    rssi              
		}
	};
	
	private boolean connect(String address) {
		stopFindDevice();
		if ((bluetoothAdapter == null) || (address == null)) {
			return false;
		}
		BluetoothGatt gatt = (BluetoothGatt) bluetoothGattMap.get(address);
		if (gatt != null) {
			gatt.close();
		}
		BluetoothDevice device = bluetoothAdapter.getRemoteDevice(address);
		if (device == null) {
			return false;
		}
		gatt = device.connectGatt(this, false, bluetoothGattCallback);
		bluetoothGattMap.put(address, gatt);
		return true;
	}
	public boolean disconnect(String address) {
		BluetoothGatt gatt = (BluetoothGatt) bluetoothGattMap.get(address);
		if (gatt != null) {
			gatt.close();
		}
		bluetoothGattMap.remove(address);
		return true;
	}
	
	BluetoothGattCallback bluetoothGattCallback=new BluetoothGattCallback(){
		@Override
		public void onConnectionStateChange(final BluetoothGatt gatt,
				int status, int newState) {
			// TODO Auto-generated method stub
			super.onConnectionStateChange(gatt, status, newState);
			if (newState == BluetoothProfile.STATE_CONNECTED) {
//				          
				gatt.discoverServices();
				TimerTask task = new TimerTask() {
					@Override
					public void run() {
//						      ,     ,          
						gatt.readRemoteRssi();
					}
				};
				mRssiTimer = new Timer();
				mRssiTimer.schedule(task, 1000, 1000);
			} else if (newState == BluetoothProfile.STATE_DISCONNECTED) {
				if (mRssiTimer != null) {
					mRssiTimer.cancel();
				}
			}
		}
		@Override
		public void onReadRemoteRssi(BluetoothGatt gatt, int rssi, int status) {
			//      rssi  
		}
		
		@Override
        // New services discovered
        public void onServicesDiscovered(BluetoothGatt gatt, int status) {
            if (status == BluetoothGatt.GATT_SUCCESS) {
            	bluetoothGatt=gatt;
            	showService(gatt.getServices());
            } else {
            }
        }
		
		
	};
	private void showService(List list){
		if (list == null) return;
		 for (BluetoothGattService gattService : list) {
			 List gattCharacteristics =gattService.getCharacteristics();
			  for ( final BluetoothGattCharacteristic  gattCharacteristic: gattCharacteristics) {
				  if(gattCharacteristic.getUuid().toString().equalsIgnoreCase("0000fff1-0000-1000-8000-00805f9b34fb")){
//					         
				  }
			}
			 
		 }
	}
	
	private void writeData(){
		 byte[] value = new byte[]{(byte) 0x01,(byte) 0x01,(byte) 0x01,(byte) 0x01};
		bluetoothGattCharacteristic.setValue(value);
		 bluetoothGatt.writeCharacteristic(bluetoothGattCharacteristic);
	}
	
}

, rssi ! , ?