如何在Android Pie和UP中以编程方式打开/关闭扬声器 [英] how to turn speaker on/off programmatically in android Pie and UP
问题描述
与此问题以及几年前的许多其他问题相同:如何在Android中以编程方式打开/关闭扬声器4.0
Same as this question and many others from a few years ago: how to turn speaker on/off programmatically in android 4.0
Android似乎已经改变了处理方式.
It seems that Android has changed the way it handles this.
以下是我尝试拨打电话以通过编程方式设置免提电话的操作.这些解决方案都无法在Android Pie上为我工作.虽然它们似乎在Android Nougat和Oreo上运行良好
here are the things I tried to make an Outgoing call to have a speakerphone programmatically. None of these solutions worked for me on Android Pie. while they seem to work well on Android Nougat and Oreo
解决方案1.
final static int FOR_MEDIA = 1;
final static int FORCE_NONE = 0;
final static int FORCE_SPEAKER = 1;
Class audioSystemClass = Class.forName("android.media.AudioSystem");
Method setForceUse = audioSystemClass.getMethod("setForceUse", int.class, int.class);
setForceUse.invoke(null, FOR_MEDIA, FORCE_SPEAKER);
2.
AudioManager audioManager = (AudioManager)getApplicationContext().getSystemService(Context.AUDIO_SERVICE);
if (audioManager != null) {
audioManager.setMode(AudioManager.MODE_IN_COMMUNICATION);
audioManager.setSpeakerphoneOn(true);
3.
AudioManager audioManager = (AudioManager)getApplicationContext().getSystemService(Context.AUDIO_SERVICE);
if (audioManager != null) {
audioManager.setMode(AudioManager.MODE_IN_CALL);
audioManager.setSpeakerphoneOn(true);
4.
Thread thread = new Thread() {
@Override
public void run() {
try {
while(true) {
sleep(1000);
audioManager.setMode(AudioManager.MODE_IN_CALL);
if (!audioManager.isSpeakerphoneOn())
audioManager.setSpeakerphoneOn(true);
}
} catch (InterruptedException e) {
e.printStackTrace();
}
}
};
thread.start();
该应用程序具有以下许多其他授予的权限:
the app has the following permissions granted among many others:
<uses-permission android:name="android.permission.CALL_PHONE"/>
<uses-permission android:name="android.permission.MODIFY_AUDIO_SETTINGS"/>
<uses-permission android:name="android.permission.MODIFY_PHONE_STATE" />
我也仅对拨出电话尝试了以下解决方案.而且也不起作用.
I have also tried the following solution only for outgoing calls. and it also didn't work.
Intent callIntent = new Intent(Intent.ACTION_CALL);
callIntent.putExtra("speaker", true);
callIntent.setData(Uri.parse("tel:" + number));
context.startActivity(callIntent);
推荐答案
在Android Pie中,我遇到了同样的问题.我使用 InCallService 和
In Android Pie, I had the same problem. I resolved it using an InCallService with
setAudioRoute(ROUTE_SPEAKER)
您的应用程序必须是默认电话应用程序.
Your app needs to be Default phone app.
这篇关于如何在Android Pie和UP中以编程方式打开/关闭扬声器的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!