當前位置:首頁 > 學習資源 > 講師博文丝瓜app > 智能手環客戶端詳細設計

智能手環客戶端詳細設計 時間:2018-10-28      來源:華清遠見

丝瓜app 1.1 客戶端簡介

丝瓜app 1.1.1 界面操作

進入頁面后,會自動進行掃描,以發現周圍可用藍牙設備。

在搜索藍牙設備的多層中,會出現圓環形進度條,當設定的搜索時間到了之后,或者我們選中了被掃描到的設備,該進度條消失,“停止掃描”轉換會“掃描”。

丝瓜app 點擊掃描到的設備進入控制設備控制頁面。

這個頁面是我們的主要控制界面,我們可以在這個界面看到手環為我們提供的一些數據。

丝瓜app 這個下拉菜單可以同過點擊也可以通過設備的menu按鍵獲得,主要用來控制計步器。

丝瓜app “斷開連接”的按鈕的作用是顯示現在設備的連接情況,如果不是已經連接了設備,那么可以看到“連接”按鈕,可以通過“連接”按鈕來實現和藍牙設備的連接,如果是已經連接了的設備,可以看到“斷開連接”,可以通過“斷開連接”來斷開和藍牙設備的連接。

設置時間按鈕,可以將我們的設備上的時間,同步到藍牙手環上。

1.1.2 工程結構

Src為java文件目錄。

Res為資源文件目錄。

AndroidManifest.xml為配置文件。

在src目錄下:

Acticity包中,是工程的兩個Activity活動相關的代碼。

丝瓜app Service包中,是工程啟動的服務相關代碼。

Tools包中,是工具類相關代碼。

丝瓜app UI包中,是自定義界面相關代碼。

在資源文件夾中,包含了Layout,values,Drawable等資源文件夾:

丝瓜app 其中layout中是布局文件,menu中,是菜單欄的布局文件,values中包括color,string,styles等設置。

1.2 代碼分析

1.2.1 界面代碼分析

本工程一共有兩個主要顯示界面,分別為掃描設備,和設備控制,通過兩個活動—Activity來進行設置與控制。

掃描-----界面ScanningActivity

丝瓜app 在onCreate中設定標題。

Java Code

public void onCreate(Bundle savedInstanceState){

getActionBar().setTitle(R.string.title_devices);

}

丝瓜app 在掃描的時候,menu顯示為“停止掃描”,并顯示圓環進度條以提醒等待;在掃描結束時,menu顯示為“掃描”。在界面中使用ListView展示掃描到的設備。

丝瓜app Java Code

/**

* 創建Menu菜單欄

*/

丝瓜app @Override

public boolean onCreateOptionsMenu(Menu menu)

{

丝瓜app getMenuInflater().inflate(R.menu.main, menu);

if (!mScanning)

{

menu.findItem(R.id.menu_stop).setVisible(false);

menu.findItem(R.id.menu_scan).setVisible(true);

丝瓜app menu.findItem(R.id.menu_refresh).setActionView(null);

} else{

menu.findItem(R.id.menu_stop).setVisible(true);

丝瓜app menu.findItem(R.id.menu_scan).setVisible(false);

丝瓜app menu.findItem(R.id.menu_refresh).setActionView(

R.layout.actionbar_indeterminate_progress);

}

return true;

}

/**

丝瓜app * Menu菜單欄被選擇時

*/

@Override

public boolean onOptionsItemSelected(MenuItem item)

{

switch (item.getItemId())

{

丝瓜app case R.id.menu_scan:

丝瓜app mLeDeviceListAdapter.clear();

scanLeDevice(true);

break;

丝瓜app case R.id.menu_stop:

scanLeDevice(false);

break;

}

丝瓜app return true;

}

ListView顯示掃描到的設備。

丝瓜app Java Code

@Override

protected void onResume(){

super.onResume();

if (!mBluetoothAdapter.isEnabled()){

if (!mBluetoothAdapter.isEnabled()){

Intent enableBtIntent = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);

丝瓜app startActivityForResult(enableBtIntent, REQUEST_ENABLE_BT);

}

}

