1

我有一个录音机 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));
4

1 回答 1

1

您需要将上下文传递给 Thread 构造函数,然后使用它来注册广播接收器:

//this.ctx is passed to the Thread constructor
this.ctx.registerReceiver(headsetReceiver, new IntentFilter(
            Intent.ACTION_HEADSET_PLUG));

不要忘记在您的线程中的 finally{} 中取消注册您的接收器,否则可能会发生泄漏:

finally{
       ctx.unregisterReceiver(headsetReceiver);
}

为了在主线程(例如活动)中更改 UI,您需要设置一个处理程序

于 2012-09-04T20:30:31.337 回答