近期在研究如何通過耳機進行一些控制操作,自然涉及到如何檢測耳機是否插入的狀態,經過一番查詢和實驗,總結如下
1.原理:
其實android系統在耳機插入和拔出的時候都會發送廣播,所以我們要想檢測耳機的狀態只需要註冊響應的BroadCastReceiver,對狀態進行響應的判斷就ok了。
這個廣播的名字叫做:android.intent.action.HEADSET_PLUG
注意,在manifest.xml裡面要添加響應的許可權:
<uses-permission android:name="android.permission.MODIFY_AUDIO_SETTINGS" />
注意,廣播要在java檔案中動態註冊。
2.代碼
[java]
/**
* Created By:alex
*/
package com.alex.erji;
import android.app.Activity;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.Bundle;
import android.widget.Toast;
public class MainActivity extends Activity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
//給廣播綁定響應的過濾器
IntentFilter intentFilter = new IntentFilter();
intentFilter.addAction("android.intent.action.HEADSET_PLUG");
HeadsetReceiver headsetReceiver = new HeadsetReceiver();
registerReceiver(headsetReceiver, intentFilter);
}
//自己定義的廣播接收器
public class HeadsetReceiver extends BroadcastReceiver {
@Override
public void onReceive(Context context, Intent intent) {
if (intent.hasExtra("state")) {
if (0 == intent.getIntExtra("state", 0)) {
Toast.makeText(context, "耳機未插入", Toast.LENGTH_SHORT).show();
} else if (1 == intent.getIntExtra("state", 0)) {
Toast.makeText(context, "耳機已插入", Toast.LENGTH_SHORT).show();
}
}
}
}
}
/**
* Created By:alex
*/
package com.alex.erji;
import android.app.Activity;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.Bundle;
import android.widget.Toast;
public class MainActivity extends Activity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
//給廣播綁定響應的過濾器
IntentFilter intentFilter = new IntentFilter();
intentFilter.addAction("android.intent.action.HEADSET_PLUG");
HeadsetReceiver headsetReceiver = new HeadsetReceiver();
registerReceiver(headsetReceiver, intentFilter);
}
//自己定義的廣播接收器
public class HeadsetReceiver extends BroadcastReceiver {
@Override
public void onReceive(Context context, Intent intent) {
if (intent.hasExtra("state")) {
if (0 == intent.getIntExtra("state", 0)) {
Toast.makeText(context, "耳機未插入", Toast.LENGTH_SHORT).show();
} else if (1 == intent.getIntExtra("state", 0)) {
Toast.makeText(context, "耳機已插入", Toast.LENGTH_SHORT).show();
}
}
}
}
}
正常運行後,插入耳機時會提醒“耳機已插入”,拔出耳機時提醒“耳機未插入”。