丝瓜app mLeDeviceListAdapter = new LeDeviceListAdapter();

setListAdapter(mLeDeviceListAdapter);

scanLeDevice(true);

}

丝瓜app 點擊ListView中的設備跳轉到控制界面。

Java Code

丝瓜app @Override

protected void onListItemClick(ListView l, View v, int position, long id){

final BluetoothDevice device = mLeDeviceListAdapter.getDevice(position);

if (device == null) return;

final Intent intent = new Intent(this, DeviceControlActivity.class);

丝瓜app intent.putExtra(DeviceControlActivity.EXTRAS_DEVICE_NAME, device.getName());

丝瓜app intent.putExtra(DeviceControlActivity.EXTRAS_DEVICE_ADDRESS, device.getAddress());

if (mScanning) {

mBluetoothAdapter.stopLeScan(mLeScanCallback);

mScanning = false;

}

startActivity(intent);

}

設備控制-------界面DeviceControlActivity

在Activity中設置主界面:

丝瓜app Java Code

@Override

protected void onCreate(Bundle savedInstanceState){

丝瓜app super.onCreate(savedInstanceState);

setContentView(R.layout.activity_device_control);

initShow();

丝瓜app btnTime.setOnClickListener(this);

final Intent intent = getIntent();

丝瓜app mDeviceName = intent.getStringExtra(EXTRAS_DEVICE_NAME);

mDeviceAddress = intent.getStringExtra(EXTRAS_DEVICE_ADDRESS);

丝瓜app Toast.makeText(this, mDeviceAddress, Toast.LENGTH_SHORT).show();

丝瓜app getActionBar().setTitle(mDeviceName);

getActionBar().setDisplayHomeAsUpEnabled(true);

}

菜單欄包括兩部分,一部分是顯示“連接”或“斷開連接”,一部分是隱藏的用以對計步功能進行設置。

丝瓜app Java Code

丝瓜app @Override

public boolean onCreateOptionsMenu(Menu menu){

丝瓜app getMenuInflater().inflate(R.menu.device_control, menu);

if (connected) {

丝瓜app menu.findItem(R.id.menu_connect).setVisible(false);

丝瓜app menu.findItem(R.id.menu_disconnect).setVisible(true);

}else{

丝瓜app menu.findItem(R.id.menu_connect).setVisible(true);

menu.findItem(R.id.menu_disconnect).setVisible(false);

}

return true;

}

@Override

public boolean onOptionsItemSelected(MenuItem item){

丝瓜app int id = item.getItemId();

丝瓜app switch (id){

丝瓜app case R.id.setting_gogal:

showGogalDialog();

break;

case R.id.setting_reset:

showResetDialog();

break;

丝瓜app case R.id.setting_stop:

丝瓜app showStopDialog();

break;

case R.id.menu_connect:

丝瓜app mBleService.connect(mDeviceAddress);

丝瓜app return true;

case R.id.menu_disconnect:

丝瓜app mBleService.disconnect();

return true;

case android.R.id.home:

onBackPressed();

return true;

丝瓜app default:

break;

}

丝瓜app return super.onOptionsItemSelected(item);

}

丝瓜app 1.2.2 藍牙連接代碼分析

掃描

藍牙連接建立的過程中,首先要先掃描到設備。

丝瓜app 在ScanningActivity中:

Java Code

