gpt4 book ai didi

android - Android "OS"如何检测来电

转载 作者:塔克拉玛干 更新时间:2023-11-02 08:56:11 24 4
gpt4 key购买 nike

我想知道:

  1. android 操作系统如何检测来电(号码)并显示联系人姓名并为我们提供接听电话的选项。
  2. 点击“结束调用按钮”时操作系统内部会发生什么。

当我对此进行搜索时,我只获得了创建我自己的应用程序的类和方法。请求解释。

最佳答案

在 Android 中,可以使用内置的 TelephonyManager 检测调用事件应用程序接口(interface)。 TelephonyManager类提供对有关设备上的电话服务的信息的访问。

示例:

创建一个名为MyCallReceiver 的新类

package com.example;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.telephony.TelephonyManager;
import android.widget.Toast;

public class MyCallReceiver extends BroadcastReceiver {

@Override
public void onReceive(Context context, Intent intent) {

if (intent.getStringExtra(TelephonyManager.EXTRA_STATE).equals(TelephonyManager.EXTRA_STATE_RINGING)) {
// This code will execute when the phone has an incoming call

// get the phone number
String incomingNumber = intent.getStringExtra(TelephonyManager.EXTRA_INCOMING_NUMBER);
Toast.makeText(context, "Call from:" +incomingNumber, Toast.LENGTH_LONG).show();

} else if (intent.getStringExtra(TelephonyManager.EXTRA_STATE).equals(
TelephonyManager.EXTRA_STATE_IDLE)
|| intent.getStringExtra(TelephonyManager.EXTRA_STATE).equals(
TelephonyManager.EXTRA_STATE_OFFHOOK)) {
// This code will execute when the call is disconnected
Toast.makeText(context, "Detected call hangup event", Toast.LENGTH_LONG).show();

}
}
}

BroadcastReceiver 类将监视手机状态,只要手机状态发生变化,就会调用 BroadcastReceiver 的 onReceive() 方法。

添加 READ_PHONE_STATE AndroidManifest.xml 中的权限

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.example"
android:versionCode="1"
android:versionName="1.0" >

<uses-sdk
android:minSdkVersion="8"
android:targetSdkVersion="18" />

<uses-permission android:name="android.permission.READ_PHONE_STATE" />

<application
android:allowBackup="true"
android:icon="@drawable/ic_launcher"
android:label="@string/app_name"
android:theme="@style/AppTheme" >
<activity
android:name="com.example.MainActivity"
android:label="@string/app_name" >
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>

<receiver android:name="com.example.MyCallReceiver" >
<intent-filter>
<action android:name="android.intent.action.PHONE_STATE" />
</intent-filter>
</receiver>
</application>

</manifest>

检查此引用资料:BroadcastReceiver

关于android - Android "OS"如何检测来电,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27105315/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com