标签:
本文主要是关于Android蓝牙设备的开启与关闭,很简单,详细请看代码。
1.MainActivity.java
public class MainActivity extends Activity { private String TAG="MainActivity"; private Button startBtn; private Button stopBtn; BluetoothAdapter mBluetoothAdapter; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); startBtn=(Button)findViewById(R.id.start_btn); stopBtn=(Button)findViewById(R.id.stop_btn); mBluetoothAdapter = BluetoothAdapter.getDefaultAdapter(); if (mBluetoothAdapter == null) { Toast.makeText(this, "本机没有找到蓝牙硬件或驱动!", Toast.LENGTH_SHORT).show(); finish(); } startBtn.setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { // TODO Auto-generated method stub // 如果本地蓝牙没有开启,则开启 if (!mBluetoothAdapter.isEnabled()) { mBluetoothAdapter.enable(); Toast.makeText(getApplicationContext(), "蓝牙已经开启", Toast.LENGTH_SHORT).show(); } } }); stopBtn.setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { // TODO Auto-generated method stub if (mBluetoothAdapter.isEnabled()) { mBluetoothAdapter.disable();//关闭蓝牙 Toast.makeText(getApplicationContext(), "蓝牙已经关闭", Toast.LENGTH_SHORT).show(); } } }); } }
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent" android:layout_height="match_parent" android:orientation="vertical" > <TextView android:layout_width="wrap_content" android:layout_height="wrap_content" android:textStyle="bold" android:textSize="24dip" android:layout_gravity="center" android:text="蓝牙打开与关闭测试 "/> <Button android:id="@+id/start_btn" android:layout_width="fill_parent" android:layout_height="wrap_content" android:text="打开" /> <Button android:id="@+id/stop_btn" android:layout_width="fill_parent" android:layout_height="wrap_content" android:text="关闭" /> </LinearLayout>
<uses-permission android:name="android.permission.BLUETOOTH"/> <uses-permission android:name="android.permission.BLUETOOTH_ADMIN"/>
版权声明:本文为博主原创文章,未经博主允许不得转载。
标签:
原文地址:http://blog.csdn.net/tanghua0809/article/details/47320303