[Android开发常见问题-5] 如何检测耳机的插入状态
近期在研究如何通过耳机进行一些控制操作,自然涉及到如何检测耳机是否插入的状态,经过一番查询和实验,总结如下
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();
}
}
}
}
}
正常运行后,插入耳机时会提醒“耳机已插入”,拔出耳机时提醒“耳机未插入”。
补充:移动开发 , Android ,