在Android开发中,可以通过使用TelephonyManager类来控制接听和挂断电话。以下是一个简单的示例: ```java import android.Manifest; import android.content.Context; import android.content.pm.PackageManager; import android.telephony.TelephonyManager; import android.util.Log; public class PhoneUtils { private static final String TAG = "PhoneUtils"; public static final int MY_PERMISSIONS_REQUEST_PHONE = 100; private static final String[] PERMISSIONS_PHONE = new String[]{Manifest.permission.READ_PHONE_STATE}; private PhoneUtils() { } public static boolean checkSelfPermission(Context context, String permission) { return context.checkSelfPermission(permission) == PackageManager.PERMISSION_GRANTED; } public static boolean hasPhonePermissions(Context context) { for (String permission : PERMISSIONS_PHONE) { if (!checkSelfPermission(context, permission)) { return false; } } return true; } public static void requestPhonePermissions(Context context) { if (hasPhonePermissions(context)) { return; } ActivityCompat.requestPermissions( context, PERMISSIONS_PHONE, MY_PERMISSIONS_REQUEST_PHONE ); } public static void answerPhone(Context context) { if (!hasPhonePermissions(context)) { Log.d(TAG, "Phone permissions not granted, cannot answer phone."); return; } TelephonyManager telephonyManager = (TelephonyManager) context.getSystemService(Context.TELEPHONY_SERVICE); try { telephonyManager answeringCall(); Log.d(TAG, "Answering phone call..."); } catch (Exception e) { Log.d(TAG, "Error answering phone call: " + e.getMessage()); } } public static void hangUpPhone(Context context) { if (!hasPhonePermissions(context)) { Log.d(TAG, "Phone permissions not granted, cannot hang up phone."); return; } TelephonyManager telephonyManager = (TelephonyManager) context.getSystemService(Context.TELEPHONY_SERVICE); try { telephonyManager.endCall(); Log.d(TAG, "Ending phone call..."); } catch (Exception e) { Log.d(TAG, "Error ending phone call: " + e.getMessage()); } } } ``` 在这个示例中,我们首先检查应用是否已经具有读取电话状态的权限。如果没有,我们就请求这些权限。然后,我们提供两个方法,一个用于接听电话,一个用于挂断电话。 这些方法可能会抛出Exception,所以你需要在调用这些方法时进行适当的错误处理。这些方法可能在某些设备上不可用,因此在实际使用时,你可能需要添加一些错误检查和处理代码。 [2023-11-07 22:45:16 | AI问答 | 557点数解答]