本文主要是介绍android bluetooth api,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!
蓝牙:
1,是目前使用最广泛的无线通讯协议
2.主要针对短距离通讯(10M)
3.常用于连接耳机,鼠标,和移动通读设备等
与蓝牙相关的API
1.BluetoothAdapter
这类的对象代表了本地的蓝牙适配器
2.BluetoothDevice:
代表了一个远程的Bluetooth设备
扫描已配对的蓝牙设备
在AndroidManifest.xml声明蓝牙权限:
<uses-permission
android:name="android.permission.BLUETOOTH">
</uses-permission>
例子:
package com.example.bluetoothtest.bluetoothtest;import android.app.Activity;
import android.bluetooth.BluetoothAdapter;
import android.bluetooth.BluetoothDevice;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.media.AudioManager;
import android.media.MediaRecorder;
import android.os.Bundle;
import android.os.Environment;
import android.os.Handler;
import android.os.Message;
import android.os.StatFs;
import android.provider.MediaStore;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
import android.widget.Toast;import java.io.File;
import java.io.IOException;
import java.util.Set;public class MainActivity extends Activity {private static String mFileName = null;private static String TAG = "BT_android";MediaRecorder mMediaRecorder;private int record_state;private static int ENABLE_BT = 1;private static int DISABLE_BT = 0;/*tmp file front*/private String strTempFile = "recaudio_";/*record audio*/private File mRecordAudioFile;private File mRecordAudioPath;private AudioManager mAudioManager;private Handler mHandler = new Handler(){@Overridepublic void handleMessage(Message msg) {super.handleMessage(msg);switch (msg.what){case 1:Log.d(TAG,"1-----------");Toast.makeText(getApplication(),"1111111",Toast.LENGTH_LONG).show();break;case 0:Log.d(TAG,"0-----------");Toast.makeText(getApplication(),"000000",Toast.LENGTH_LONG).show();break;}}};@Overrideprotected void onCreate(Bundle savedInstanceState) {super.onCreate(savedInstanceState);setContentView(R.layout.activity_main);mMediaRecorder = new MediaRecorder();final Button startBT = (Button)findViewById(R.id.mybluetooth) ;Button stopBT = (Button)findViewById(R.id.stopBT);Button unpairBT = (Button)findViewById(R.id.unpairDevice);Button startRecord = (Button)findViewById(R.id.startRecord);Button stopRecord = (Button)findViewById(R.id.stopRecord);Button visableBT = (Button)findViewById(R.id.visableBT);final TextView stateBT = (TextView)findViewById(R.id.stateBT);final TextView bounddeviceBT = (TextView)findViewById(R.id.bounddeviceBT);mAudioManager = (AudioManager)getSystemService(Context.AUDIO_SERVICE);/*mMediaRecorder = new MediaRecorder();*/final BluetoothAdapter adapter = BluetoothAdapter.getDefaultAdapter();if (Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)){/*get sdcard's path*/mRecordAudioPath = Environment.getExternalStorageDirectory();}else{Toast.makeText(getApplicationContext(),"no sdcard in box",Toast.LENGTH_LONG);}startBT.setOnClickListener(new View.OnClickListener() {@Overridepublic void onClick(View view) {adapter.enable();Log.d(TAG,"enable BT");//打开本机的蓝牙发现功能(默认打开120秒,可以将时间最多延长至300秒)/* Intent discoveryIntent = new Intent(BluetoothAdapter.ACTION_REQUEST_DISCOVERABLE);discoveryIntent.putExtra(BluetoothAdapter.EXTRA_DISCOVERABLE_DURATION, 300);//设置持续时间(最多300秒)*//*取到扫描到的可见蓝牙设备*/registerReceiver(new BroadcastReceiver() {@Overridepublic void onReceive(Context context, Intent intent) {BluetoothDevice mdevBT = intent.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE);Log.e(TAG,mdevBT.getName() + mdevBT.getAddress());}},new IntentFilter(BluetoothDevice.ACTION_FOUND));adapter.startDiscovery();/*得到适配器中已配对过的设备信息*/Set<BluetoothDevice> mPairDevice = adapter.getBondedDevices();if (mPairDevice.size()> 0)for (BluetoothDevice mBtDevice:mPairDevice){bounddeviceBT.append("\nName:" + mBtDevice.getName() + "\tMac:" + mBtDevice.getAddress() + "\n");}Toast.makeText(getApplicationContext(),"scanning-----",Toast.LENGTH_LONG).show();Message mMessage = new Message();mMessage.what = 1;mHandler.sendMessage(mMessage);if (adapter.getState() == adapter.STATE_ON){stateBT.setText("enable BT");}else{stateBT.setText("disable BT");}}});//关闭蓝牙stopBT.setOnClickListener(new View.OnClickListener() {@Overridepublic void onClick(View view) {adapter.disable();Log.d(TAG,"state:"+ adapter.getState());if (adapter.getState() == adapter.STATE_ON){stateBT.setText("enable BT");}else{stateBT.setText("disable BT");}Toast.makeText(getApplicationContext(),"disable BT",Toast.LENGTH_SHORT).show();}});unpairBT.setOnClickListener(new View.OnClickListener() {@Overridepublic void onClick(View view) {Log.d(TAG,"unpair BT");if (adapter.getState() == adapter.STATE_ON){stateBT.setText("enable BT");}else{stateBT.setText("disable BT");}Toast.makeText(getApplicationContext(),"unpair BT",Toast.LENGTH_SHORT).show();}});startRecord.setOnClickListener(new View.OnClickListener() {@Overridepublic void onClick(View view) {/* mRecordAudioFile = File.createTempFile(strTempFile,".amr",mRecordAudioPath);*/mRecordAudioFile = new File(mRecordAudioPath.toString(), "zyk.mp3");Toast.makeText(getApplicationContext(), mRecordAudioPath.toString(), Toast.LENGTH_LONG).show();if (!mAudioManager.isBluetoothScoAvailableOffCall()) {Toast.makeText(getApplicationContext(), "BT is not support record", Toast.LENGTH_LONG);return;}/*new a mediarecorder list*//*set the source */mMediaRecorder.setAudioSource(MediaRecorder.AudioSource.MIC);/*set the format*/mMediaRecorder.setOutputFormat(MediaRecorder.OutputFormat.THREE_GPP);/*set the encorder*/mMediaRecorder.setAudioEncoder(MediaRecorder.AudioEncoder.AMR_NB);/*set outpout file's pathc*/mMediaRecorder.setOutputFile(mRecordAudioFile.getAbsolutePath());try {mMediaRecorder.prepare();} catch (IOException e) {e.printStackTrace();}if (!mAudioManager.isBluetoothScoAvailableOffCall()){Log.d(TAG,"system not support BT record");return;}mAudioManager.startBluetoothSco();registerReceiver(new BroadcastReceiver() {@Overridepublic void onReceive(Context context, Intent intent) {record_state = intent.getByteExtra(AudioManager.ACTION_SCO_AUDIO_STATE_CHANGED,(byte)-1);if (AudioManager.SCO_AUDIO_STATE_CONNECTED == record_state) {mAudioManager.setBluetoothScoOn(true);mMediaRecorder.start();unregisterReceiver(this);}else {try {Thread.sleep(1000);} catch (InterruptedException e) {e.printStackTrace();}}}},new IntentFilter(AudioManager.ACTION_SCO_AUDIO_STATE_CHANGED));}});stopRecord.setOnClickListener(new View.OnClickListener() {@Overridepublic void onClick(View view) {if (mMediaRecorder != null) {/* mMediaRecorder.stop();*/mMediaRecorder.release();mMediaRecorder = null;/* mAudioManager.setBluetoothScoOn(false);mAudioManager.stopBluetoothSco();*/}}});visableBT.setOnClickListener(new View.OnClickListener() {@Overridepublic void onClick(View view) {Intent mvisableBtIntent = new Intent(BluetoothAdapter.ACTION_REQUEST_DISCOVERABLE);mvisableBtIntent.putExtra(BluetoothAdapter.EXTRA_DISCOVERABLE_DURATION,360);startActivity(mvisableBtIntent);Toast.makeText(getApplicationContext(),"mvisableBtIntent",Toast.LENGTH_LONG).show();}});};}
修改蓝牙设备的可见性,需要以下权限:
<uses-permission android:name="android.permission.BLUETOOTH_ADMIN">
</uses-permission>
如下将蓝牙适配器可见的时间调整为70s
Intent mvisableBtIntent = new
Intent(BluetoothAdapter.ACTION_REQUEST_DISCOVERABLE); mvisableBtIntent.putExtra(BluetoothAdapter.EXTRA_DISCOVERABLE_DURATION,70);
startActivity(mvisableBtIntent); Toast.makeText(getApplicationContext(),"mvisableBtIntent",Toast.LENGTH_LONG).show();
``
这篇关于android bluetooth api的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!