public class ScanningActivity extends ListActivity{

private LeDeviceListAdapter mLeDeviceListAdapter;

private BluetoothAdapter mBluetoothAdapter;

丝瓜app private boolean mScanning;

丝瓜app private Handler mHandler;

private static final int REQUEST_ENABLE_BT = 1;

// Stops scanning after 10 seconds.

private static final long SCAN_PERIOD = 10000;

丝瓜app public void onCreate(Bundle savedInstanceState) {

super.onCreate(savedInstanceState);

mHandler = new Handler();

//PackageManager.FEATURE_BLUETOOTH_LE

丝瓜app if (!getPackageManager().hasSystemFeature(PackageManager.FEATURE_BLUETOOTH_LE)){

Toast.makeText(this, R.string.ble_not_supported, Toast.LENGTH_SHORT).show();

finish();

}

//BluetoothManager

丝瓜app final BluetoothManager bluetoothManager =

丝瓜app (BluetoothManager) getSystemService(Context.BLUETOOTH_SERVICE);

mBluetoothAdapter = bluetoothManager.getAdapter();

//BluetoothAdapter

丝瓜app if (mBluetoothAdapter == null){

Toast.makeText(this, R.string.error_bluetooth_not_supported, Toast.LENGTH_SHORT).show();

finish();

return;

}

}

private void scanLeDevice(final boolean enable){

if (enable){

丝瓜app mHandler.postDelayed(new Runnable(){

@Override

public void run(){

丝瓜app mScanning = false;

丝瓜app mBluetoothAdapter.stopLeScan(mLeScanCallback);

invalidateOptionsMenu();

}

}, SCAN_PERIOD);

丝瓜app mScanning = true;

mBluetoothAdapter.startLeScan(mLeScanCallback);

}else{

mScanning = false;

丝瓜app mBluetoothAdapter.stopLeScan(mLeScanCallback);

}

invalidateOptionsMenu();

}

private BluetoothAdapter.LeScanCallback mLeScanCallback =

new BluetoothAdapter.LeScanCallback(){

@Override

public void onLeScan(final BluetoothDevice device, int rssi, byte[] scanRecord){

runOnUiThread(new Runnable(){

丝瓜app @Override

public void run(){

mLeDeviceListAdapter.addDevice(device);

mLeDeviceListAdapter.notifyDataSetChanged();

}

});

}

};

}

連接藍牙

在掃描結束的時候,點擊ListView上的設備名稱的時候,將設備MAC通過Intent傳遞給DeviceControlActivity,在控制頁面啟動BLEService服務,控制設備連接。

Java Code

public class DeviceControlActivity extends Activity implements View.OnClickListener

{

private final String TAG = "Device";

private final Double G = 9.8;

public static final String EXTRAS_DEVICE_NAME = "DEVICE_NAME";

public static final String EXTRAS_DEVICE_ADDRESS = "DEVICE_ADDRESS";

private static String UUID_date = "0000180f-0000-1000-8000-00805f9b34fb";

private static String UUID_D = "00002a19-0000-1000-8000-00805f9b34fb";

丝瓜app private String UUID_write = "00001802-0000-1000-8000-00805f9b34fb";

private String UUID_W = "00002a06-0000-1000-8000-00805f9b34fb";

private Phone mPhone;

private BLEService mBleService;

丝瓜app private String mDeviceAddress;

private String mDeviceName;

private int xBefore, yBefore, zBefore;

丝瓜app private CircleBar mCircleBar;

private Button btnTime;

丝瓜app private TextView txvX, txvY, txvZ, txvPower;

private EditText gogalInput;

丝瓜app private boolean connected = false;

private boolean first = true;

private BluetoothGattCharacteristic mNotifyCharacteristic;

丝瓜app protected void onCreate(Bundle savedInstanceState){

//...

super.onCreate(savedInstanceState);

//bindService啟動服務,注冊廣播接收器實現服務與活動之間的通信

Intent gattIntent = new Intent(this, BLEService.class);

bindService(gattIntent, mServiceConnection, BIND_AUTO_CREATE);

registerReceiver(mGattUpdateReceiver, makeGattUpdateIntentFilter());

//實例化一個電話模型。

mPhone = new Phone(this);

}

@Override

丝瓜app protected void onResume(){

super.onResume();

registerReceiver(mGattUpdateReceiver, makeGattUpdateIntentFilter());

丝瓜app if (mBleService != null){

丝瓜app final boolean result = mBleService.connect(mDeviceAddress);

丝瓜app Log.d(TAG, "Connect request result=" + result);

}

}

//服務連接

private final ServiceConnection mServiceConnection = new ServiceConnection(){

@Override

public void onServiceDisconnected(ComponentName name){

}

@Override

public void onServiceConnected(ComponentName name, IBinder service){

mBleService = ((BLEService.LocalBinder) service).getService();

if (!mBleService.initialize()){

丝瓜app Log.e(TAG, "unable to initilize Bluetooth Service");

丝瓜app finish();

}

丝瓜app mBleService.connect(mDeviceAddress);

}

};

}

