(O)Telephony分析之通话流程分析(二)拨打电话流程分析(上)

本文详细解析了手机拨号盘界面的拨号流程,涵盖从用户输入号码到通话建立的关键步骤,深入理解Telephony系统的工作机制。
拨打电话,是从通话的拨号盘开始的,而拨号盘的界面是在DialpadFragment,因此,需要从这个地方进行分析

一.拨号盘界面拨号流程

public void onClick(View view) {
    ......
    if (resId == R.id.dialpad_floating_action_button) {
        view.performHapticFeedback(HapticFeedbackConstants.VIRTUAL_KEY);
        // 处理Dial Button点击事件
        handleDialButtonPressed();
    }
    ......
}
通过调用handleDialButtonPressed方法,处理点击拨号按钮后的流程

private void handleDialButtonPressed() {
	// 没有输入号码的情况下,暂不讨论
    if (isDigitsEmpty()) { // No number entered.
        handleDialButtonClickWithEmptyDigits();
    } else {
    	......
      // uri加上tel前缀,并且type设置为INITIATION_DIALPAD,生成URI
      final Intent intent = new CallIntentBuilder(number).setCallInitiationType(LogState.INITIATION_DIALPAD).build();
            // Leo, 尝试去启动一个Activity,如果启动不了,会弹出一个 "Activity is not found" 的Toast框
      DialerUtils.startActivityWithErrorToast(getActivity(), intent);
      // Leo,隐藏拨号盘,并且清除号码盘上的号码
      hideAndClearDialpad(false);  
    }
}
可以看到此处通过初始化CallIntentBuilder,然后调用其build方法,生成一个Intent对象,并作为参数,调用DialerUtils的startActivityWithErrorToast方法
public static class CallIntentBuilder {
    ......
    public CallIntentBuilder(Uri uri) {
        mUri = uri;
    }

    public CallIntentBuilder(String number) {
        this(CallUtil.getCallUri(number));
    }

    public CallIntentBuilder setCallInitiationType(int initiationType) {
        mCallInitiationType = initiationType;
        return this;
    }

    public Intent build() {
    	// Leo, 初始化一个Intent
        return getCallIntent(
                mUri,
                mPhoneAccountHandle,
                mIsVideoCall ? VideoProfile.STATE_BIDIRECTIONAL : VideoProfile.STATE_AUDIO_ONLY,
                mCallInitiationType);
    }
}
从这边来看,首先通过构造方法,将number生成一个Uri,然后通过build方法调用getCallIntent方法,返回一个Intent,而通过上述了解,
知道getCallIntent的参数分别为,
第一个参数为刚刚生成的Uri对象,其是以tel:为前缀的
第二个参数由于并未设置过,因此为null
第三个参数由于没有设置过视频通话,因此为VideoProfile.STATE_AUDIO_ONLY,语音通话
第四个参数为传入的LogState.INITIATION_DIALPAD

