以下是通过辅助功能事件检测拨出呼叫的代码 -
在您的项目中添加一个扩展 AccessibilityService 的类 -
public class CallDetection extends AccessibilityService {
@Override
public void onAccessibilityEvent(AccessibilityEvent event) {
acquireLock(this);
Log.d("myaccess","after lock");
if (event.getEventType() == AccessibilityEvent.TYPE_WINDOW_CONTENT_CHANGED) {
Log.d("myaccess","in window changed");
AccessibilityNodeInfo info = event.getSource();
if (info != null && info.getText() != null) {
String duration = info.getText().toString();
String zeroSeconds = String.format("%02d:%02d", new Object[]{Integer.valueOf(0), Integer.valueOf(0)});
String firstSecond = String.format("%02d:%02d", new Object[]{Integer.valueOf(0), Integer.valueOf(1)});
Log.d("myaccess","after calculation - "+ zeroSeconds + " --- "+ firstSecond + " --- " + duration);
if (zeroSeconds.equals(duration) || firstSecond.equals(duration)) {
Toast.makeText(getApplicationContext(),"Call answered",Toast.LENGTH_SHORT).show();
// Your Code goes here
}
info.recycle();
}
}
}
@Override
protected void onServiceConnected() {
super.onServiceConnected();
Toast.makeText(this,"Service connected",Toast.LENGTH_SHORT).show();
AccessibilityServiceInfo info = new AccessibilityServiceInfo();
info.eventTypes = AccessibilityEvent.TYPE_WINDOW_CONTENT_CHANGED;
info.feedbackType = AccessibilityServiceInfo.FEEDBACK_GENERIC;
info.notificationTimeout = 0;
info.packageNames = null;
setServiceInfo(info);
}
@Override
public void onInterrupt() {
}
}
但要让event.getSource() 函数工作,你必须通过xml 指定一些服务配置,所以在你的项目中创建一个xml 文件夹并添加一个名为serviceconfig 的xml 文件。 xml(你可以给任何你想要的名字。
serviceconfig的内容如下——
<accessibility-service xmlns:android="http://schemas.android.com/apk/res/android"
android:description="@string/callDetection"
android:accessibilityEventTypes="typeWindowContentChanged"
android:notificationTimeout="100"
android:canRetrieveWindowContent="true"
/>
您可以在Here中找到更多关于serviceconfig的信息
现在像这样在 Manifest 文件中添加您的服务 -
<service android:name=".CallDetection"
android:permission="android.permission.BIND_ACCESSIBILITY_SERVICE"
android:label="@string/callDetection">
<intent-filter>
<action android:name="android.accessibilityservice.AccessibilityService" />
</intent-filter>
<meta-data
android:name="android.accessibilityservice"
android:resource="@xml/serviceconfig" />
</service>
大功告成,只需运行该应用程序并转到手机中的辅助功能设置,您将找到一个名为检测(或任何您喜欢的名称)的选项已作为您的服务描述提供),将其打开以授予您应用的访问权限。
现在您会在接听电话时看到祝酒词。
您可以在其中编写任何您想要的代码,也可以在您的活动中调用回调函数
最重要的 - 在接听电话之前不要拨打您的通话窗口(Android 拨号器窗口),否则这将不起作用。
注意 - 由于 android 没有提供任何解决方案来检测呼叫是否被应答,这是我所做的最好的选择,希望它对你有用。