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:
Do not forget to unregister your receiver in finally{} in your Thread or leaks may occur:
In order to change UI inside main thread(eg an activity), you will need to setup a handler