package com.ken.testBluetooth;import android.app.Activity;import android.app.AlertDialog;import android.bluetooth.BluetoothAdapter;import android.content.DialogInterface;import android.content.Intent;import android.graphics.Color;import android.os.Bundle;import android.view.View;public class TestBluetoothActivity extends Activity {//獲得藍芽適配器 BluetoothAdapter mAdapter=BluetoothAdapter.getDefaultAdapter();//藍芽請求開啟private static final int REQUEST_ENABLE=0x1;/* 請求能夠被搜尋 */private static final int REQUEST_DISCOVERABLE = 0x2; /** Called when the activity is first created. */ @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.main);} //開啟藍芽public void onEnableButtonClicked(View view){ if(!mAdapter.isEnabled()){ //彈出對話方塊提示使用者 Intent enabler=new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE); startActivityForResult(enabler,REQUEST_ENABLE); /** * 不做提示開啟 * mAdapter.enable(); */ }else{ new AlertDialog.Builder(this).setMessage("藍芽已開啟!").setPositiveButton("確定", new DialogInterface.OnClickListener() {public void onClick(DialogInterface dialog, int which) {}}).setNegativeButton("取消", null).show(); }} //關閉藍芽 public void onDisableButtonClicked(View view){ mAdapter.disable(); } /* 使裝置能夠被搜尋 */public void onMakeDiscoverableButtonClicked(View view){Intent enabler = new Intent(BluetoothAdapter.ACTION_REQUEST_DISCOVERABLE);startActivityForResult(enabler, REQUEST_DISCOVERABLE);}/* 開始搜尋 */public void onStartDiscoveryButtonClicked(View view){Intent enabler = new Intent(this, DiscoveryActivity.class);startActivity(enabler);}/* 用戶端 */public void onOpenClientSocketButtonClicked(View view){Intent enabler = new Intent(this, ClientSocketActivity.class);startActivity(enabler);}/* 服務端 */public void onOpenServerSocketButtonClicked(View view){Intent enabler = new Intent(this, ServerSocketActivity.class);startActivity(enabler);}/* OBEX伺服器 */public void onOpenOBEXServerSocketButtonClicked(View view){Intent enabler = new Intent(this, OBEXActivity.class);startActivity(enabler);}}
原文:http://www.eoeandroid.com/thread-18993-1-1.html