蓝牙适配器无法在Android 4.0上运行(API 14-15)

时间:2013-08-06 22:02:35

标签: android bluetooth

我是Android上的新手,我只是想开发一款可以打开/关闭设备蓝牙功能的应用。此代码在Android 4.2 / 4.3上完美运行(在物理设备上测试);但它不适用于Android 4.0 / 4.1。有人可以帮我这个吗?

import android.app.Activity;
import android.bluetooth.BluetoothAdapter;
import android.content.Context;
import android.content.Intent;
import android.media.AudioManager;
import android.net.wifi.WifiManager;
import android.os.Bundle;
import android.telephony.PhoneStateListener;
import android.telephony.TelephonyManager;
import android.widget.CompoundButton;
import android.widget.CompoundButton.OnCheckedChangeListener;
import android.widget.RadioButton;
import android.widget.RadioGroup;
import android.widget.SeekBar;
import android.widget.Switch;
import android.widget.TextView;
import android.view.Menu;

public class MainActivity extends Activity {

private static final int REQUEST_ENABLE_BT = 1;
private BluetoothAdapter bA;

@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
}

public void onResume(){
    checkBluetooth();
    setBluetoothListener();
}

@Override
public boolean onCreateOptionsMenu(Menu menu) {
    // Inflate the menu; this adds items to the action bar if it is present.
    getMenuInflater().inflate(R.menu.main, menu);
    return true;
}


private void checkBluetooth(){
    bA = BluetoothAdapter.getDefaultAdapter();
    Switch blue = (Switch)findViewById(R.id.switch4);
    blue.setChecked(true);
    }

private void setBluetoothListener(){
    Switch sBlue = (Switch) findViewById(R.id.switch4);
    sBlue.setOnCheckedChangeListener(new OnCheckedChangeListener() {
        @Override
        public void onCheckedChanged(CompoundButton arg0, boolean arg1) {
             if (arg1) {
                    Intent enableBtIntent = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);
                    startActivityForResult(enableBtIntent, REQUEST_ENABLE_BT);   
                } else {
                    bA.disable();
                }
            }
    });
}

}

1 个答案:

答案 0 :(得分:0)

尝试:

@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    checkBluetooth();
    setBluetoothListener();
}


@Override
public void onResume(){
    super.onResume();
    checkBluetooth();
}

在onCreate()方法中,建议创建和绑定视图和数据。并保留onResume只是为了检查是否有任何变量(即蓝牙状态)。

这也是你想要的:

private void checkBluetooth(){
    bA = BluetoothAdapter.getDefaultAdapter();
    Switch blue = (Switch)findViewById(R.id.switch4);
    blue.setChecked(bA.isEnabled());
}