ANDROID_MARS学习笔记_S03_002_设置可见性及扫描蓝牙设备
2016-02-20 12:21
531 查看
一、代码
1.xml
(1)AndroidManifest.xml
2.java
(1)MainActivity.java
1.xml
(1)AndroidManifest.xml
<uses-permission android:name="android.permission.BLUETOOTH"/> <uses-permission android:name="android.permission.BLUETOOTH_ADMIN"/> </manifest>
2.java
(1)MainActivity.java
package com.bluetooth2; 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.os.Bundle; import android.view.View; import android.view.View.OnClickListener; import android.widget.Button; public class MainActivity extends Activity { private Button discoverButton = null; private Button scanButton = null; private BluetoothAdapter adapter = null; private BluetoothReceiver bluetoothReceiver = null; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); adapter = BluetoothAdapter.getDefaultAdapter(); discoverButton = (Button) findViewById(R.id.discoverButton); scanButton = (Button) findViewById(R.id.scanButton); discoverButton.setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { Intent discoverIntent = new Intent(BluetoothAdapter.ACTION_REQUEST_DISCOVERABLE); //设置蓝牙可见性,500表示可见时间(单位:秒),当值大于300时默认为300 discoverIntent.putExtra(BluetoothAdapter.EXTRA_DISCOVERABLE_DURATION, 500); System.out.println("设置蓝牙可见性-->"); startActivity(discoverIntent);//android自带的activity } }); scanButton.setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { //开始扫描周围蓝牙设备,该方法是异步调用并以广播的机制返回,所以需要创建一个BroadcastReceiver来获取信息 System.out.println("开始扫描周围蓝牙设备-->"); adapter.startDiscovery(); } }); //设定广播接收的filter IntentFilter intentFilter = new IntentFilter(BluetoothDevice.ACTION_FOUND); //创建蓝牙广播信息的receiver bluetoothReceiver = new BluetoothReceiver(); //注册广播接收器 registerReceiver(bluetoothReceiver, intentFilter); } private class BluetoothReceiver extends BroadcastReceiver { @Override public void onReceive(Context context, Intent intent) { //获得扫描到的远程蓝牙设备 BluetoothDevice device = intent.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE); System.out.println("BluetoothReceiver收到广播---->" + device); } } }
相关文章推荐
- android时差8小时
- android adb 常用命令
- android中常用的设计模式
- 第6章 Android的Drawable
- android spinner handleDataChanged的问题
- Android屏幕适配全攻略(最权威的官方适配指导)
- Android防止按钮连续点击
- android系统级弹窗
- 第一次使用Android AIDL总结
- Andriod之import android.support.v4或者import android.support.v7提示导入错误解决办法
- RecyclerView应用 —— 好友列表实现
- Android Studio apk 打包流程
- android wifi
- Android图片裁剪
- Android常用系统广播
- 在Android的TableLayout布局中,column和span属性“失效”原因分析与解决
- android中多个fragment切换时如何避免重复执行onCreateView方法,如何保存上一个fragment的状态
- Android基于XMPP Smack及Openfire学习笔记(1)
- Android学习笔记三 Tip Calculator
- Android EditText自定义样式的方法