2015-05-25 255 views

回答

0

要確定藍牙是否可發現,我會檢查適配器上的當前狀態getState()。

MainActivity getState();看到

public class MainActivity extends AppCompatActivity { 
    BluetoothAdapter bluetoothAdapter = BluetoothAdapter.getDefaultAdapter(); 
    @Override 
    protected void onCreate(Bundle savedInstanceState) { 
     super.onCreate(savedInstanceState); 
     setContentView(R.layout.activity_main); 
     if (!BluetoothConnection.canDeviceConnectViaBluetooth(bluetoothAdapter, this)) { 
      Toast.makeText(this, "Not Compatible", Toast.LENGTH_SHORT).show(); 
     } else { 
      if (BluetoothConnection.isBluetoothAdapterEnabled(bluetoothAdapter, this)) { 
       int isBlueToothDiscoverable = bluetoothAdapter.getState(); 
       switch (isBlueToothDiscoverable) { 
        case BluetoothAdapter.STATE_OFF: 
         Toast.makeText(this, "STATE_OFF", Toast.LENGTH_SHORT).show(); // Not discoverable 
         break; 
        case BluetoothAdapter.STATE_TURNING_ON: 
         Toast.makeText(this, "STATE_TURNING_ON", Toast.LENGTH_SHORT).show(); // Maybe discoverable 
         break; 
        case BluetoothAdapter.STATE_ON: 
         Toast.makeText(this, "STATE_ON", Toast.LENGTH_SHORT).show(); // Discoverable 
         break; 
        case BluetoothAdapter.STATE_TURNING_OFF: 
         Toast.makeText(this, "STATE_TURNING_OFF", Toast.LENGTH_SHORT).show(); // Not discoverable 
         break; 
        default: 
         break; 
       } 
      } 
     } 
    } 
} 

檢查設備是否兼容藍牙

public class BluetoothConnection { 
    public final static int REQUEST_ENABLE_BT = 1; 

    public static boolean canDeviceConnectViaBluetooth(BluetoothAdapter bluetoothAdapter, Activity activity) { 
     if (bluetoothAdapter == null) { 
      Log.e("DEVICE_COMPATIBLE", "FALSE"); 
      return false; 
     } 
     return true; 
    } 

    public static boolean isBluetoothAdapterEnabled(BluetoothAdapter bluetoothAdapter, Activity activity) { 
     if (!bluetoothAdapter.isEnabled()) { 
      Intent enableBtIntent = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE); 
      activity.startActivityForResult(enableBtIntent, REQUEST_ENABLE_BT); 
      Log.e("IS_BLUETOOTH_ON", "FALSE"); 
      return false; 
     } else { 
      return true; 
     } 
    } 
}