Android开发蓝牙和震动器操作

打开蓝牙或者判断设备是否支持蓝牙首先要加入权限

    <!--蓝牙权限-->
    <uses-permission android:name="android.permission.BLUETOOTH" />
    <uses-permission android:name="android.permission.BLUETOOTH_ADMIN"/>

判断并打开蓝牙

        BluetoothAdapter myBluetooth = BluetoothAdapter.getDefaultAdapter();
        if (myBluetooth == null) {
            Toast.makeText(this, "您的设备不支持蓝牙", Toast.LENGTH_SHORT).show();
        } else {
            if (!myBluetooth.isEnabled()) {//如果蓝牙没打开
                Intent enableIntent = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);
                startActivity(enableIntent);
            } else {
                Toast.makeText(this, "蓝牙已打开", Toast.LENGTH_SHORT).show();
            }
        }

开启手机震动需要加入震动权限

    <!--震动权限-->
    <uses-permission android:name="android.permission.VIBRATE" />

开启与取消震动

    private Vibrator myVib;

    public void tv(View view) {
        myVib = (Vibrator) getSystemService(Context.VIBRATOR_SERVICE);
        //震动时间
        //myVib.vibrate(2000);
        //节奏震动:0-n依次为静止时间,震动时间,静止时间,震动时间......依次类推 例如SOS求助震动模式(三短三长三短法则)
        long[] pattern = {500, 500, 500, 500, 500, 500, 500, 1000, 500, 1000, 500, 1000, 500, 500, 500, 500, 500, 500, 3000};
        //vibrate()方法的第二个参数指定pattern数组中表示重复起始点的元素下标。如将其设为-1,表示不对模式做任何重复
        myVib.vibrate(pattern, 1);
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        //取消震动
        myVib.cancel();
    }

猜你喜欢

转载自blog.csdn.net/juer2017/article/details/117816915
今日推荐