您的位置:首页 > 移动开发 > Android开发

android 蓝牙搜索功能实现

2016-06-26 19:55 549 查看

MainActivity.java

package com.example.bluefind;

import android.media.AudioManager;
import android.os.Bundle;
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.util.Log;
import android.view.KeyEvent;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;
import android.widget.AdapterView.OnItemClickListener;

public class MainActivity extends Activity {

private BlueFindReceiver mBFR;
private Button bt_start;
private Button bt_stop;
private BluetoothAdapter mBtAdapter;
private ListView newDevice;
private ArrayAdapter<String> mNewDevicesArrayAdapter;
private LinearLayout mliLayout;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
bt_start = (Button) findViewById(R.id.start);
bt_stop = (Button) findViewById(R.id.stop);
mliLayout = (LinearLayout) findViewById(R.id.progress_bar);
initListView();
mBFR = new BlueFindReceiver();
final IntentFilter mFilter = new IntentFilter();
mFilter.addAction(BluetoothDevice.ACTION_FOUND);
mFilter.addAction(BluetoothAdapter.ACTION_DISCOVERY_FINISHED);
mBtAdapter = BluetoothAdapter.getDefaultAdapter();
newDevice.setOnItemClickListener(mDeviceClickListener)
;        bt_start.setOnClickListener(new View.OnClickListener() {

@Override
public void onClick(View v) {
// TODO Auto-generated method stub
if(mBtAdapter == null){
Toast.makeText(getApplicationContext(), "此设备不支持蓝牙", Toast.LENGTH_SHORT).show();
return;
}
mNewDevicesArrayAdapter.clear();
mliLayout.setVisibility(View.VISIBLE);
getApplication().registerReceiver(mBFR, mFilter);
startFind();

}

});
bt_stop.setOnClickListener(new View.OnClickListener() {

@Override
public void onClick(View v) {
// TODO Auto-generated method stub
stopFind();
getApplication().unregisterReceiver(mBFR);
mliLayout.setVisibility(View.GONE);

}

});

}
private void initListView() {
// TODO Auto-generated method stub
newDevice = (ListView) findViewById(R.id.new_devices);
mNewDevicesArrayAdapter = new ArrayAdapter<String>(this,
R.layout.device_name);
newDevice.setAdapter(mNewDevicesArrayAdapter);
}
protected void stopFind() {
// TODO Auto-generated method stub
mBtAdapter.cancelDiscovery();
if (mNewDevicesArrayAdapter.getCount() == 0)
{
String noDevices = "很抱歉没有找到!!";
mNewDevicesArrayAdapter.add(noDevices);
}

}

protected void startFind() {
// TODO Auto-generated method stub

if (mBtAdapter.isDiscovering())
{
mBtAdapter.cancelDiscovery();
}
Log.i("zpf ", "start.........discovery");
mBtAdapter.startDiscovery();
}

class BlueFindReceiver extends BroadcastReceiver{

@Override
public void onReceive(Context context, Intent intent)
{
String action = intent.getAction();

if (BluetoothDevice.ACTION_FOUND.equals(action))
{

BluetoothDevice device = intent
.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE);
Log.i("zpf onReceive ","name -> "+device.getName());
if (device.getBondState() != BluetoothDevice.BOND_BONDED) //通过此方法去判断,哪个设备连接了,刷新连接的视图bug
{
mNewDevicesArrayAdapter.add(device.getName() + "\n"
+ device.getAddress());

}
}
else if (BluetoothAdapter.ACTION_DISCOVERY_FINISHED.equals(action))
{
Log.i("zpf onReceive ","zpf  "+action);
mliLayout.setVisibility(View.GONE);
if (mNewDevicesArrayAdapter.getCount() == 0)
{
String noDevices = "很抱歉没有找到!!";
mNewDevicesArrayAdapter.add(noDevices);
}
}
}

}

private OnItemClickListener mDeviceClickListener = new OnItemClickListener()
{
public void onItemClick(AdapterView<?> av, View v, int arg2, long arg3)
{
mBtAdapter.cancelDiscovery();

String info = ((TextView) v).getText().toString();
String address = info.substring(info.length() - 17);
BluetoothDevice device = BluetoothAdapter.getDefaultAdapter()
.getRemoteDevice(address);
//	mChatService.connect(device);
//开始连接
//显示一个view
//连接状态发生了改变
//取消显示

}
};

//测试蓝牙音乐bug的一些api
private  AudioManager audioManager;
@SuppressWarnings("deprecation")
public   void testAudio(){

//还有这种STREAM_BLUETOOTH_SCO 流,关于蓝牙通话的。7
audioManager = (AudioManager) getApplication().getSystemService(this.AUDIO_SERVICE);
audioManager.isBluetoothA2dpOn();   //判断a2dp状态,正确处理获取音频焦点(暂停,播放)的问题
audioManager.setBluetoothA2dpOn(true);//设置A2dp的开关,去实现,手机端播放(没有声音),设备不发声的问题
// audioManager. setStreamMute(AudioManager.str,booleanstate)
//把铃声,媒体,闹钟,通话,系统的声音中的某一种切换到静音
audioManager.getMode();//得到当前的声音模式。
audioManager.isBluetoothScoOn();
audioManager.isBluetoothScoAvailableOffCall();
audioManager.isSpeakerphoneOn();
audioManager.isMusicActive();
//   audioManager.setBluetoothScoOn(on)

}

int count = -1;

//    @Override
//    public boolean dispatchKeyEvent(KeyEvent event) {
//
//        int action = event.getAction();
//
//        if (action ==KeyEvent.ACTION_DOWN) {
//            Log.i("zpf","+++++++++ACTION_DOWN++++++"+ count++);
//            return true;
//        }
//
//        if (action == KeyEvent.ACTION_UP) {
//        	Log.i("zpf","+++++ACTION_UP++++++++++");
//            return true;
//        }
//
//        return super.dispatchKeyEvent(event);
//    }

@Override
public boolean onKeyDown(int keyCode, KeyEvent event) {
switch (keyCode) {

case KeyEvent.KEYCODE_VOLUME_DOWN:

Log.i("zpf","-----------------"+count);
count--;

return true;

case KeyEvent.KEYCODE_VOLUME_UP:
Log.i("zpf","++++++++++++++++"+ count);
count++;
return true;
case KeyEvent.KEYCODE_VOLUME_MUTE:
Log.i("zpf","MUTE");

return true;
}
return super.onKeyDown(keyCode, event);
}

}


activity_main.xml

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical" >

<Button
android:id="@+id/start"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="开始搜索" />

<Button
android:id="@+id/stop"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="停止搜索" />

<FrameLayout
android:id="@+id/myview"
android:layout_width="match_parent"
android:layout_height="200dp" >

<ListView
android:id="@+id/new_devices"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_weight="2" />

<LinearLayout
android:layout_width="match_parent"
android:layout_height="150dp"
android:id="@+id/progress_bar"
android:background="@android:color/black"
android:alpha="0.4"
android:visibility="gone">

<ProgressBar android:layout_width="100dp"
android:layout_height="100dp"
android:layout_marginLeft="150dp"
android:layout_marginTop="20dp"
/>
</LinearLayout>
</FrameLayout>

</LinearLayout>


device_name.xml

<?xml version="1.0" encoding="utf-8"?>
<TextView xmln
4000
s:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:textSize="18sp"
android:padding="5dp"
/>
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: