http://tieba.baidu.com/p/4175489217
这是原帖,分步教太麻烦,直接去看原帖。这里贴上代码和代码。。。。。
package xyz.atdstudio.blue;
import android.app.*;
import android.os.*;
import android.view.*;
import android.widget.*;
import android.bluetooth.*;
import android.content.*;
import android.view.View.*;
import android.util.*;
import java.util.*;
import android.widget.AdapterView.*;
import java.io.*;
import java.lang.reflect.*;
import android.graphics.*;
import android.text.*;
public class MainActivity extends Activity
{
//表示串口服务的uuid
static final String SPP_UUID = "00001101-0000-1000-8000-00805F9B34FB";
//蓝牙适配器
BluetoothAdapter blueAdapter =null;
//蓝牙socket
public static BluetoothSocket btSocket;
OutputStream os =null;//输出流
ListAdapter listAdapter;
List<String> blueName=new ArrayList<String>(),
blueAddress=new ArrayList<String>();
BroadcastReceiver mReceiver;//广播接收器
Button close;//关闭按钮
ProgressBar pb;//进度条
TextView tv;
/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
pb=(ProgressBar) findViewById(R.id.mainProgressBar1);
close=(Button) findViewById(R.id.mainButton1);
close.setOnClickListener(new OnClickListener(){
@Override
public void onClick(View p1)
{
try
{
if (os != null)
os.close();
}
catch (IOException e)
{}
unregisterReceiver(mReceiver);//取消接收广播
blueAdapter.disable();//关闭蓝牙
//把信息写入文件
try
{
FileWriter temp=new FileWriter(Environment.getExternalStorageDirectory().getAbsolutePath()+"/啊杜拉.txt");
temp.write(blueName.toString()+"地址"+blueAddress.toString());
temp.flush();
temp.close();
}
catch (IOException e)
{}
// TODO: Implement this method
}
});
blueAdapter= BluetoothAdapter.getDefaultAdapter();//获取本机蓝牙
if(blueAdapter==null)//如果没有蓝牙
{
Toast.makeText(this,"抱歉,您的手机没有蓝牙功能!",Toast.LENGTH_LONG).show();
finish();//结束程序
}
else
{
if (blueAdapter.isEnabled()==false)//如果本机蓝牙没有打开
{
blueAdapter.enable();//打开
}
}
tv=(TextView) findViewById(R.id.mainTextView1);
final EditText sd=(EditText) findViewById(R.id.mainEditText1);
Button sb=(Button) findViewById(R.id.mainButton2);
sb.setOnClickListener(new OnClickListener(){
@Override
public void onClick(View p1)
{
String s=sd.getText().toString();
if(!s.equals(""))
{
try{
if(os==null)
os= btSocket.getOutputStream();
os.write(getBytes(s));
os.flush();
Toast.makeText(MainActivity.this,s+"已发送",Toast.LENGTH_SHORT).show();
sd.setText("");
}
catch(Exception e)
{
Toast.makeText(MainActivity.this,"发送失败"+e,Toast.LENGTH_SHORT).show();
}
}
else
Toast.makeText(MainActivity.this,"发送内容不能为空!",Toast.LENGTH_SHORT).show();
// TODO: Implement this method
}});
}
@Override
protected void onResume()
{
// TODO: Implement this method
mReceiver=new BroadcastReceiver() {
public void onReceive(Context context, Intent intent) {
String action = intent.getAction();
// 发现设备
if (BluetoothDevice.ACTION_FOUND.equals(action)) {
// 从Intent中获取设备对象
BluetoothDevice device = intent.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE);
blueName.add(device.getName()+"的地址"+device.getAddress());
blueAddress.add(device.getAddress());
if(device.getAddress().equals("98 3:31:80:3D:3E"))
blueAdapter.cancelDiscovery();//这是我的蓝牙模块地址,找到就直接结束
}
else if (BluetoothAdapter.ACTION_DISCOVERY_FINISHED.equals(action)) //扫描结束
{
pb.setVisibility(5);
listAdapter= new ArrayAdapter<String>(MainActivity.this, android.R.layout.simple_list_item_1, blueName);
final ListView listView = (ListView) findViewById(R.id.mainListView1);
listView.setAdapter(listAdapter);
listView.setOnItemClickListener(new OnItemClickListener() {
@Override
public void onItemClick(AdapterView<?> l, View v, int position, long id)
{
String address=blueAddress.get(position);
BluetoothDevice btDev = blueAdapter.getRemoteDevice(address);
try {
Boolean returnValue = false;
if (btDev.getBondState() == BluetoothDevice.BOND_NONE) {
//利用反射方法调用BluetoothDevice.createBond(BluetoothDevice remoteDevice);
Toast.makeText(MainActivity.this,"正在配对"+address,Toast.LENGTH_SHORT).show();
Method createBondMethod = BluetoothDevice.class.getMethod("createBond");
//配对
returnValue = (Boolean) createBondMethod.invoke(btDev);
Toast.makeText(MainActivity.this,"配对结果:"+returnValue,Toast.LENGTH_SHORT).show();
}else if(btDev.getBondState() == BluetoothDevice.BOND_BONDED){
//连接
//Toast.makeText(MainActivity.this,"正在连接"+address,Toast.LENGTH_SHORT).show();
if(connect(btDev))
{
listView.setVisibility(5);
tv.setText(blueName.get(position));
tv.setTextColor(Color.BLUE);
}
else
Toast.makeText(MainActivity.this,"连接失败",Toast.LENGTH_SHORT);
}
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
}
};
// 注册BroadcastReceiver
IntentFilter filter = new IntentFilter(BluetoothDevice.ACTION_FOUND);
registerReceiver(mReceiver,filter); // 不要忘了之后解除绑定
filter = new IntentFilter(BluetoothAdapter.ACTION_DISCOVERY_FINISHED);
registerReceiver(mReceiver,filter); // 不要忘了之后解除绑定
new Handler().postDelayed(new Runnable() {
public void run() {
blueAdapter.startDiscovery();//开始搜索设备
}
}, 1500);//1500毫秒后执行上面
super.onResume();
}
private boolean connect(BluetoothDevice btDev) {
UUID uuid = UUID.fromString(SPP_UUID);
try {
btSocket = btDev.createRfcommSocketToServiceRecord(uuid);
Log.d("BlueToothTestActivity", "开始连接...");
btSocket.connect();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
return false;
}
return true;
}
public static byte[] getBytes(String s)
{
byte[] bytes=null;
try
{
bytes=s.getBytes("us-ascii");
}
catch (UnsupportedEncodingException e)
{}
return bytes;
}
}
|