我有一个录音机 android 线程,我需要知道录音时是否连接了麦克风/耳机,所以我需要在线程内使用 BroadcastReceiver()。我该如何注册?this.registerReceiver() 不起作用,因为它只在活动内部起作用。
如果在线程内使用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));