블루투스를 켜고 끌 수있는 응용 프로그램을 만들었습니다. 켜기/끄기에는 스위치 버튼을 사용했습니다. 여기에 코드입니다 :블루투스 사용/사용 안 함
public class MainActivity extends AppCompatActivity {
private static final String TAG = "MainActivity";
private final static int REQUEST_ENABLE_BT = 1;
BluetoothAdapter mBluetoothAdapter = null;
private final BroadcastReceiver mReceiver = new BroadcastReceiver() {
public void onReceive(Context context, Intent intent) {
String action = intent.getAction();
if (action.equals(mBluetoothAdapter.ACTION_STATE_CHANGED)) {
final int state = intent.getIntExtra(mBluetoothAdapter.EXTRA_STATE, mBluetoothAdapter.ERROR);
switch (state){
case BluetoothAdapter.STATE_OFF:
break;
case BluetoothAdapter.STATE_ON:
break;
}
}
}
};
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
final Switch bluetoothSwitch = (Switch) findViewById(R.id.bluetoothSwitch);
mBluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
if (mBluetoothAdapter == null){
//Device does not support bluetooth
}
else{
bluetoothSwitch.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
@Override
public void onCheckedChanged(CompoundButton compoundButton, boolean b) {
if(bluetoothSwitch.isChecked() && !mBluetoothAdapter.isEnabled()){
Intent enableBtIntent = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);
startActivityForResult(enableBtIntent, REQUEST_ENABLE_BT);
IntentFilter BTIntent = new IntentFilter(BluetoothAdapter.ACTION_STATE_CHANGED);
registerReceiver(mReceiver, BTIntent);
}
if(!bluetoothSwitch.isChecked() && mBluetoothAdapter.isEnabled()){
mBluetoothAdapter.disable();
IntentFilter BTIntent = new IntentFilter(BluetoothAdapter.ACTION_STATE_CHANGED);
registerReceiver(mReceiver, BTIntent);
}
}
});
}
}
}
문제는 내가 내 응용 프로그램의 설정에서/오프 블루투스를 켜고하지 않을 경우 스위치가 변경되지 않는다는 것입니다. 브로드 캐스트 리시버를 구현했지만 스위치에서 액세스 할 수 없습니다. 방송 수신기 내부
bluetoothSwich.setChecked(true)
그러나 그것은 작동하지 않습니다 나는 시도했다.
타이
편집 : 나는 부분적으로 처음 난 내 응용 프로그램에서 한 번 이상에서 ON/OFF 버튼을 클릭해야 설정에서 ON/OFF 동작을 잡을 수 있지만 글로벌 스위치와 함께 문제를 해결했다. 어떠한 제안?
당신은 안드로이드 매니페스트 파일에있는 수신기를 추가 한? 스위치 버튼을 전역 전송 수신기 내에서 액세스 할 수 있도록 전역으로 설정하십시오. –
예. 안드로이드 매니페스트에 수신기를 추가했습니다. 전 swtich 버튼을 글로벌하게 만들려고했는데 브로드 캐스트 수신기에서 액세스 할 수 있지만 설정에서 블루투스를 켜고 끌 수는 없습니다. – Tenrampi