cmc*_*nce 46
您可以使用广播接收器.
所以,您可以在"AndroidManifest.xml"中编写此代码
<receiver android:name="com.juno.brheadset.HeadsetStateReceiver">
<intent-filter>
<action android:name="android.intent.action.HEADSET_PLUG"/>
</intent-filter>
</receiver>-->
Run Code Online (Sandbox Code Playgroud)
但是,这不起作用.当OS发送此"HEADSET_PLUG"意图时,OS会设置标志"Intent.FLAG_RECEIVER_REGISTERED_ONLY"因此,您应该在Activity或Service类中编写如下代码,而不是"AndroidManifest".
public class BRHeadsetActivity extends Activity {
/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
IntentFilter receiverFilter = new IntentFilter(Intent.ACTION_HEADSET_PLUG);
HeadsetStateReceiver receiver = new HeadsetStateReceiver();
registerReceiver( receiver, receiverFilter );
}
Run Code Online (Sandbox Code Playgroud)
我希望这篇文章可以帮到你.再见!
这是"HeadsetObserver.java",Android SDK Source的一部分.
private final void sendIntent(int headset, int headsetState, int prevHeadsetState, String headsetName) {
if ((headsetState & headset) != (prevHeadsetState & headset)) {
// Pack up the values and broadcast them to everyone
Intent intent = new Intent(Intent.ACTION_HEADSET_PLUG);
**intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY);**
int state = 0;
int microphone = 0;
if ((headset & HEADSETS_WITH_MIC) != 0) {
microphone = 1;
}
if ((headsetState & headset) != 0) {
state = 1;
}
intent.putExtra("state", state);
intent.putExtra("name", headsetName);
intent.putExtra("microphone", microphone);
if (LOG) Slog.v(TAG, "Intent.ACTION_HEADSET_PLUG: state: "+state+" name: "+headsetName+" mic: "+microphone);
// TODO: Should we require a permission?
ActivityManagerNative.broadcastStickyIntent(intent, null);
}
}
Run Code Online (Sandbox Code Playgroud)
Ebo*_*ike 31
当你说"耳机"时,你的意思是"有线耳机"吗?如果是这样,就有意识到是否插入或拔出插头:ACTION_HEADSET_PLUG.
要检查状态,您可以使用AudioManager.isWiredHeadsetOn(),但如果还有蓝牙耳机可能会返回false,并且音频将路由到该状态.
小智 15
AudioManager.isWiredHeadsetOn()总是返回,false因为它需要用户权限MODIFY_AUDIO_SETTINGS.
我花了几天时间找到答案.官方文档中没有关于此的信息.这bug已经注册了BugTracker.
| 归档时间: |
|
| 查看次数: |
44706 次 |
| 最近记录: |