丝瓜app BLEService服務代碼如下:

Java Code

public class BLEService extends Service{

private BluetoothManager mBluetoothManager;

丝瓜app private BluetoothAdapter mBluetoothAdapter;

private String mBluetoothDeviceAddress;

public BluetoothGatt mBluetoothGatt;

public final static String ACTION_TIME_SETTING = "com.farsight.bluetooth.le.ACTION_TIME_SETTING";

public final static String ACTION_GATT_CONNECTED = "com.farsight.bluetooth.le.ACTION_GATT_CONNECTED";

丝瓜app public final static String ACTION_GATT_DISCONNECTED = "com.farsight.bluetooth.le.ACTION_GATT_DISCONNECTED";

丝瓜app public final static String ACTION_GATT_SERVICES_DISCOVERED = "com.farsight.bluetooth.le.ACTION_GATT_SERVICES_DISCOVERED";

丝瓜app public final static String ACTION_DATA_AVAILABLE = "com.farsight.bluetooth.le.ACTION_DATA_AVAILABLE";

丝瓜app public final static String EXTRA_DATA = "com.farsight.bluetooth.le.EXTRA_DATA";

丝瓜app public final static UUID UUID_FARSIGHT_SMART_WRIST = UUID.fromString(GattAttributes.FARSIGHT_SMART_WRIST);

/**

* 回調函數

*/

丝瓜app private final BluetoothGattCallback mGattCallback = new BluetoothGattCallback(){

@Override

丝瓜app public void onConnectionStateChange(BluetoothGatt gatt, int status, int newState){

丝瓜app String intentAction;

丝瓜app if (newState == BluetoothProfile.STATE_CONNECTED){

mBluetoothGatt.getServices();

intentAction = ACTION_GATT_CONNECTED;

mConnectionState = STATE_CONNECTED;

broadcastUpdate(intentAction);

Log.i(TAG, "Connected to GATT server.");

// Attempts to discover services after successful connection.

Log.i(TAG, "Attempting to start service discovery:" + mBluetoothGatt.discoverServices());

}else if (newState == BluetoothProfile.STATE_DISCONNECTED){

intentAction = ACTION_GATT_DISCONNECTED;

mConnectionState = STATE_DISCONNECTED;

丝瓜app Log.i(TAG, "Disconnected from GATT server.");

broadcastUpdate(intentAction);

}

}

//發現新服務

@Override

丝瓜app public void onServicesDiscovered(BluetoothGatt gatt, int status){

if (status == BluetoothGatt.GATT_SUCCESS){

丝瓜app broadcastUpdate(ACTION_GATT_SERVICES_DISCOVERED);

}else{

丝瓜app Log.w("DSTTTTTTTTT", "onServicesDiscovered received: " + status);

}

}

丝瓜app //讀到特征設備

丝瓜app @Override

public void onCharacteristicRead(BluetoothGatt gatt, BluetoothGattCharacteristic characteristic, int status){

丝瓜app if (status == BluetoothGatt.GATT_SUCCESS){

broadcastUpdate(ACTION_DATA_AVAILABLE, characteristic);

}

}

@Override

public void onCharacteristicChanged(BluetoothGatt gatt, BluetoothGattCharacteristic characteristic){

丝瓜app broadcastUpdate(ACTION_DATA_AVAILABLE, characteristic);

}

};

/**

丝瓜app * 通過廣播發送數據

*/

private void broadcastUpdate(final String action){

final Intent intent = new Intent(action);

sendBroadcast(intent);

}

/**

丝瓜app * 通過廣播發送數據

*/

丝瓜app private void broadcastUpdate(final String action, final BluetoothGattCharacteristic characteristic){

丝瓜app final Intent intent = new Intent(action);

丝瓜app // For all profiles, writes the data formatted in HEX.

丝瓜app final byte[] data = characteristic.getValue();

Log.d(TAG, data.length + "");

if (data != null && data.length > 0){

final StringBuilder stringBuilder = new StringBuilder(data.length);

丝瓜app for (byte byteChar : data)

stringBuilder.append(String.format("%02X ", byteChar));

// new String(data) + "\n" +

intent.putExtra(EXTRA_DATA, stringBuilder.toString());

}

丝瓜app sendBroadcast(intent);

}

if (mBluetoothManager == null){

丝瓜app mBluetoothManager = (BluetoothManager) getSystemService(Context.BLUETOOTH_SERVICE);

丝瓜app if (mBluetoothManager == null){

Log.e(TAG, "Unable to initialize BluetoothManager.");

return false;

}

}

丝瓜app mBluetoothAdapter = mBluetoothManager.getAdapter();

丝瓜app if (mBluetoothAdapter == null){

Log.e(TAG, "Unable to obtain a BluetoothAdapter.");

return false;

}

return true;

}

