AndroidManifest.xml 添加权限:

<uses-permission android:name="android.permission.BLUETOOTH" />
<uses-permission android:name="android.permission.BLUETOOTH_ADMIN" />

Main.xml 布局:

<?xml version="1.0" encoding="utf-8"?><LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"    android:layout_width="fill_parent"    android:layout_height="fill_parent"    android:orientation="vertical" >    <TextView        android:id="@+id/t"        android:layout_width="fill_parent"        android:layout_height="wrap_content"        android:text="@string/hello" />    <Button        android:id="@+id/button1"        android:layout_width="match_parent"        android:layout_height="wrap_content"        android:text="Button" />    <Button        android:id="@+id/button2"        android:layout_width="match_parent"        android:layout_height="wrap_content"        android:text="Button" />    <ImageView        android:id="@+id/imageView1"        android:layout_width="wrap_content"        android:layout_height="65dp"        android:src="@drawable/ic_launcher" /></LinearLayout>

MainActivity :

package com.zxl;import android.app.Activity;import android.bluetooth.BluetoothAdapter;import android.content.BroadcastReceiver;import android.content.Context;import android.content.Intent;import android.content.IntentFilter;import android.os.Bundle;import android.provider.MediaStore.Images;import android.view.View;import android.view.View.OnClickListener;import android.widget.Button;import android.widget.ImageView;import android.widget.TextView;import android.widget.Toast;public class MainActivity extends Activity {    /** Called when the activity is first created. */public TextView statuUpdate;public Button connect;public Button disconnect;public ImageView logo;private BluetoothAdapter btAdapter; BroadcastReceiver bluetoothState=new BroadcastReceiver(){ public void onReceive(Context context,Intent intent){ String prevStateExtra=BluetoothAdapter.EXTRA_PREVIOUS_STATE; String stateExtra=BluetoothAdapter.EXTRA_STATE; int state=intent.getIntExtra(stateExtra, -1); //int previouState=intent.getIntExtra(prevStateExtra, -1); String toastText=""; switch (state) {case (BluetoothAdapter.STATE_TURNING_ON):toastText="Bluetooth turning on";Toast.makeText(MainActivity.this, toastText, Toast.LENGTH_SHORT).show();break;case (BluetoothAdapter.STATE_ON):toastText="Bluetooth on";Toast.makeText(MainActivity.this, toastText, Toast.LENGTH_SHORT).show();setupUI();break;case (BluetoothAdapter.STATE_TURNING_OFF):toastText="Bluetooth turning off";Toast.makeText(MainActivity.this, toastText, Toast.LENGTH_SHORT).show();break;case (BluetoothAdapter.STATE_OFF):toastText="Bluetooth off";Toast.makeText(MainActivity.this, toastText, Toast.LENGTH_SHORT).show();break;default:break;} } };@Override    public void onCreate(Bundle savedInstanceState) {        super.onCreate(savedInstanceState);        setContentView(R.layout.main);        setupUI();    }private void setupUI(){//get referncesfinal TextView statuUpdate=(TextView)findViewById(R.id.t);final Button connect=(Button)findViewById(R.id.button1);final Button disconnect=(Button)findViewById(R.id.button2);final ImageView logo=(ImageView)findViewById(R.id.imageView1);//set display viewdisconnect.setVisibility(View.GONE);logo.setVisibility(View.GONE);btAdapter=BluetoothAdapter.getDefaultAdapter();if(btAdapter.isEnabled()){String address=btAdapter.getAddress();String name=btAdapter.getName();String statusText=name+":"+address;statuUpdate.setText(statusText);disconnect.setVisibility(View.VISIBLE);logo.setVisibility(View.VISIBLE);connect.setVisibility(View.GONE);}else{connect.setVisibility(View.GONE);statuUpdate.setText("bluetooth is not on");}connect.setOnClickListener(new OnClickListener() {public void onClick(View v) {// TODO Auto-generated method stubString actionStateChanged=BluetoothAdapter.ACTION_STATE_CHANGED;String actionRequesEnableString=BluetoothAdapter.ACTION_REQUEST_ENABLE;IntentFilter filter=new IntentFilter(actionStateChanged);registerReceiver(bluetoothState, filter);startActivityForResult(new Intent(actionRequesEnableString), 0);}}); //end connect onclicklistenerdisconnect.setOnClickListener(new OnClickListener() {public void onClick(View v) {// TODO Auto-generated method stubbtAdapter.disable();disconnect.setVisibility(View.GONE);logo.setVisibility(View.GONE);connect.setVisibility(View.VISIBLE);statuUpdate.setText("Bluetooth OFF");}});}}


改写:

package com.zxl;import java.util.Set;import android.R.integer;import android.R.string;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.content.SharedPreferences;import android.os.Bundle;import android.provider.MediaStore.Images;import android.view.View;import android.view.View.OnClickListener;import android.widget.Button;import android.widget.ImageView;import android.widget.TextView;import android.widget.Toast;public class MainActivity extends Activity {    /** Called when the activity is first created. */public TextView statuUpdate;public Button connect;public Button disconnect;public ImageView logo;private BluetoothAdapter btAdapter;protected static final int DISCOVERY_REQUEST=1;public String toastText;private BluetoothDevice remoteDevice;//create a broadcastreceiver to receive state changes BroadcastReceiver bluetoothState=new BroadcastReceiver(){ public void onReceive(Context context,Intent intent){ String prevStateExtra=BluetoothAdapter.EXTRA_PREVIOUS_STATE; String stateExtra=BluetoothAdapter.EXTRA_STATE; int state=intent.getIntExtra(stateExtra, -1); //int previouState=intent.getIntExtra(prevStateExtra, -1); //String toastText=""; switch (state) {case (BluetoothAdapter.STATE_TURNING_ON):toastText="Bluetooth turning on";Toast.makeText(MainActivity.this, toastText, Toast.LENGTH_SHORT).show();break;case (BluetoothAdapter.STATE_ON):toastText="Bluetooth on";Toast.makeText(MainActivity.this, toastText, Toast.LENGTH_SHORT).show();setupUI();break;case (BluetoothAdapter.STATE_TURNING_OFF):toastText="Bluetooth turning off";Toast.makeText(MainActivity.this, toastText, Toast.LENGTH_SHORT).show();break;case (BluetoothAdapter.STATE_OFF):toastText="Bluetooth off";Toast.makeText(MainActivity.this, toastText, Toast.LENGTH_SHORT).show();break;default:break;} } };@Override    public void onCreate(Bundle savedInstanceState) {        super.onCreate(savedInstanceState);        setContentView(R.layout.main);        setupUI();    }private void setupUI(){//get referncesfinal TextView statuUpdate=(TextView)findViewById(R.id.t);final Button connect=(Button)findViewById(R.id.button1);final Button disconnect=(Button)findViewById(R.id.button2);final ImageView logo=(ImageView)findViewById(R.id.imageView1);//set display viewdisconnect.setVisibility(View.GONE);logo.setVisibility(View.GONE);btAdapter=BluetoothAdapter.getDefaultAdapter();if(btAdapter.isEnabled()){String address=btAdapter.getAddress();String name=btAdapter.getName();String statusText=name+":"+address;statuUpdate.setText(statusText);disconnect.setVisibility(View.VISIBLE);logo.setVisibility(View.VISIBLE);connect.setVisibility(View.GONE);}else{connect.setVisibility(View.GONE);statuUpdate.setText("bluetooth is not on");}connect.setOnClickListener(new OnClickListener() {public void onClick(View v) {// TODO Auto-generated method stub/*String actionStateChanged=BluetoothAdapter.ACTION_STATE_CHANGED;String actionRequesEnableString=BluetoothAdapter.ACTION_REQUEST_ENABLE;IntentFilter filter=new IntentFilter(actionStateChanged);registerReceiver(bluetoothState, filter);startActivityForResult(new Intent(actionRequesEnableString), 0);*///register for discovery ecentsString scanModeChanged=BluetoothAdapter.ACTION_SCAN_MODE_CHANGED;String beDiscoveroble=BluetoothAdapter.ACTION_REQUEST_DISCOVERABLE;IntentFilter filter=new IntentFilter(scanModeChanged);registerReceiver(bluetoothState, filter);startActivityForResult(new Intent(beDiscoveroble), DISCOVERY_REQUEST);}}); //end connect onclicklistenerdisconnect.setOnClickListener(new OnClickListener() {public void onClick(View v) {// TODO Auto-generated method stubbtAdapter.disable();disconnect.setVisibility(View.GONE);logo.setVisibility(View.GONE);connect.setVisibility(View.VISIBLE);statuUpdate.setText("Bluetooth OFF");}});}protected void onActivityResult(int requestCode,int resultCode,Intent data){if(requestCode==DISCOVERY_REQUEST){Toast.makeText(MainActivity.this, "discovery in progress",Toast.LENGTH_SHORT).show();setupUI();findDevices();}}private void findDevices(){String lastUserRemoteDevice=getlastUserRemoteDevice();if(lastUserRemoteDevice!=null){toastText="checking for know paired devixes namely:"+lastUserRemoteDevice;Toast.makeText(MainActivity.this, toastText, Toast.LENGTH_SHORT).show();//see if this device is in a list of currently visible(?) 。paired devicesSet<BluetoothDevice> pairedDevices=btAdapter.getBondedDevices();for(BluetoothDevice paireDevice : pairedDevices){if(paireDevice.getAddress().equals(lastUserRemoteDevice)){toastText="found device:"+paireDevice.getName()+"@"+lastUserRemoteDevice;Toast.makeText(MainActivity.this, toastText, Toast.LENGTH_SHORT).show();remoteDevice=paireDevice;}}}if(remoteDevice==null){toastText="starting discovery for remote devixes...";Toast.makeText(MainActivity.this, toastText, Toast.LENGTH_SHORT).show();registerReceiver(discoveryResult, new IntentFilter(BluetoothDevice.ACTION_FOUND));}}BroadcastReceiver discoveryResult=new BroadcastReceiver() {@Overridepublic void onReceive(Context context, Intent intent) {// TODO Auto-generated method stubString remoteDeciceName=intent.getStringExtra(BluetoothDevice.EXTRA_NAME);BluetoothDevice remoteDevice;remoteDevice=intent.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE);toastText="discovered:"+remoteDeciceName;Toast.makeText(MainActivity.this, toastText, Toast.LENGTH_SHORT).show();}};private String getlastUserRemoteDevice(){SharedPreferences prefs=getPreferences(MODE_PRIVATE);String result=prefs.getString("LAST_REMOTE_DEVICE_ADDRESS", null);return result;}}









更多相关文章

  1. Android(安卓)BaseFragment基类
  2. Kotlin简单开发-RecyclerView
  3. Android(安卓)录制音频示例
  4. 聊聊 RN 中 Android(安卓)提供 View 的那些坑
  5. Android布局(一)之基本视图View
  6. Android课程表界面布局实现
  7. 详解 Android(安卓)Views 元素的 layout_weight 属性
  8. Android高性能编码 - 第八篇 移动端安全规范
  9. 权重平等分布局And TableRow布局误区

随机推荐

  1. 【Android】调用系统应用常用uri & inten
  2. Androd学习笔记——Android中Touch事件的
  3. 【转】How to port native (C/C++) libra
  4. 《Android 获取当前app的版本号和版本名
  5. Android(安卓)Studio运行Hello World程序
  6. android 中给图片加圆角效果
  7. Android API 中文 (112) ―― ThumbnailU
  8. Android Binder机制(三) ServiceManager
  9. Android屏幕截图实现 (adbd部分)
  10. Ubuntu10.04 LTS 下编译Android