2017-11-14 24 views
1

블루투스를 켜고 끌 수있는 응용 프로그램을 만들었습니다. 켜기/끄기에는 스위치 버튼을 사용했습니다. 여기에 코드입니다 :블루투스 사용/사용 안 함

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 동작을 잡을 수 있지만 글로벌 스위치와 함께 문제를 해결했다. 어떠한 제안?

+0

당신은 안드로이드 매니페스트 파일에있는 수신기를 추가 한? 스위치 버튼을 전역 전송 수신기 내에서 액세스 할 수 있도록 전역으로 설정하십시오. –

+0

예. 안드로이드 매니페스트에 수신기를 추가했습니다. 전 swtich 버튼을 글로벌하게 만들려고했는데 브로드 캐스트 수신기에서 액세스 할 수 있지만 설정에서 블루투스를 켜고 끌 수는 없습니다. – Tenrampi

답변

1

블루투스의 상태 변경을 감지하려면 AndroidManifest.xml에 다음 권한을 추가해야합니다.

<uses-permission android:name="android.permission.BLUETOOTH" /> 

로컬 방송을 사용하는 것이 좋습니다. 매니페스트에 등록 할 필요가 없습니다. 당신이 그것을 필요로하는 곳에 런타임에 등록 (응용 프로그램은 다음 매니페스트에 등록을 통해 필요한 경우)

private final BroadcastReceiver bStateReceiver = new BroadcastReceiver() { 
    public void onReceive(Context context, Intent intent) { 
     String action = intent.getAction(); 
     if (BluetoothAdapter.ACTION_STATE_CHANGED.equals(action)) { 
      if (intent.getIntExtra(BluetoothAdapter.EXTRA_STATE, -1) == BluetoothAdapter.STATE_OFF) { 
       // Bluetooth is disconnected, do handling here 
      } 
     } 
    } 

}; 

런타임 레지스터 :.

LocalBroadcastManager.getInstance(this).registerReceiver(bStateReceiver, new IntentFilter(BluetoothAdapter.ACTION_STATE_CHANGED)); 

런타임 등록 취소를 : 방송의 등록을 취소하는 것을 잊지 마십시오.

LocalBroadcastManager.getInstance(this).unregisterReceiver(bStateReceiver); 

정적 등록은 :

<receiver 
    android:name=".FullyQualifiedBroadcastReceiverClassName" 
    android:enabled="true"> 
<intent-filter> 
    <action android:name="android.bluetooth.adapter.action.STATE_CHANGED"/> 
</intent-filter>