Android 蓝牙设备的开启与关闭功能的实现

本文主要是关于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();  
					 }
				}  	
	        });
	    }  
	}  

2.布局文件activity_main.xml


   
	
	
    

3.配置文件AndroidManifest.xml添加权限

  
      
    


你可能感兴趣的:(Android 蓝牙设备的开启与关闭功能的实现)