При использовании API 8 мой широковещательный приемник вызывается без создания службы или запроса дополнительных разрешений.
Вы можете определить внутренний класс в своей основной деятельности, подобный тому, который я определил ниже:
public class HeadSetBroadCastReceiver extends BroadcastReceiver
{
@Override
public void onReceive(Context context, Intent intent) {
// TODO Auto-generated method stub
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
}
}
}
}
Затем зарегистрируйте приемник вещания динамически или статически. Я зарегистрировал мой динамически в методе onCreate () моей Activity:
this.registerReceiver(headsetReceiver, new IntentFilter(Intent.ACTION_HEADSET_PLUG));
Убедитесь, что вы отменили регистрацию вашего BroadcastReceiver с помощью контекста unregisterReceiver. В моем случае я сделал это в методе onDestroy (). Это должно сделать это.