/**

* 連接

*/

丝瓜app public boolean connect(final String address){

if (mBluetoothAdapter == null || address == null){

Log.w(TAG, "BluetoothAdapter not initialized or unspecified address.");

return false;

}

if (mBluetoothDeviceAddress != null && address.equals(mBluetoothDeviceAddress) && mBluetoothGatt != null){

Log.d(TAG, "Trying to use an existing mBluetoothGatt for connection.");

if (mBluetoothGatt.connect()){

mConnectionState = STATE_CONNECTING;

return true;

}else{

丝瓜app return false;

}

}

final BluetoothDevice device = mBluetoothAdapter.getRemoteDevice(address);

if (device == null){

Log.w(TAG, "Device not found. Unable to connect.");

return false;

}

mBluetoothGatt = device.connectGatt(this, false, mGattCallback);

丝瓜app Log.d(TAG, "Trying to create a new connection.");

丝瓜app mBluetoothDeviceAddress = address;

mConnectionState = STATE_CONNECTING;

丝瓜app return true;

}

/**

* 可通知

*/

public void setCharacteristicNotification(BluetoothGattCharacteristic characteristic, boolean enabled){

if (mBluetoothAdapter == null || mBluetoothGatt == null){

Log.w(TAG, "BluetoothAdapter not initialized");

return;

}

丝瓜app mBluetoothGatt.setCharacteristicNotification(characteristic, enabled);

丝瓜app if (UUID_FARSIGHT_SMART_WRIST.equals(characteristic.getUuid())){

丝瓜app BluetoothGattDescriptor descriptor = characteristic

.getDescriptor(UUID.fromString(GattAttributes.CLIENT_CHARACTERISTIC_CONFIG));

丝瓜app descriptor.setValue(BluetoothGattDescriptor.ENABLE_NOTIFICATION_VALUE);

丝瓜app mBluetoothGatt.writeDescriptor(descriptor);

}

}

/**

* 所有服務列表

*/

丝瓜app public List getSupportedGattServices(){

if (mBluetoothGatt == null)

return null;

return mBluetoothGatt.getServices();

}

丝瓜app 1.2.3 信號處理

從藍牙設備接收數據

這里我們使用設備接收來自藍牙的通知即Notification信號,所以我們需要讓我們的設備讀取相應特征值的可通知信號。

丝瓜app 在BLEService中:

Java Code

public void setCharacteristicNotification(BluetoothGattCharacteristic characteristic, boolean enabled)

{

if (mBluetoothAdapter == null || mBluetoothGatt == null)

{

Log.w(TAG, "BluetoothAdapter not initialized");

return;

}

mBluetoothGatt.setCharacteristicNotification(characteristic, enabled);

丝瓜app if (UUID_FARSIGHT_SMART_WRIST.equals(characteristic.getUuid()))

{

丝瓜app BluetoothGattDescriptor descriptor = characteristic

丝瓜app .getDescriptor(UUID.fromString(GattAttributes.CLIENT_CHARACTERISTIC_CONFIG));

descriptor.setValue(BluetoothGattDescriptor.ENABLE_NOTIFICATION_VALUE);

mBluetoothGatt.writeDescriptor(descriptor);

}

}

