2014-09-30 70 views
1

我目前通過科爾多瓦文檔閱讀和發現的基本輪廓如下:如何編寫一個android cordova插件,如果藍牙打開,將返回1,否則返回0?

package org.apache.cordova.plugin; 

import org.apache.cordova.api.CordovaPlugin; 
import org.apache.cordova.api.PluginResult; 
import org.json.JSONArray; 
import org.json.JSONException; 
import org.json.JSONObject; 

/** 
* This class echoes a string called from JavaScript. 
*/ 
public class Echo extends CordovaPlugin { 
    @Override 
    public boolean execute(String action, JSONArray args, CallbackContext callbackContext) throws JSONException { 
     if (action.equals("echo")) { 
      String message = args.getString(0); 
      this.echo(message, callbackContext); 
      return true; 
     } 
     return false; 
    } 

    private void echo(String message, CallbackContext callbackContext) { 
     if (message != null && message.length() > 0) { 
      callbackContext.success(message); 
     } else { 
      callbackContext.error("Expected one non-empty string argument."); 
     } 
    } 
} 

這使得有很大的意義,我的理解Java代碼如何被執行,調度信息返回給調用JavaScript的。

但是,我沒有看到我如何訪問android中的api,告訴我藍牙是打開還是關閉。我需要導入android包嗎?有關於此主題的文檔?

感謝所有幫助

回答

2

是的,你需要導入BluetoothManagerBluetoothAdapter

事情是這樣的:

import android.bluetooth.BluetoothManager; 
import android.bluetooth.BluetoothAdapter; 

... 

final BluetoothManager bluetoothManager = (BluetoothManager) getSystemService(Context.BLUETOOTH_SERVICE); 
private BluetoothAdapter mBluetoothAdapter; 

... 

if (!getPackageManager().hasSystemFeature(PackageManager.FEATURE_BLUETOOTH)) { 
    // BLUETOOTH is NOT SUPPORTED 
    //use PackageManager.FEATURE_BLUETOOTH_LE if you need bluetooth low energy 
    return false; 
} else { 
    mBluetoothAdapter = bluetoothManager.getAdapter(); 
    if (mBluetoothAdapter == null) { 
     // BLUETOOTH is NOT AVAILABLE 
     return false; 
    } else { 
     if (mBluetoothAdapter.isEnabled()) 
      // BLUETOOTH is TURNED ON 
      return true; 
     else 
      // BLUETOOTH is TURNED OFF 
      return false; 
    } 
} 

你可以更瞭解它:

+1

我剛剛編輯和改變'FEATURE_BLUETOOTH_LE'到'FEATURE_BLUETOOTH'來檢查標準藍牙,如果你需要低能量,儘管使用'FEATURE_BLUETOOTH_LE'常量 – benka 2014-09-30 15:05:44

相關問題