嗨,我正在處理一個應用程序,當耳機從手機中移除時會生成一個事件。 我已經創建與接收方法的廣播接收器作爲BroadcastReceiver用於拔掉耳機
public void onReceive(Context context, Intent intent) {
// TODO Auto-generated method stub
String action = intent.getAction();
Log.i("Broadcast Receiver", "Hello");
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
}
}
}
調用此方法如下
IntentFilter receiverFilter = new IntentFilter(Intent.ACTION_HEADSET_PLUG);
HeadSetBroadCastReceiver receiver = new HeadSetBroadCastReceiver();
registerReceiver(receiver, receiverFilter);
也我有清單中註冊此作爲
<receiver android:name=".HeadsetBroadCastReceiver">
<intent-filter>
<action android:name="android.intent.action.ACTION_HEADSET_PLUG"/>
</intent-filter>
</receiver>
和權限
但是這並不奏效可以你通過這個指導我嗎?
共同的傢伙沒人能指導我? – Sumit 2012-07-30 06:47:50
[選中此項](http:// stackoverflow。問題/ 4092438/intent-action-headset-plug-is-received-when-activity-starts) – 2012-07-30 07:11:36
[This works](http://stackoverflow.com/a/6366238/726863) – 2012-07-30 07:23:36