在DeviceControlActivity中,通過廣播接收器接收來自BLEService中的廣播發出的信號:

Java Code

private final BroadcastReceiver mGattUpdateReceiver = new BroadcastReceiver(){

@Override

public void onReceive(Context context, Intent intent)

{

final String action = intent.getAction();

丝瓜app Log.d(TAG, action);

if (BLEService.ACTION_GATT_CONNECTED.equals(action))

{

connected = true;

丝瓜app invalidateOptionsMenu();

}

else if (BLEService.ACTION_GATT_DISCONNECTED.equals(action))

{

丝瓜app connected = false;

丝瓜app invalidateOptionsMenu();

}

丝瓜app else if (BLEService.ACTION_GATT_SERVICES_DISCOVERED.equals(action))

{

丝瓜app Log.d(TAG, "received Discoveryed");

if (first)

{

丝瓜app first = false;

}

getcharacteristic(mBleService.getSupportedGattServices());

}

else if (BLEService.ACTION_DATA_AVAILABLE.equals(action))

{

String data = intent.getStringExtra(BLEService.EXTRA_DATA);

setTribleAndPower(data);

getcharacteristic(mBleService.getSupportedGattServices());

丝瓜app Log.d("DATAIS", data);

}

}

};

丝瓜app 當發現服務的時候,調用getcharacteristic(mBleService.getSupportedGattServices())以判斷特征值是否是我們需要的。

Java Code

丝瓜app private void getcharacteristic(List gattServices){

丝瓜app String uuid = null;

Log.d(TAG, "++++++++++++++++++++++++++++++++++++++++++++");

丝瓜app for (BluetoothGattService gattService : gattServices) {

uuid = gattService.getUuid().toString();

Log.d(TAG, uuid);

if (uuid.equalsIgnoreCase(UUID_date)) {

丝瓜app List gattCharacteristics = gattService.getCharacteristics();

for (BluetoothGattCharacteristic gattCharacteristic : gattCharacteristics)

uuid = gattCharacteristic.getUuid().toString();

丝瓜app Log.d(TAG, uuid + "characteristic");

if (uuid.equalsIgnoreCase(UUID_D)) {

final int charaProp = gattCharacteristic.getProperties();

丝瓜app if ((charaProp | BluetoothGattCharacteristic.PROPERTY_READ) > 0) {

// If there is an active notification on a

// characteristic, clear

if (mNotifyCharacteristic != null) {

mBleService.setCharacteristicNotification(mNotifyCharacteristic, false);

mNotifyCharacteristic = null;

}

mBleService.readCharacteristic(gattCharacteristic);

}

if ((charaProp | BluetoothGattCharacteristic.PROPERTY_NOTIFY) > 0) {

丝瓜app mNotifyCharacteristic = gattCharacteristic;

mBleService.setCharacteristicNotification(gattCharacteristic, true); }

}else{

continue;

}

}

}

}

當接收到ACTION_DATA_AVAILABLE廣播的時候,讀出廣播中的數據,并通過數據對界面進行操作。

向藍牙設備發送數據

丝瓜app 電話狀態監聽類代碼:

Java Code

package com.farsight.lastsmartwrist.tools;

import android.annotation.SuppressLint;

import android.content.Context;

import android.database.ContentObserver;

丝瓜app import android.database.Cursor;

丝瓜app import android.net.Uri;

丝瓜app import android.os.Handler;

import android.provider.CallLog;

import android.provider.CallLog.Calls;

import android.telephony.PhoneStateListener;

import android.telephony.TelephonyManager;

public class Phone

