问题描述
我有一个soundrecorder Android的线程,我需要知道,如果麦克风/耳机连接或不同时录制,所以我需要使用一个BroadcastReceiver()的thread.how里面我可以注册? this.registerReceiver()不会工作,因为它仅适用于内活动。
如果使用一个线程内broadcasereceivers是不是一个好主意,所以什么解决办法吗?
这里是code这将一个活动,不会工作线程内内工作:
headsetReceiver =新的广播接收器(){
@覆盖
公共无效的onReceive(上下文的背景下,意图意图){
字符串行动= intent.getAction();
Log.i(广播接收器,动作);
如果((action.compareTo(Intent.ACTION_HEADSET_PLUG))== 0)//如果
//将
//动作
// 匹配
// 一个
//耳机
// 1
{
INT headSetState = intent.getIntExtra(国家,0); //获取
//将
//耳机
//状态
//财产
INT hasMicrophone = intent.getIntExtra(话筒,0); //获取
//将
//耳机
//麦克风
//财产
如果((headSetState == 0)及及(hasMicrophone == 0))//耳机
//是
//不插电
//&安培;
// 具有
//没有
//麦克风
{
//做什么
}
}
}
}; this.registerReceiver(headsetReceiver,新的IntentFilter(
Intent.ACTION_HEADSET_PLUG));
您将需要上下文传递给线程构造函数,然后使用它来注册的广播接收器:
// this.ctx传递给Thread构造
this.ctx.registerReceiver(headsetReceiver,新的IntentFilter(
Intent.ACTION_HEADSET_PLUG));
不要忘了最终{}注销您的接收器在你的线程或泄漏,可能会发生:
终于{
ctx.unregisterReceiver(headsetReceiver);
}
为了改变主线程(如一个活动)内的UI,你需要安装一个处理程序
I have a soundrecorder android thread and i need to know if mic/headset is connected or not while recording,so i need to use a BroadcastReceiver() inside the thread.how can i register that? this.registerReceiver() wont work because it only works inside activities.
If using broadcasereceivers inside a thread is not a good idea,so whats the solution?
here is the code which would work inside an activity and wont work inside a thread:
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));
You will need to pass the context to the Thread constructor and then use it to register the broadcast receiver:
//this.ctx is passed to the Thread constructor
this.ctx.registerReceiver(headsetReceiver, new IntentFilter(
Intent.ACTION_HEADSET_PLUG));
Do not forget to unregister your receiver in finally{} in your Thread or leaks may occur:
finally{
ctx.unregisterReceiver(headsetReceiver);
}
In order to change UI inside main thread(eg an activity), you will need to setup a handler
这篇关于如何注册一个BroadcastReceiver()一个线程内的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!