1
我有一個soundrecorder android線程,我需要知道在記錄時是否連接了麥克風/頭戴式耳機,所以我需要在thread.how中使用BroadcastReceiver()我註冊了嗎? this.registerReceiver()不會工作,因爲它只適用於活動。如何註冊一個線程內的BroadcastReceiver()
如果在線程中使用broadcasereceivers不是一個好主意,那麼解決方案是什麼?
這裏是將一個活動,不會工作裏面工作線程中的代碼:
headsetReceiver = new BroadcastReceiver() {
@Override
public void onReceive(Context context, Intent intent) {
String action = intent.getAction();
Log.i("Broadcast Receiver", action);
if ((action.compareTo(Intent.ACTION_HEADSET_PLUG)) == 0) // if
// the
// action
// match
// a
// headset
// one
{
int headSetState = intent.getIntExtra("state", 0); // get
// the
// headset
// state
// property
int hasMicrophone = intent.getIntExtra("microphone", 0);// get
// the
// headset
// microphone
// property
if ((headSetState == 0) && (hasMicrophone == 0)) // headset
// was
// unplugged
// &
// has
// no
// microphone
{
// do whatever
}
}
}
};
this.registerReceiver(headsetReceiver, new IntentFilter(
Intent.ACTION_HEADSET_PLUG));