{

丝瓜app private boolean first = true;

public byte msgCount = 0;

public byte phoneCount = 0;

private Context context = null;

public BufferTool cmdBuf = null;

public Phone(Context con)

{

context = con;

cmdBuf = new BufferTool(1024);

TelephonyManager teleMgr = (TelephonyManager) context

丝瓜app .getSystemService(Context.TELEPHONY_SERVICE);

丝瓜app teleMgr.listen(new MyPhoneStateListener(),

丝瓜app PhoneStateListener.LISTEN_CALL_STATE);

丝瓜app registerObserver();

丝瓜app init();

}

// 剛開始就發送現有的數據

丝瓜app void init()

{

phoneCount = (byte) readMissCall();

cmdBuf.addBuffer((byte) 'a', 1, phoneCount);

msgCount = (byte) getNewSmsCount();

丝瓜app cmdBuf.addBuffer((byte) 'c', 1, msgCount);

}

public void Quit()

{

unregisterObserver();

}

// 監聽來電

丝瓜app class MyPhoneStateListener extends PhoneStateListener

{

丝瓜app @Override

public void onCallStateChanged(int state, String incomingNumber)

{

if (state == TelephonyManager.CALL_STATE_RINGING)

{

cmdBuf.addBuffer((byte) 'b', incomingNumber.getBytes().length,

incomingNumber.getBytes());

}

else if (state == TelephonyManager.CALL_STATE_IDLE)

{

丝瓜app int tmp = readMissCall();

丝瓜app if (first == true)

{

丝瓜app phoneCount = (byte) (tmp);

丝瓜app first = false;

}

else

{

phoneCount = (byte) (tmp + 1);

}

cmdBuf.addBuffer((byte) 'a', 1, phoneCount);

}

}

}

// 監聽短信

public ContentObserver newMmsContentObserver = new ContentObserver(

丝瓜app new Handler())

{

丝瓜app public void onChange(boolean selfChange)

{

丝瓜app if (cmdBuf.getVolume() == 0)

{

cmdBuf.addBuffer((byte) 'd', 1, (byte) (getNewSmsCount() + 1));// 發送短信通知

}

}

};

// 注冊監聽者

@SuppressLint("NewApi")

丝瓜app public void registerObserver()

{

unregisterObserver();

context.getContentResolver().registerContentObserver(

丝瓜app Uri.parse("content://sms"), true, newMmsContentObserver);

}

// 取消注冊

丝瓜app public void unregisterObserver()

{

try

{

丝瓜app if (newMmsContentObserver != null)

{

context.getContentResolver().unregisterContentObserver(

丝瓜app newMmsContentObserver);

}

}

catch (Exception e)

{

}

}

丝瓜app // 獲得短信條數

丝瓜app public int getNewSmsCount()

{

int result = 0;

丝瓜app Cursor csr = context.getContentResolver().query(

丝瓜app Uri.parse("content://sms"), null, "type = 1 and read = 0",

null, null);

丝瓜app if (csr != null)

{

result = csr.getCount();

丝瓜app csr.close();

丝瓜app return result;

}

else

{

丝瓜app return 0;

}

}

// 獲得電話個數

public int readMissCall()

{

int result = 0;

丝瓜app Cursor cursor = context.getContentResolver().query(

CallLog.Calls.CONTENT_URI, new String[] { Calls.TYPE },

" type=? and new=?",

new String[] { Calls.MISSED_TYPE + "", "1" }, "date desc");

if (cursor != null)

{

丝瓜app result = cursor.getCount();

cursor.close();

丝瓜app return result;

}

else

{

丝瓜app return 0;

}

}

}

要發送的數據通過BuffTools來設置:

丝瓜app Java Code

package com.farsight.lastsmartwrist.tools;

丝瓜app mport java.util.Collection;

import java.util.HashMap;

丝瓜app import android.annotation.SuppressLint;

public class BufferTool

{

private int volume = 0;

丝瓜app private HashMap buffer = null;

丝瓜app @SuppressLint("UseSparseArrays")

public BufferTool(int dataVolume)

{

丝瓜app volume = dataVolume;

buffer = new HashMap(volume);

}

丝瓜app public synchronized Boolean addBuffer(byte[] data)

{

if (data != null)

{

if (buffer.size() < volume)

{

buffer.put(buffer.size(), data);

return true;

}

else

{

return false;

}

}

else

{

丝瓜app return false;

}

}

public synchronized Boolean addBuffer(int kind, int num, int msg)

{

byte[] cmdd = { (byte) kind, (byte) num, (byte) msg };

丝瓜app if (buffer.size() < volume)

}

else

{

return false;

}

}

