2013-08-06 145 views
0

我是Android新手,我只是想開發一個打開/關閉設備上的藍牙應用程序。此代碼完美適用於Android 4.2/4.3(在物理設備上測試);但它不適用於Android 4.0/4.1。任何人都可以幫助我嗎?藍牙適配器不適用於Android 4.0(API 14-15)

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(); 
       } 
      } 
    }); 
} 

}

+0

是否引發任何錯誤或警告日誌? – frogmanx

回答

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()); 
} 
+0

嗨frogmanx,我已經嘗試過這些變化。事情是我得到一個nullpointerexception,當我運行代碼只在android 4.0 & 4.1;但不是在4.2上嘗試時。 – Vicentepp

+0

你從哪裏得到空指針? – frogmanx

+0

我在調用方法「bA.isEnabled()」時得到它(再次,只在Android 4.0中,不在4.2中) – Vicentepp

相關問題