public static Intent getCallIntent(
        Uri uri, PhoneAccountHandle accountHandle, int videoState, int callIntiationType) {
	// 初始化一个Intent,action为CALL_ACTION,Data为uri
    final Intent intent = new Intent(CALL_ACTION, uri);
    // 目前应该是没有videoState的,即为VideoProfile.STATE_AUDIO_ONLY
    intent.putExtra(TelecomManager.EXTRA_START_CALL_WITH_VIDEO_STATE, videoState);

    final Bundle b = new Bundle();
    // 设置其INITIATION_TYPE,此处第一次为LogState.INITIATION_DIALPAD
    b.putInt(EXTRA_CALL_INITIATION_TYPE, callIntiationType);
    // 设置其Extra
    intent.putExtra(TelecomManager.EXTRA_OUTGOING_CALL_EXTRAS, b);

    // 此前没有设置,应该为null
    
<think>我们正在开发一个后台服务,用于在后台拨打电话。在Android中,拨打电话通常使用Intent.ACTION_CALL,但需要注意的是,在后台服务中直接启动Activity(如拨号界面)是不合适的,因为服务没有界面。另外,从Android 10(API 29)开始,后台启动Activity受到限制。因此,我们需要考虑使用其他方法。 然而,根据Android的安全策略,拨打电话需要用户交互(比如用户点击按钮)或者前台服务(带有通知)来确保用户知晓。在后台服务中直接拨打电话可能会被系统阻止,除非应用是默认拨号应用或者具有特殊权限。 但是,我们可以通过使用`TelecomManager`的`placeCall`方法(需要系统权限)或者使用`Intent.ACTION_CALL`并启动一个Activity(但这样会跳出界面,不符合后台要求)。因此,我们需要权衡: 1. 如果应用是默认拨号应用,那么可以使用`TelecomManager.placeCall`方法。 2. 否则,可能需要启动一个Activity(比如在通知中点击后启动拨号界面)或者使用前台服务并显示一个通知,用户通过通知控制。 但是,根据问题,我们希望在后台服务中直接拨打电话,即不需要用户交互。这通常需要系统应用权限(比如系统预装应用)或者设备制造商签名。普通应用很难实现。 不过,我们可以尝试以下方法: 方法一:使用Intent.ACTION_CALL,并添加FLAG_ACTIVITY_NEW_TASK标志启动一个Activity,但这样会跳出拨号界面,并且从Android 10开始,后台启动Activity被禁止(除非满足特定条件,比如用户点击通知)。 方法:使用`TelecomManager`的`placeCall`方法,但需要满足: - 应用具有`CALL_PHONE`权限 - 应用具有`MANAGE_OWN_CALLS`权限(如果针对Android 10+) - 应用被设为默认拨号应用(通过`TelecomManager`的`getDefaultDialerPackage`和`setDefaultDialerPackage`) 但是,将应用设为默认拨号应用需要用户手动设置。 因此,实现方案如下: 步骤1:在AndroidManifest.xml中声明权限 ```xml <uses-permission android:name="android.permission.CALL_PHONE" /> <uses-permission android:name="android.permission.MANAGE_OWN_CALLS" /> ``` 注意:`MANAGE_OWN_CALLS`权限在Android 10(API 29)引入,用于管理自己的通话。 步骤2:请求用户将应用设置为默认拨号应用(如果应用不是默认拨号应用,则无法使用`placeCall`在后台拨打电话) 步骤3:在服务中使用`TelecomManager`拨打电话 代码示例: 1. 检查并请求成为默认拨号应用(在Activity中,因为需要用户交互): ```java if (!isDefaultDialer()) { // 提示用户设置 Intent intent = new Intent(TelecomManager.ACTION_CHANGE_DEFAULT_DIALER); intent.putExtra(TelecomManager.EXTRA_CHANGE_DEFAULT_DIALER_PACKAGE_NAME, getPackageName()); startActivity(intent); } private boolean isDefaultDialer() { TelecomManager tm = (TelecomManager) getSystemService(Context.TELECOM_SERVICE); return tm != null && getPackageName().equals(tm.getDefaultDialerPackage()); } ``` 2. 在服务中拨打电话(需要先确保应用是默认拨号应用): ```java public class CallService extends Service { @Override public int onStartCommand(Intent intent, int flags, int startId) { if (intent != null) { String number = intent.getStringExtra("number"); if (number != null) { makeCall(number); } } return START_STICKY; } private void makeCall(String number) { TelecomManager telecomManager = (TelecomManager) getSystemService(Context.TELECOM_SERVICE); if (telecomManager != null) { Uri uri = Uri.fromParts(PhoneAccount.SCHEME_TEL, number, null); Bundle extras = new Bundle(); // 需要检查权限 if (ActivityCompat.checkSelfPermission(this, Manifest.permission.CALL_PHONE) == PackageManager.PERMISSION_GRANTED) { // 从Android 10开始,需要MANAGE_OWN_CALLS权限 if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) { extras.putBoolean(TelecomManager.EXTRA_START_CALL_WITH_SPEAKERPHONE, false); } telecomManager.placeCall(uri, extras); } } } } ``` 注意:即使应用是默认拨号应用,从Android 10开始,后台启动通话也需要前台服务(Foreground Service)并显示通知。因此,我们需要将服务改为前台服务。 步骤4:将服务改为前台服务(在onStartCommand中启动为前台服务) ```java @Override public int onStartCommand(Intent intent, int flags, int startId) { // 创建通知渠道(针对Android 8.0+) if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) { NotificationChannel channel = new NotificationChannel("call_channel", "Call Service", NotificationManager.IMPORTANCE_DEFAULT); NotificationManager manager = (NotificationManager) getSystemService(NOTIFICATION_SERVICE); manager.createNotificationChannel(channel); } Notification notification = new NotificationCompat.Builder(this, "call_channel") .setContentTitle("Call Service") .setContentText("Making a call...") .setSmallIcon(R.drawable.ic_notification) .build(); startForeground(1, notification); // 拨打电话 // ... 同上 return START_STICKY; } ``` 但是,请注意:即使这样,后台拨打电话仍然可能被系统限制。因为拨打电话是一个敏感操作,系统可能会要求用户确认。另外,用户必须将应用设置为默认拨号应用。 替代方案:使用无障碍服务(AccessibilityService)模拟用户操作拨打电话,但这种方法复杂且不稳定,而且需要用户手动开启无障碍权限,不推荐。 总结:在后台服务中拨打电话的可行方案是: 1. 应用成为默认拨号应用(用户手动设置) 2. 使用TelecomManager.placeCall方法 3. 服务必须为前台服务(显示通知) 注意:普通应用(非系统应用)无法在后台无声无息地拨打电话,这是出于安全考虑。 如果应用不能成为默认拨号应用,则只能通过启动Activity的方式(跳出拨号界面)来拨打电话,但这不符合后台执行的要求。 因此,请根据应用的实际需求(比如是否是拨号应用)来选择实现方式。 相关问题: 1. 如何将应用设置为默认拨号应用? 2. 在Android 10以上,后台启动Activity的限制是什么? 3. 如何通过无障碍服务模拟拨打电话? 4. 前台服务通知的详细配置方法?</think>### Android Service 后台拨打电话实现方法 在 Android 服务中实现后台拨打电话需要解决两个核心问题:**电话权限管理**和**后台执行限制**。以下是完整实现方案: --- ### 一、基础实现步骤 #### 1. 声明权限 ```xml <!-- AndroidManifest.xml --> <uses-permission android:name="android.permission.CALL_PHONE"/> <uses-permission android:name="android.permission.READ_PHONE_STATE"/> ``` #### 2. 创建电话服务 ```java public class CallService extends Service { @Override public int onStartCommand(Intent intent, int flags, int startId) { String phoneNumber = intent.getStringExtra("PHONE_NUMBER"); makeCall(phoneNumber); return START_STICKY; } private void makeCall(String number) { try { Uri uri = Uri.parse("tel:" + number); Intent callIntent = new Intent(Intent.ACTION_CALL, uri); callIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK); startActivity(callIntent); } catch (SecurityException e) { Log.e("CallService", "拨号权限被拒绝"); } } } ``` #### 3. 启动服务 ```java // 在Activity或BroadcastReceiver中 Intent serviceIntent = new Intent(context, CallService.class); serviceIntent.putExtra("PHONE_NUMBER", "13800138000"); ContextCompat.startForegroundService(context, serviceIntent); ``` --- ### 、关键问题解决方案 #### 1. 后台执行限制 (Android 8.0+) ```java // 在CallService的onCreate()中添加 @Override public void onCreate() { super.onCreate(); if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) { NotificationChannel channel = new NotificationChannel( "call_channel", "电话服务", NotificationManager.IMPORTANCE_LOW ); NotificationManager manager = getSystemService(NotificationManager.class); manager.createNotificationChannel(channel); Notification notification = new NotificationCompat.Builder(this, "call_channel") .setContentTitle("电话服务运行中") .setSmallIcon(R.drawable.ic_call) .build(); startForeground(1, notification); // 转为前台服务 } } ``` #### 2. 权限动态申请 ```java // 在Activity中请求权限 private void requestCallPermission() { if (ContextCompat.checkSelfPermission(this, Manifest.permission.CALL_PHONE) != PackageManager.PERMISSION_GRANTED) { ActivityCompat.requestPermissions( this, new String[]{Manifest.permission.CALL_PHONE}, REQUEST_CALL_PERMISSION ); } else { startCallService(); } } @Override public void onRequestPermissionsResult(int requestCode, String[] permissions, int[] grantResults) { if (requestCode == REQUEST_CALL_PERMISSION && grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) { startCallService(); } } ``` --- ### 三、厂商兼容方案 #### 华为设备特殊处理 ```java private void makeHuaweiCall(String number) { try { Class<?> hwManager = Class.forName("com.huawei.android.telephony.TelephonyManagerEx"); Method method = hwManager.getMethod("invokeOemRilRequestRaw", byte[].class, Message.class); byte[] dialCmd = ("ATD" + number + ";").getBytes(); method.invoke(null, dialCmd, null); } catch (Exception e) { Log.e("HuaweiCall", "华为特殊拨号失败", e); makeNormalCall(number); // 回退标准方式 } } ``` --- ### 四、完整调用流程 1. **权限检查**:动态请求`CALL_PHONE`权限 2. **启动服务**: ```java if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) { startForegroundService(serviceIntent); } else { startService(serviceIntent); } ``` 3. **服务执行**: - Android 8.0+ 转为前台服务 - 根据设备厂商选择拨号方式 - 通过`ACTION_CALL`发起通话 --- ### 五、注意事项 1. **系统限制**: - Android 10+ 后台启动Activity受限,需使用前台服务 - 部分厂商(小米、华为)需要额外权限[^1] 2. **权限要求**: ```xml <!-- 小米设备需要 --> <uses-permission android:name="android.permission.MANAGE_OWN_CALLS"/> ``` 3. **政策合规**: - Google Play禁止滥用电话权限 - 需在应用描述中明确告知电话功能用途 - 提供显性的用户操作入口(不能完全后台静默拨打) --- ### 替代方案:无障碍服务 ```java public class CallAccessibilityService extends AccessibilityService { @Override public void onAccessibilityEvent(AccessibilityEvent event) { if (event.getEventType() == AccessibilityEvent.TYPE_WINDOW_STATE_CHANGED) { performGlobalAction(GLOBAL_ACTION_END_CALL); // 挂断电话 // 或通过界面模拟拨号 } } } ``` > **配置说明**: > 1. 在`res/xml/service_config.xml`声明服务 > 2. 用户需手动在系统设置启用无障碍服务[^3] ---
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值