public synchronized Boolean addBuffer(int kind, int num, byte[] msg)

{

byte[] cmdd = new byte[msg.length + 2];

cmdd[0] = (byte) kind;

cmdd[1] = (byte) num;

丝瓜app System.arraycopy(msg, 0, cmdd, 2, msg.length);

丝瓜app if (buffer.size() < volume)

{

buffer.put(buffer.size(), cmdd);

return true;

}

else

{

return false;

}

}

丝瓜app public synchronized Boolean addBuffer(int cmd)

{

byte[] cmdd = { (byte) cmd };

丝瓜app if (buffer.size() < volume)

{

丝瓜app buffer.put(buffer.size(), cmdd);

丝瓜app return true;

}

else

{

return false;

}

}

public synchronized byte[] getBuffer()

{

丝瓜app byte[] data = null;

if (buffer.size() > 0)

{

data = buffer.get(buffer.size() - 1);

buffer.remove(buffer.size() - 1);

}

else

{

}

return data;

}

public synchronized byte[][] getBuffer(int num)

{

丝瓜app byte[][] data = new byte[num][];

for (int i = 0; i < num; i++)

{

丝瓜app if (buffer.size() > 0)

{

data[i] = buffer.get(0);

丝瓜app buffer.remove(0);

}

else

{

data[i] = null;

break;

}

}

丝瓜app return data;

}

public synchronized byte[][] getAllBuffer()

{

if (buffer.isEmpty() == false)

{

丝瓜app int num = 0;

Collection Col = buffer.values();

丝瓜app int vol = Col.size();

byte[][] data = new byte[vol + 1][];

for (byte[] i : Col)

{

data[num] = i;

num++;

}

丝瓜app data[num] = null;

丝瓜app buffer.clear();

丝瓜app return data;

}

else

{

return null;

}

}

丝瓜app public synchronized int getVolume()

{

丝瓜app return buffer.size();

}

}

和接收數據時不一樣的是,我們在發現服務和特征值之后,就應該去查看Phone實例中是否有未傳輸出去的數據,如果有,而且服務和特征值是我們要發送的設備的話,就要進行數據傳送。

Java Code

丝瓜app private void getcharacteristic(List gattServices)

{

String uuid = null;

丝瓜app Log.d(TAG, "++++++++++++++++++++++++++++++++++++++++++++");

丝瓜app for (BluetoothGattService gattService : gattServices)

{

丝瓜app uuid = gattService.getUuid().toString();

丝瓜app Log.d(TAG, uuid);

if (uuid.equalsIgnoreCase(UUID_date))

{

。。。。

}

else if (uuid.equals(UUID_write))

{

List gattCharacteristics = gattService.getCharacteristics();

for (BluetoothGattCharacteristic bluetoothGattCharacteristic : gattCharacteristics)

{

丝瓜app uuid = bluetoothGattCharacteristic.getUuid().toString();

final BluetoothGattCharacteristic inBluetoothGattCharacteristic = bluetoothGattCharacteristic;

丝瓜app if (uuid.equals(UUID_W))

{

丝瓜app byte[] datas = null;

丝瓜app if (0 != mPhone.cmdBuf.getVolume())

{

}

while (null != (datas = mPhone.cmdBuf.getBuffer()))

{

丝瓜app inBluetoothGattCharacteristic.setValue(datas);

mBleService.mBluetoothGatt.writeCharacteristic(inBluetoothGattCharacteristic);

}

}

else

{

丝瓜app continue;

}

}

}

else

{

continue;

}

}

}

上一篇:安卓開發中實用的例子

下一篇:智能手環客戶端詳細設計

丝瓜app戳我查看2019年嵌入式每月就業風云榜

丝瓜app點我了解華清遠見高校學霸學習秘籍

丝瓜app猜你關心企業是如何評價華清學員的

干貨分享
相關新聞
前臺專線:010-82525158 企業培訓洽談專線:010-82525379 院校合作洽談專線:010-82525379 Copyright © 2004-2019 丝瓜app 版權所有 ,京ICP備16055225號,京公海網安備11010802025203號