├── .gitignore ├── .idea ├── AndroidProjectSystem.xml ├── caches │ └── build_file_checksums.ser ├── checkstyle-idea.xml ├── codeStyles │ ├── Project.xml │ └── codeStyleConfig.xml ├── compiler.xml ├── deploymentTargetDropDown.xml ├── deploymentTargetSelector.xml ├── dictionaries │ └── Cerie.xml ├── encodings.xml ├── gradle.xml ├── jarRepositories.xml ├── markdown-navigator.xml ├── markdown-navigator │ └── profiles_settings.xml ├── migrations.xml ├── misc.xml ├── runConfigurations.xml └── vcs.xml ├── LICENSE ├── README.md ├── app ├── .gitignore ├── build.gradle ├── proguard-rules.pro └── src │ ├── androidTest │ └── java │ │ └── com │ │ └── ajiew │ │ └── phonecallapp │ │ └── ExampleInstrumentedTest.java │ ├── main │ ├── AndroidManifest.xml │ ├── java │ │ └── com │ │ │ └── ajiew │ │ │ └── phonecallapp │ │ │ ├── ActivityStack.java │ │ │ ├── MainActivity.java │ │ │ ├── listenphonecall │ │ │ ├── CallListenerService.java │ │ │ └── PhoneStateListenerCompat.java │ │ │ └── phonecallui │ │ │ ├── PhoneCallActivity.java │ │ │ ├── PhoneCallManager.java │ │ │ └── PhoneCallService.java │ └── res │ │ ├── drawable │ │ ├── ic_phone_call_in.xml │ │ ├── ic_phone_call_out.xml │ │ ├── ic_phone_hang_up.xml │ │ └── ic_phone_pick_up.xml │ │ ├── layout │ │ ├── activity_main.xml │ │ ├── activity_phone_call.xml │ │ └── view_phone_call.xml │ │ ├── mipmap-hdpi │ │ └── ic_launcher.png │ │ ├── mipmap-mdpi │ │ └── ic_launcher.png │ │ ├── mipmap-xhdpi │ │ └── ic_launcher.png │ │ ├── mipmap-xxhdpi │ │ └── ic_launcher.png │ │ ├── mipmap-xxxhdpi │ │ └── ic_launcher.png │ │ └── values │ │ ├── colors.xml │ │ ├── strings.xml │ │ └── styles.xml │ └── test │ └── java │ └── com │ └── ajiew │ └── phonecallapp │ └── ExampleUnitTest.java ├── build.gradle ├── gradle.properties ├── gradle └── wrapper │ ├── gradle-wrapper.jar │ └── gradle-wrapper.properties ├── gradlew ├── gradlew.bat ├── media ├── Screenshot_375x667.png ├── listen_phone_call.gif └── replace_default_phone_app.gif └── settings.gradle /.gitignore: -------------------------------------------------------------------------------- 1 | *.iml 2 | .gradle 3 | /local.properties 4 | /.idea/caches 5 | /.idea/libraries 6 | /.idea/modules.xml 7 | /.idea/workspace.xml 8 | .DS_Store 9 | /build 10 | /captures 11 | .externalNativeBuild 12 | -------------------------------------------------------------------------------- /.idea/AndroidProjectSystem.xml: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 6 | -------------------------------------------------------------------------------- /.idea/caches/build_file_checksums.ser: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/aJIEw/PhoneCallApp/54ade14439d949d2bd9b5b75ea346d2803dc0cf6/.idea/caches/build_file_checksums.ser -------------------------------------------------------------------------------- /.idea/checkstyle-idea.xml: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 15 | 16 | -------------------------------------------------------------------------------- /.idea/codeStyles/Project.xml: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 7 | 8 | 9 |
10 | 11 | 12 | 13 | xmlns:android 14 | 15 | ^$ 16 | 17 | 18 | 19 |
20 |
21 | 22 | 23 | 24 | xmlns:.* 25 | 26 | ^$ 27 | 28 | 29 | BY_NAME 30 | 31 |
32 |
33 | 34 | 35 | 36 | .*:id 37 | 38 | http://schemas.android.com/apk/res/android 39 | 40 | 41 | 42 |
43 |
44 | 45 | 46 | 47 | .*:name 48 | 49 | http://schemas.android.com/apk/res/android 50 | 51 | 52 | 53 |
54 |
55 | 56 | 57 | 58 | name 59 | 60 | ^$ 61 | 62 | 63 | 64 |
65 |
66 | 67 | 68 | 69 | style 70 | 71 | ^$ 72 | 73 | 74 | 75 |
76 |
77 | 78 | 79 | 80 | .* 81 | 82 | ^$ 83 | 84 | 85 | BY_NAME 86 | 87 |
88 |
89 | 90 | 91 | 92 | .* 93 | 94 | http://schemas.android.com/apk/res/android 95 | 96 | 97 | ANDROID_ATTRIBUTE_ORDER 98 | 99 |
100 |
101 | 102 | 103 | 104 | .* 105 | 106 | .* 107 | 108 | 109 | BY_NAME 110 | 111 |
112 |
113 |
114 |
115 |
116 |
-------------------------------------------------------------------------------- /.idea/codeStyles/codeStyleConfig.xml: -------------------------------------------------------------------------------- 1 | 2 | 3 | 5 | -------------------------------------------------------------------------------- /.idea/compiler.xml: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | -------------------------------------------------------------------------------- /.idea/deploymentTargetDropDown.xml: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9 | 10 | 11 | 12 | 13 | 14 | 15 | 16 | 17 | -------------------------------------------------------------------------------- /.idea/deploymentTargetSelector.xml: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | 16 | 17 | 18 | -------------------------------------------------------------------------------- /.idea/dictionaries/Cerie.xml: -------------------------------------------------------------------------------- 1 | 2 | 3 | -------------------------------------------------------------------------------- /.idea/encodings.xml: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | -------------------------------------------------------------------------------- /.idea/gradle.xml: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 18 | 19 | -------------------------------------------------------------------------------- /.idea/jarRepositories.xml: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 9 | 10 | 14 | 15 | 19 | 20 | 24 | 25 | 29 | 30 | 34 | 35 | 39 | 40 | 44 | 45 | 49 | 50 | -------------------------------------------------------------------------------- /.idea/markdown-navigator.xml: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9 | 10 | 11 | 36 | 37 | 55 | 56 | 57 | 58 | 59 | 60 | 61 | 62 | 63 | 64 | 65 | 66 | 67 | 68 | 69 | 70 | 71 | 72 | 73 | 74 | 75 | 76 | 77 | 78 | -------------------------------------------------------------------------------- /.idea/markdown-navigator/profiles_settings.xml: -------------------------------------------------------------------------------- 1 | 2 | 3 | -------------------------------------------------------------------------------- /.idea/migrations.xml: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 9 | 10 | -------------------------------------------------------------------------------- /.idea/misc.xml: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 29 | 51 | 52 | 53 | 54 | 55 | 56 | 58 | -------------------------------------------------------------------------------- /.idea/runConfigurations.xml: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 16 | 17 | -------------------------------------------------------------------------------- /.idea/vcs.xml: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | Apache License 2 | Version 2.0, January 2004 3 | http://www.apache.org/licenses/ 4 | 5 | TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION 6 | 7 | 1. Definitions. 8 | 9 | "License" shall mean the terms and conditions for use, reproduction, 10 | and distribution as defined by Sections 1 through 9 of this document. 11 | 12 | "Licensor" shall mean the copyright owner or entity authorized by 13 | the copyright owner that is granting the License. 14 | 15 | "Legal Entity" shall mean the union of the acting entity and all 16 | other entities that control, are controlled by, or are under common 17 | control with that entity. For the purposes of this definition, 18 | "control" means (i) the power, direct or indirect, to cause the 19 | direction or management of such entity, whether by contract or 20 | otherwise, or (ii) ownership of fifty percent (50%) or more of the 21 | outstanding shares, or (iii) beneficial ownership of such entity. 22 | 23 | "You" (or "Your") shall mean an individual or Legal Entity 24 | exercising permissions granted by this License. 25 | 26 | "Source" form shall mean the preferred form for making modifications, 27 | including but not limited to software source code, documentation 28 | source, and configuration files. 29 | 30 | "Object" form shall mean any form resulting from mechanical 31 | transformation or translation of a Source form, including but 32 | not limited to compiled object code, generated documentation, 33 | and conversions to other media types. 34 | 35 | "Work" shall mean the work of authorship, whether in Source or 36 | Object form, made available under the License, as indicated by a 37 | copyright notice that is included in or attached to the work 38 | (an example is provided in the Appendix below). 39 | 40 | "Derivative Works" shall mean any work, whether in Source or Object 41 | form, that is based on (or derived from) the Work and for which the 42 | editorial revisions, annotations, elaborations, or other modifications 43 | represent, as a whole, an original work of authorship. For the purposes 44 | of this License, Derivative Works shall not include works that remain 45 | separable from, or merely link (or bind by name) to the interfaces of, 46 | the Work and Derivative Works thereof. 47 | 48 | "Contribution" shall mean any work of authorship, including 49 | the original version of the Work and any modifications or additions 50 | to that Work or Derivative Works thereof, that is intentionally 51 | submitted to Licensor for inclusion in the Work by the copyright owner 52 | or by an individual or Legal Entity authorized to submit on behalf of 53 | the copyright owner. For the purposes of this definition, "submitted" 54 | means any form of electronic, verbal, or written communication sent 55 | to the Licensor or its representatives, including but not limited to 56 | communication on electronic mailing lists, source code control systems, 57 | and issue tracking systems that are managed by, or on behalf of, the 58 | Licensor for the purpose of discussing and improving the Work, but 59 | excluding communication that is conspicuously marked or otherwise 60 | designated in writing by the copyright owner as "Not a Contribution." 61 | 62 | "Contributor" shall mean Licensor and any individual or Legal Entity 63 | on behalf of whom a Contribution has been received by Licensor and 64 | subsequently incorporated within the Work. 65 | 66 | 2. Grant of Copyright License. Subject to the terms and conditions of 67 | this License, each Contributor hereby grants to You a perpetual, 68 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 69 | copyright license to reproduce, prepare Derivative Works of, 70 | publicly display, publicly perform, sublicense, and distribute the 71 | Work and such Derivative Works in Source or Object form. 72 | 73 | 3. Grant of Patent License. Subject to the terms and conditions of 74 | this License, each Contributor hereby grants to You a perpetual, 75 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 76 | (except as stated in this section) patent license to make, have made, 77 | use, offer to sell, sell, import, and otherwise transfer the Work, 78 | where such license applies only to those patent claims licensable 79 | by such Contributor that are necessarily infringed by their 80 | Contribution(s) alone or by combination of their Contribution(s) 81 | with the Work to which such Contribution(s) was submitted. If You 82 | institute patent litigation against any entity (including a 83 | cross-claim or counterclaim in a lawsuit) alleging that the Work 84 | or a Contribution incorporated within the Work constitutes direct 85 | or contributory patent infringement, then any patent licenses 86 | granted to You under this License for that Work shall terminate 87 | as of the date such litigation is filed. 88 | 89 | 4. Redistribution. You may reproduce and distribute copies of the 90 | Work or Derivative Works thereof in any medium, with or without 91 | modifications, and in Source or Object form, provided that You 92 | meet the following conditions: 93 | 94 | (a) You must give any other recipients of the Work or 95 | Derivative Works a copy of this License; and 96 | 97 | (b) You must cause any modified files to carry prominent notices 98 | stating that You changed the files; and 99 | 100 | (c) You must retain, in the Source form of any Derivative Works 101 | that You distribute, all copyright, patent, trademark, and 102 | attribution notices from the Source form of the Work, 103 | excluding those notices that do not pertain to any part of 104 | the Derivative Works; and 105 | 106 | (d) If the Work includes a "NOTICE" text file as part of its 107 | distribution, then any Derivative Works that You distribute must 108 | include a readable copy of the attribution notices contained 109 | within such NOTICE file, excluding those notices that do not 110 | pertain to any part of the Derivative Works, in at least one 111 | of the following places: within a NOTICE text file distributed 112 | as part of the Derivative Works; within the Source form or 113 | documentation, if provided along with the Derivative Works; or, 114 | within a display generated by the Derivative Works, if and 115 | wherever such third-party notices normally appear. The contents 116 | of the NOTICE file are for informational purposes only and 117 | do not modify the License. You may add Your own attribution 118 | notices within Derivative Works that You distribute, alongside 119 | or as an addendum to the NOTICE text from the Work, provided 120 | that such additional attribution notices cannot be construed 121 | as modifying the License. 122 | 123 | You may add Your own copyright statement to Your modifications and 124 | may provide additional or different license terms and conditions 125 | for use, reproduction, or distribution of Your modifications, or 126 | for any such Derivative Works as a whole, provided Your use, 127 | reproduction, and distribution of the Work otherwise complies with 128 | the conditions stated in this License. 129 | 130 | 5. Submission of Contributions. Unless You explicitly state otherwise, 131 | any Contribution intentionally submitted for inclusion in the Work 132 | by You to the Licensor shall be under the terms and conditions of 133 | this License, without any additional terms or conditions. 134 | Notwithstanding the above, nothing herein shall supersede or modify 135 | the terms of any separate license agreement you may have executed 136 | with Licensor regarding such Contributions. 137 | 138 | 6. Trademarks. This License does not grant permission to use the trade 139 | names, trademarks, service marks, or product names of the Licensor, 140 | except as required for reasonable and customary use in describing the 141 | origin of the Work and reproducing the content of the NOTICE file. 142 | 143 | 7. Disclaimer of Warranty. Unless required by applicable law or 144 | agreed to in writing, Licensor provides the Work (and each 145 | Contributor provides its Contributions) on an "AS IS" BASIS, 146 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or 147 | implied, including, without limitation, any warranties or conditions 148 | of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A 149 | PARTICULAR PURPOSE. You are solely responsible for determining the 150 | appropriateness of using or redistributing the Work and assume any 151 | risks associated with Your exercise of permissions under this License. 152 | 153 | 8. Limitation of Liability. In no event and under no legal theory, 154 | whether in tort (including negligence), contract, or otherwise, 155 | unless required by applicable law (such as deliberate and grossly 156 | negligent acts) or agreed to in writing, shall any Contributor be 157 | liable to You for damages, including any direct, indirect, special, 158 | incidental, or consequential damages of any character arising as a 159 | result of this License or out of the use or inability to use the 160 | Work (including but not limited to damages for loss of goodwill, 161 | work stoppage, computer failure or malfunction, or any and all 162 | other commercial damages or losses), even if such Contributor 163 | has been advised of the possibility of such damages. 164 | 165 | 9. Accepting Warranty or Additional Liability. While redistributing 166 | the Work or Derivative Works thereof, You may choose to offer, 167 | and charge a fee for, acceptance of support, warranty, indemnity, 168 | or other liability obligations and/or rights consistent with this 169 | License. However, in accepting such obligations, You may act only 170 | on Your own behalf and on Your sole responsibility, not on behalf 171 | of any other Contributor, and only if You agree to indemnify, 172 | defend, and hold each Contributor harmless for any liability 173 | incurred by, or claims asserted against, such Contributor by reason 174 | of your accepting any such warranty or additional liability. 175 | 176 | END OF TERMS AND CONDITIONS 177 | 178 | APPENDIX: How to apply the Apache License to your work. 179 | 180 | To apply the Apache License to your work, attach the following 181 | boilerplate notice, with the fields enclosed by brackets "[]" 182 | replaced with your own identifying information. (Don't include 183 | the brackets!) The text should be enclosed in the appropriate 184 | comment syntax for the file format. We also recommend that a 185 | file or class name and description of purpose be included on the 186 | same "printed page" as the copyright notice for easier 187 | identification within third-party archives. 188 | 189 | Copyright 2021 aJIEw 190 | 191 | Licensed under the Apache License, Version 2.0 (the "License"); 192 | you may not use this file except in compliance with the License. 193 | You may obtain a copy of the License at 194 | 195 | http://www.apache.org/licenses/LICENSE-2.0 196 | 197 | Unless required by applicable law or agreed to in writing, software 198 | distributed under the License is distributed on an "AS IS" BASIS, 199 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 200 | See the License for the specific language governing permissions and 201 | limitations under the License. 202 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | ## Phone Call App 2 | 3 | This project shows you how to make your app as the default phone call app and manage phone calls (only for 6.0+), it also shows you how to listen phone call states. 4 | 5 | 本项目主要演示了如何将你的应用设置为默认电话应用并对电话接打进行管理,同时也演示了如何监听电话状态。 6 | 7 | ### Demo 8 | 9 | 主页面: 10 | 11 | ![Screenshot_375x667](media/Screenshot_375x667.png) 12 | 13 | 设置为默认电话应用(Android 6.0+): 14 | 15 | ![replace_default_phone_app](media/replace_default_phone_app.gif) 16 | 17 | 监听来电: 18 | 19 | ![listen_phone_call](media/listen_phone_call.gif) 20 | 21 | 原文链接:[安卓代替系统默认电话应用 (Android 6.0+) 与电话状态监听](https://ajiew.github.io/android-phone-call-app-and-listen-phone-calls/) 22 | -------------------------------------------------------------------------------- /app/.gitignore: -------------------------------------------------------------------------------- 1 | /build 2 | -------------------------------------------------------------------------------- /app/build.gradle: -------------------------------------------------------------------------------- 1 | plugins { 2 | id "com.android.application" 3 | } 4 | 5 | android { 6 | namespace 'com.ajiew.phonecallapp' 7 | compileSdk 35 8 | 9 | defaultConfig { 10 | applicationId "com.ajiew.phonecallapp" 11 | minSdk 21 12 | targetSdk 35 13 | versionCode 1 14 | versionName "1.0" 15 | testInstrumentationRunner 'androidx.test.runner.AndroidJUnitRunner' 16 | } 17 | 18 | buildTypes { 19 | release { 20 | minifyEnabled false 21 | proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro' 22 | } 23 | } 24 | 25 | compileOptions { 26 | sourceCompatibility JavaVersion.VERSION_1_8 27 | targetCompatibility JavaVersion.VERSION_1_8 28 | } 29 | } 30 | 31 | dependencies { 32 | implementation fileTree(include: ['*.jar'], dir: 'libs') 33 | implementation 'androidx.appcompat:appcompat:1.5.1' 34 | implementation 'androidx.constraintlayout:constraintlayout:2.1.4' 35 | implementation 'androidx.activity:activity:1.10.1' 36 | 37 | testImplementation 'junit:junit:4.13.2' 38 | androidTestImplementation 'androidx.test.ext:junit:1.1.5' 39 | androidTestImplementation 'androidx.test.espresso:espresso-core:3.5.1' 40 | } 41 | -------------------------------------------------------------------------------- /app/proguard-rules.pro: -------------------------------------------------------------------------------- 1 | # Add project specific ProGuard rules here. 2 | # You can control the set of applied configuration files using the 3 | # proguardFiles setting in build.gradle. 4 | # 5 | # For more details, see 6 | # http://developer.android.com/guide/developing/tools/proguard.html 7 | 8 | # If your project uses WebView with JS, uncomment the following 9 | # and specify the fully qualified class name to the JavaScript interface 10 | # class: 11 | #-keepclassmembers class fqcn.of.javascript.interface.for.webview { 12 | # public *; 13 | #} 14 | 15 | # Uncomment this to preserve the line number information for 16 | # debugging stack traces. 17 | #-keepattributes SourceFile,LineNumberTable 18 | 19 | # If you keep the line number information, uncomment this to 20 | # hide the original source file name. 21 | #-renamesourcefileattribute SourceFile 22 | -------------------------------------------------------------------------------- /app/src/androidTest/java/com/ajiew/phonecallapp/ExampleInstrumentedTest.java: -------------------------------------------------------------------------------- 1 | package com.ajiew.phonecallapp; 2 | 3 | import android.content.Context; 4 | import androidx.test.platform.app.InstrumentationRegistry; 5 | import androidx.test.ext.junit.runners.AndroidJUnit4; 6 | 7 | import org.junit.Test; 8 | import org.junit.runner.RunWith; 9 | 10 | import static org.junit.Assert.*; 11 | 12 | /** 13 | * Instrumented test, which will execute on an Android device. 14 | * 15 | * @see Testing documentation 16 | */ 17 | @RunWith(AndroidJUnit4.class) 18 | public class ExampleInstrumentedTest { 19 | @Test 20 | public void useAppContext() { 21 | // Context of the app under test. 22 | Context appContext = InstrumentationRegistry.getTargetContext(); 23 | 24 | assertEquals("com.ajiew.phonecallapp", appContext.getPackageName()); 25 | } 26 | } 27 | -------------------------------------------------------------------------------- /app/src/main/AndroidManifest.xml: -------------------------------------------------------------------------------- 1 | 2 | 4 | 5 | 8 | 9 | 10 | 11 | 12 | 13 | 14 | 15 | 16 | 17 | 18 | 19 | 26 | 29 | 30 | 31 | 32 | 33 | 34 | 35 | 36 | 41 | 42 | 43 | 44 | 45 | 46 | 47 | 48 | 49 | 50 | 51 | 52 | 53 | 54 | 55 | 56 | 57 | 58 | 59 | 60 | 61 | 66 | 69 | 70 | 71 | 72 | 73 | 77 | 78 | 79 | 80 | 81 | 82 | 83 | 84 | -------------------------------------------------------------------------------- /app/src/main/java/com/ajiew/phonecallapp/ActivityStack.java: -------------------------------------------------------------------------------- 1 | package com.ajiew.phonecallapp; 2 | 3 | import android.app.Activity; 4 | 5 | import java.util.ArrayList; 6 | import java.util.List; 7 | 8 | 9 | public class ActivityStack { 10 | 11 | private static final ActivityStack INSTANCE = new ActivityStack(); 12 | 13 | private List activities = new ArrayList<>(); 14 | 15 | public static ActivityStack getInstance() { 16 | return INSTANCE; 17 | } 18 | 19 | public void addActivity(Activity activity) { 20 | activities.add(activity); 21 | } 22 | 23 | public Activity getTopActivity() { 24 | if (activities.isEmpty()) { 25 | return null; 26 | } 27 | return activities.get(activities.size() - 1); 28 | } 29 | 30 | public void finishTopActivity() { 31 | if (!activities.isEmpty()) { 32 | activities.remove(activities.size() - 1).finish(); 33 | } 34 | } 35 | 36 | public void finishActivity(Activity activity) { 37 | if (activity != null) { 38 | activities.remove(activity); 39 | activity.finish(); 40 | } 41 | } 42 | 43 | public void finishActivity(Class activityClass) { 44 | for (Activity activity : activities) { 45 | if (activity.getClass().equals(activityClass)) { 46 | finishActivity(activity); 47 | } 48 | } 49 | } 50 | 51 | public void finishAllActivity() { 52 | if (!activities.isEmpty()) { 53 | for (Activity activity : activities) { 54 | activity.finish(); 55 | activities.remove(activity); 56 | } 57 | } 58 | } 59 | } 60 | -------------------------------------------------------------------------------- /app/src/main/java/com/ajiew/phonecallapp/MainActivity.java: -------------------------------------------------------------------------------- 1 | package com.ajiew.phonecallapp; 2 | 3 | import android.Manifest; 4 | import android.annotation.SuppressLint; 5 | import android.app.Activity; 6 | import android.app.ActivityManager; 7 | import android.app.role.RoleManager; 8 | import android.content.Context; 9 | import android.content.Intent; 10 | import android.content.pm.PackageManager; 11 | import android.net.Uri; 12 | import android.os.Build; 13 | import android.os.Bundle; 14 | import android.provider.Settings; 15 | import android.telecom.TelecomManager; 16 | import android.view.WindowManager; 17 | import android.widget.CompoundButton; 18 | import android.widget.Switch; 19 | import android.widget.Toast; 20 | 21 | import androidx.activity.EdgeToEdge; 22 | import androidx.activity.result.ActivityResultLauncher; 23 | import androidx.activity.result.contract.ActivityResultContracts; 24 | import androidx.annotation.Nullable; 25 | import androidx.appcompat.app.AlertDialog; 26 | import androidx.appcompat.app.AppCompatActivity; 27 | import androidx.core.content.ContextCompat; 28 | 29 | import com.ajiew.phonecallapp.listenphonecall.CallListenerService; 30 | 31 | import java.lang.reflect.Field; 32 | 33 | 34 | public class MainActivity extends AppCompatActivity { 35 | 36 | @SuppressLint("UseSwitchCompatOrMaterialCode") 37 | private Switch switchPhoneCall; 38 | 39 | @SuppressLint("UseSwitchCompatOrMaterialCode") 40 | private Switch switchListenCall; 41 | 42 | private CompoundButton.OnCheckedChangeListener switchCallCheckChangeListener; 43 | 44 | private final ActivityResultLauncher dialerRequestLauncher = registerForActivityResult( 45 | new ActivityResultContracts.StartActivityForResult(), result -> { 46 | if (result.getResultCode() == Activity.RESULT_OK) { 47 | Toast.makeText(MainActivity.this, getString(R.string.app_name) + " 已成为默认电话应用", 48 | Toast.LENGTH_SHORT).show(); 49 | } 50 | }); 51 | 52 | @Override 53 | protected void onCreate(@Nullable Bundle savedInstanceState) { 54 | EdgeToEdge.enable(this); 55 | super.onCreate(savedInstanceState); 56 | setContentView(R.layout.activity_main); 57 | 58 | initView(); 59 | } 60 | 61 | private void initView() { 62 | switchPhoneCall = findViewById(R.id.switch_default_phone_call); 63 | switchListenCall = findViewById(R.id.switch_call_listenr); 64 | 65 | switchPhoneCall.setOnClickListener(v -> { 66 | // 发起将本应用设为默认电话应用的请求,仅支持 Android M 及以上 67 | if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) { 68 | if (switchPhoneCall.isChecked()) { 69 | // Android 10 之后需要通过 RoleManager 修改默认电话应用 70 | if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.Q) { 71 | RoleManager roleManager = (RoleManager) getSystemService(Context.ROLE_SERVICE); 72 | Intent intent = roleManager.createRequestRoleIntent(RoleManager.ROLE_DIALER); 73 | dialerRequestLauncher.launch(intent); 74 | } else { 75 | Intent intent = new Intent(TelecomManager.ACTION_CHANGE_DEFAULT_DIALER); 76 | intent.putExtra(TelecomManager.EXTRA_CHANGE_DEFAULT_DIALER_PACKAGE_NAME, getPackageName()); 77 | startActivity(intent); 78 | } 79 | } else { 80 | // 取消时跳转到默认设置页面 81 | startActivity(new Intent("android.settings.MANAGE_DEFAULT_APPS_SETTINGS")); 82 | } 83 | } else { 84 | Toast.makeText(MainActivity.this, "Android 6.0 以上才支持修改默认电话应用!", Toast.LENGTH_LONG) 85 | .show(); 86 | switchPhoneCall.setChecked(false); 87 | } 88 | 89 | }); 90 | 91 | // 检查是否开启了权限 92 | switchCallCheckChangeListener = (buttonView, isChecked) -> { 93 | if (isChecked && Build.VERSION.SDK_INT >= Build.VERSION_CODES.M 94 | && !Settings.canDrawOverlays(MainActivity.this)) { 95 | // 请求 悬浮框 权限 96 | askForDrawOverlay(); 97 | 98 | // 未开启时清除选中状态,同时避免回调 99 | switchListenCall.setOnCheckedChangeListener(null); 100 | switchListenCall.setChecked(false); 101 | switchListenCall.setOnCheckedChangeListener(switchCallCheckChangeListener); 102 | return; 103 | } 104 | 105 | boolean granted = ContextCompat.checkSelfPermission(this, 106 | Manifest.permission.READ_PHONE_STATE) == PackageManager.PERMISSION_GRANTED; 107 | if (isChecked && Build.VERSION.SDK_INT >= Build.VERSION_CODES.S && !granted) { 108 | Toast.makeText(this, "缺少获取电话状态权限", Toast.LENGTH_SHORT).show(); 109 | return; 110 | } 111 | 112 | Intent callListener = new Intent(MainActivity.this, CallListenerService.class); 113 | if (isChecked) { 114 | startService(callListener); 115 | Toast.makeText(this, "电话监听服务已开启", Toast.LENGTH_SHORT).show(); 116 | } else { 117 | stopService(callListener); 118 | Toast.makeText(this, "电话监听服务已关闭", Toast.LENGTH_SHORT).show(); 119 | } 120 | }; 121 | switchListenCall.setOnCheckedChangeListener(switchCallCheckChangeListener); 122 | } 123 | 124 | private void askForDrawOverlay() { 125 | AlertDialog alertDialog = new AlertDialog.Builder(this) 126 | .setTitle("允许显示悬浮框") 127 | .setMessage("为了使电话监听服务正常工作,请允许这项权限") 128 | .setPositiveButton("去设置", (dialog, which) -> { 129 | openDrawOverlaySettings(); 130 | dialog.dismiss(); 131 | }) 132 | .setNegativeButton("稍后再说", (dialog, which) -> dialog.dismiss()) 133 | .create(); 134 | 135 | //noinspection ConstantConditions 136 | alertDialog.getWindow().setFlags( 137 | WindowManager.LayoutParams.FLAG_NOT_FOCUSABLE, 138 | WindowManager.LayoutParams.FLAG_NOT_FOCUSABLE); 139 | alertDialog.show(); 140 | } 141 | 142 | /** 143 | * 跳转悬浮窗管理设置界面 144 | */ 145 | private void openDrawOverlaySettings() { 146 | if (android.os.Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) { 147 | // Android M 以上引导用户去系统设置中打开允许悬浮窗 148 | // 使用反射是为了用尽可能少的代码保证在大部分机型上都可用 149 | try { 150 | Context context = this; 151 | Class clazz = Settings.class; 152 | Field field = clazz.getDeclaredField("ACTION_MANAGE_OVERLAY_PERMISSION"); 153 | Intent intent = new Intent(field.get(null).toString()); 154 | intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK); 155 | intent.setData(Uri.parse("package:" + context.getPackageName())); 156 | context.startActivity(intent); 157 | } catch (Exception e) { 158 | Toast.makeText(this, "请在悬浮窗管理中打开权限", Toast.LENGTH_LONG).show(); 159 | } 160 | } 161 | } 162 | 163 | @Override 164 | protected void onResume() { 165 | super.onResume(); 166 | 167 | switchPhoneCall.setChecked(isDefaultPhoneCallApp()); 168 | switchListenCall.setChecked(isServiceRunning(CallListenerService.class)); 169 | } 170 | 171 | /** 172 | * Android M 及以上检查是否是系统默认电话应用 173 | */ 174 | public boolean isDefaultPhoneCallApp() { 175 | if (android.os.Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) { 176 | TelecomManager manger = (TelecomManager) getSystemService(TELECOM_SERVICE); 177 | if (manger != null && manger.getDefaultDialerPackage() != null) { 178 | return manger.getDefaultDialerPackage().equals(getPackageName()); 179 | } 180 | } 181 | return false; 182 | } 183 | 184 | public boolean isServiceRunning(Class serviceClass) { 185 | ActivityManager manager = (ActivityManager) getSystemService(Context.ACTIVITY_SERVICE); 186 | if (manager == null) return false; 187 | 188 | for (ActivityManager.RunningServiceInfo service : manager.getRunningServices( 189 | Integer.MAX_VALUE)) { 190 | if (serviceClass.getName().equals(service.service.getClassName())) { 191 | return true; 192 | } 193 | } 194 | 195 | return false; 196 | } 197 | } 198 | -------------------------------------------------------------------------------- /app/src/main/java/com/ajiew/phonecallapp/listenphonecall/CallListenerService.java: -------------------------------------------------------------------------------- 1 | package com.ajiew.phonecallapp.listenphonecall; 2 | 3 | import android.app.Service; 4 | import android.content.Context; 5 | import android.content.Intent; 6 | import android.content.pm.ActivityInfo; 7 | import android.graphics.PixelFormat; 8 | import android.os.Build; 9 | import android.os.IBinder; 10 | import android.telephony.PhoneStateListener; 11 | import android.telephony.TelephonyCallback; 12 | import android.telephony.TelephonyManager; 13 | import android.text.TextUtils; 14 | import android.view.Gravity; 15 | import android.view.KeyEvent; 16 | import android.view.LayoutInflater; 17 | import android.view.View; 18 | import android.view.WindowManager; 19 | import android.widget.Button; 20 | import android.widget.FrameLayout; 21 | import android.widget.TextView; 22 | 23 | import androidx.annotation.Nullable; 24 | 25 | import com.ajiew.phonecallapp.MainActivity; 26 | import com.ajiew.phonecallapp.R; 27 | 28 | 29 | public class CallListenerService extends Service { 30 | 31 | private View phoneCallView; 32 | private TextView tvCallNumber; 33 | private Button btnOpenApp; 34 | 35 | private WindowManager windowManager; 36 | private WindowManager.LayoutParams params; 37 | 38 | private PhoneStateListenerCompat phoneStateListenerCompat; 39 | 40 | private String callNumber; 41 | private boolean hasShown; 42 | private boolean isCallingIn; 43 | 44 | @Override 45 | public void onCreate() { 46 | super.onCreate(); 47 | 48 | initPhoneStateListener(); 49 | 50 | initPhoneCallView(); 51 | } 52 | 53 | @Nullable 54 | @Override 55 | public IBinder onBind(Intent intent) { 56 | return null; 57 | } 58 | 59 | /** 60 | * 初始化来电状态监听器 61 | */ 62 | private void initPhoneStateListener() { 63 | phoneStateListenerCompat = new PhoneStateListenerCompat() { 64 | @Override 65 | public void onCallStateChanged(int state) { 66 | switch (state) { 67 | case TelephonyManager.CALL_STATE_IDLE: // 待机,即无电话时,挂断时触发 68 | dismiss(); 69 | break; 70 | 71 | case TelephonyManager.CALL_STATE_RINGING: // 响铃,来电时触发 72 | isCallingIn = true; 73 | updateUI(); 74 | show(); 75 | break; 76 | 77 | case TelephonyManager.CALL_STATE_OFFHOOK: // 摘机,接听或拨出电话时触发 78 | updateUI(); 79 | show(); 80 | break; 81 | 82 | default: 83 | break; 84 | 85 | } 86 | } 87 | }; 88 | phoneStateListenerCompat.startListening(this); 89 | } 90 | 91 | private void initPhoneCallView() { 92 | windowManager = (WindowManager) getApplicationContext() 93 | .getSystemService(Context.WINDOW_SERVICE); 94 | int width = windowManager.getDefaultDisplay().getWidth(); 95 | int height = windowManager.getDefaultDisplay().getHeight(); 96 | 97 | params = new WindowManager.LayoutParams(); 98 | params.gravity = Gravity.CENTER_HORIZONTAL | Gravity.TOP; 99 | params.width = width; 100 | params.height = WindowManager.LayoutParams.WRAP_CONTENT; 101 | params.screenOrientation = ActivityInfo.SCREEN_ORIENTATION_PORTRAIT; 102 | 103 | // 设置图片格式,效果为背景透明 104 | params.format = PixelFormat.TRANSLUCENT; 105 | // 设置 Window flag 为系统级弹框 | 覆盖表层 106 | params.type = Build.VERSION.SDK_INT >= Build.VERSION_CODES.O ? 107 | WindowManager.LayoutParams.TYPE_APPLICATION_OVERLAY : 108 | WindowManager.LayoutParams.TYPE_PHONE; 109 | 110 | // 不可聚集(不响应返回键)| 全屏 111 | params.flags = WindowManager.LayoutParams.FLAG_NOT_FOCUSABLE 112 | | WindowManager.LayoutParams.FLAG_FULLSCREEN 113 | | WindowManager.LayoutParams.FLAG_LAYOUT_IN_SCREEN; 114 | // API 19 以上则还可以开启透明状态栏与导航栏 115 | if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) { 116 | params.flags = WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS 117 | | WindowManager.LayoutParams.FLAG_TRANSLUCENT_NAVIGATION 118 | | WindowManager.LayoutParams.FLAG_NOT_FOCUSABLE 119 | | WindowManager.LayoutParams.FLAG_FULLSCREEN 120 | | WindowManager.LayoutParams.FLAG_LAYOUT_IN_SCREEN; 121 | } 122 | 123 | FrameLayout interceptorLayout = new FrameLayout(this) { 124 | 125 | @Override 126 | public boolean dispatchKeyEvent(KeyEvent event) { 127 | 128 | if (event.getAction() == KeyEvent.ACTION_DOWN) { 129 | if (event.getKeyCode() == KeyEvent.KEYCODE_BACK) { 130 | 131 | return true; 132 | } 133 | } 134 | 135 | return super.dispatchKeyEvent(event); 136 | } 137 | }; 138 | 139 | phoneCallView = ((LayoutInflater) getSystemService(Context.LAYOUT_INFLATER_SERVICE)) 140 | .inflate(R.layout.view_phone_call, interceptorLayout); 141 | tvCallNumber = phoneCallView.findViewById(R.id.tv_call_number); 142 | btnOpenApp = phoneCallView.findViewById(R.id.btn_open_app); 143 | btnOpenApp.setOnClickListener(v -> { 144 | Intent intent = new Intent(getApplicationContext(), MainActivity.class); 145 | intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK); 146 | CallListenerService.this.startActivity(intent); 147 | }); 148 | } 149 | 150 | /** 151 | * 显示顶级弹框展示通话信息 152 | */ 153 | private void show() { 154 | if (!hasShown) { 155 | windowManager.addView(phoneCallView, params); 156 | hasShown = true; 157 | } 158 | } 159 | 160 | /** 161 | * 取消显示 162 | */ 163 | private void dismiss() { 164 | if (hasShown) { 165 | windowManager.removeView(phoneCallView); 166 | isCallingIn = false; 167 | hasShown = false; 168 | } 169 | } 170 | 171 | private void updateUI() { 172 | tvCallNumber.setText(formatPhoneNumber(callNumber)); 173 | 174 | int callTypeDrawable = isCallingIn ? R.drawable.ic_phone_call_in : R.drawable.ic_phone_call_out; 175 | tvCallNumber.setCompoundDrawablesWithIntrinsicBounds(null, null, 176 | getResources().getDrawable(callTypeDrawable), null); 177 | } 178 | 179 | public static String formatPhoneNumber(String phoneNum) { 180 | if (!TextUtils.isEmpty(phoneNum) && phoneNum.length() == 11) { 181 | return phoneNum.substring(0, 3) + "-" 182 | + phoneNum.substring(3, 7) + "-" 183 | + phoneNum.substring(7); 184 | } 185 | return phoneNum; 186 | } 187 | 188 | @Override 189 | public void onDestroy() { 190 | super.onDestroy(); 191 | 192 | phoneStateListenerCompat.stopListening(this); 193 | } 194 | } 195 | -------------------------------------------------------------------------------- /app/src/main/java/com/ajiew/phonecallapp/listenphonecall/PhoneStateListenerCompat.java: -------------------------------------------------------------------------------- 1 | package com.ajiew.phonecallapp.listenphonecall; 2 | 3 | import android.content.Context; 4 | import android.os.Build; 5 | import android.telephony.PhoneStateListener; 6 | import android.telephony.TelephonyManager; 7 | import android.util.Log; 8 | 9 | import androidx.annotation.RequiresApi; 10 | 11 | /** 12 | * 新的电话状态监听器,适配 {@link android.telephony.TelephonyCallback} 以及老版本的 {@link PhoneStateListener} 13 | * 14 | * @author aJIEw 15 | * Created on: 2025/5/6 16:45 16 | */ 17 | public abstract class PhoneStateListenerCompat { 18 | private PhoneStateListener phoneStateListener; 19 | private TelephonyCallback telephonyCallback; 20 | 21 | public void startListening(Context context) { 22 | TelephonyManager tm = (TelephonyManager) context.getSystemService( 23 | Context.TELEPHONY_SERVICE); 24 | 25 | if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.S) { 26 | telephonyCallback = new TelephonyCallback() { 27 | @Override 28 | public void onCallStateChanged(int state) { 29 | Log.d(PhoneStateListenerCompat.class.getSimpleName(), "onCallStateChanged: "); 30 | PhoneStateListenerCompat.this.onCallStateChanged(state); 31 | } 32 | }; 33 | tm.registerTelephonyCallback(context.getMainExecutor(), telephonyCallback); 34 | } else { 35 | phoneStateListener = new PhoneStateListener() { 36 | @Override 37 | public void onCallStateChanged(int state, String phoneNumber) { 38 | PhoneStateListenerCompat.this.onCallStateChanged(state); 39 | } 40 | }; 41 | tm.listen(phoneStateListener, PhoneStateListener.LISTEN_CALL_STATE); 42 | } 43 | } 44 | 45 | public void stopListening(Context context) { 46 | TelephonyManager tm = (TelephonyManager) context.getSystemService( 47 | Context.TELEPHONY_SERVICE); 48 | 49 | if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.S) { 50 | if (telephonyCallback != null) { 51 | tm.unregisterTelephonyCallback(telephonyCallback); 52 | } 53 | } else { 54 | if (phoneStateListener != null) { 55 | tm.listen(phoneStateListener, PhoneStateListener.LISTEN_NONE); 56 | } 57 | } 58 | } 59 | 60 | public abstract void onCallStateChanged(int state); 61 | } 62 | 63 | @RequiresApi(api = Build.VERSION_CODES.S) 64 | class TelephonyCallback extends android.telephony.TelephonyCallback 65 | implements android.telephony.TelephonyCallback.CallStateListener { 66 | 67 | @Override 68 | public void onCallStateChanged(int state) { 69 | switch (state) { 70 | case TelephonyManager.CALL_STATE_IDLE: 71 | // 空闲状态 72 | break; 73 | case TelephonyManager.CALL_STATE_RINGING: 74 | // 来电响铃 75 | break; 76 | case TelephonyManager.CALL_STATE_OFFHOOK: 77 | // 通话中 78 | break; 79 | } 80 | } 81 | } 82 | -------------------------------------------------------------------------------- /app/src/main/java/com/ajiew/phonecallapp/phonecallui/PhoneCallActivity.java: -------------------------------------------------------------------------------- 1 | package com.ajiew.phonecallapp.phonecallui; 2 | 3 | import static com.ajiew.phonecallapp.listenphonecall.CallListenerService.formatPhoneNumber; 4 | 5 | import android.annotation.SuppressLint; 6 | import android.content.Context; 7 | import android.content.Intent; 8 | import android.os.Build; 9 | import android.os.Bundle; 10 | import android.view.View; 11 | import android.view.WindowManager; 12 | import android.widget.TextView; 13 | 14 | import androidx.activity.EdgeToEdge; 15 | import androidx.annotation.RequiresApi; 16 | import androidx.appcompat.app.AppCompatActivity; 17 | 18 | import com.ajiew.phonecallapp.ActivityStack; 19 | import com.ajiew.phonecallapp.R; 20 | 21 | import java.util.Timer; 22 | import java.util.TimerTask; 23 | 24 | 25 | /** 26 | * 提供接打电话的界面,仅支持 Android M (6.0, API 23) 及以上的系统 27 | * 28 | * @author aJIEw 29 | */ 30 | @RequiresApi(api = Build.VERSION_CODES.M) 31 | public class PhoneCallActivity extends AppCompatActivity implements View.OnClickListener { 32 | 33 | private TextView tvCallNumberLabel; 34 | private TextView tvCallNumber; 35 | private TextView tvPickUp; 36 | private TextView tvCallingTime; 37 | private TextView tvHangUp; 38 | 39 | private PhoneCallManager phoneCallManager; 40 | private PhoneCallService.CallType callType; 41 | private String phoneNumber; 42 | 43 | private Timer onGoingCallTimer; 44 | private int callingTime; 45 | 46 | public static void actionStart(Context context, String phoneNumber, 47 | PhoneCallService.CallType callType) { 48 | Intent intent = new Intent(context, PhoneCallActivity.class); 49 | intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK); 50 | intent.putExtra(Intent.EXTRA_MIME_TYPES, callType); 51 | intent.putExtra(Intent.EXTRA_PHONE_NUMBER, phoneNumber); 52 | context.startActivity(intent); 53 | } 54 | 55 | @Override 56 | protected void onCreate(Bundle savedInstanceState) { 57 | EdgeToEdge.enable(this); 58 | super.onCreate(savedInstanceState); 59 | setContentView(R.layout.activity_phone_call); 60 | 61 | ActivityStack.getInstance().addActivity(this); 62 | 63 | initData(); 64 | 65 | initView(); 66 | } 67 | 68 | private void initData() { 69 | phoneCallManager = new PhoneCallManager(this); 70 | onGoingCallTimer = new Timer(); 71 | if (getIntent() != null) { 72 | phoneNumber = getIntent().getStringExtra(Intent.EXTRA_PHONE_NUMBER); 73 | callType = (PhoneCallService.CallType) getIntent().getSerializableExtra(Intent.EXTRA_MIME_TYPES); 74 | } 75 | } 76 | 77 | private void initView() { 78 | int uiOptions = View.SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION 79 | | View.SYSTEM_UI_FLAG_HIDE_NAVIGATION //hide navigationBar 80 | | View.SYSTEM_UI_FLAG_IMMERSIVE_STICKY 81 | | View.SYSTEM_UI_FLAG_LAYOUT_STABLE; 82 | getWindow().getDecorView().setSystemUiVisibility(uiOptions); 83 | getWindow().addFlags(WindowManager.LayoutParams.FLAG_TURN_SCREEN_ON); 84 | 85 | tvCallNumberLabel = findViewById(R.id.tv_call_number_label); 86 | tvCallNumber = findViewById(R.id.tv_call_number); 87 | tvPickUp = findViewById(R.id.tv_phone_pick_up); 88 | tvCallingTime = findViewById(R.id.tv_phone_calling_time); 89 | tvHangUp = findViewById(R.id.tv_phone_hang_up); 90 | 91 | tvCallNumber.setText(formatPhoneNumber(phoneNumber)); 92 | tvPickUp.setOnClickListener(this); 93 | tvHangUp.setOnClickListener(this); 94 | 95 | // 打进的电话 96 | if (callType == PhoneCallService.CallType.CALL_IN) { 97 | tvCallNumberLabel.setText("来电号码"); 98 | tvPickUp.setVisibility(View.VISIBLE); 99 | } 100 | // 打出的电话 101 | else if (callType == PhoneCallService.CallType.CALL_OUT) { 102 | tvCallNumberLabel.setText("呼叫号码"); 103 | tvPickUp.setVisibility(View.GONE); 104 | phoneCallManager.openSpeaker(); 105 | } 106 | 107 | showOnLockScreen(); 108 | } 109 | 110 | public void showOnLockScreen() { 111 | this.getWindow().setFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON | 112 | WindowManager.LayoutParams.FLAG_FULLSCREEN | 113 | WindowManager.LayoutParams.FLAG_SHOW_WHEN_LOCKED | 114 | WindowManager.LayoutParams.FLAG_TURN_SCREEN_ON, 115 | WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON | 116 | WindowManager.LayoutParams.FLAG_FULLSCREEN | 117 | WindowManager.LayoutParams.FLAG_SHOW_WHEN_LOCKED | 118 | WindowManager.LayoutParams.FLAG_TURN_SCREEN_ON); 119 | } 120 | 121 | @Override 122 | public void onClick(View v) { 123 | if (v.getId() == R.id.tv_phone_pick_up) { 124 | phoneCallManager.answer(); 125 | tvPickUp.setVisibility(View.GONE); 126 | tvCallingTime.setVisibility(View.VISIBLE); 127 | onGoingCallTimer.schedule(new TimerTask() { 128 | @Override 129 | public void run() { 130 | runOnUiThread(new Runnable() { 131 | @SuppressLint("SetTextI18n") 132 | @Override 133 | public void run() { 134 | callingTime++; 135 | tvCallingTime.setText("通话中:" + getCallingTime()); 136 | } 137 | }); 138 | } 139 | }, 0, 1000); 140 | } else if (v.getId() == R.id.tv_phone_hang_up) { 141 | phoneCallManager.disconnect(); 142 | stopTimer(); 143 | } 144 | } 145 | 146 | private String getCallingTime() { 147 | int minute = callingTime / 60; 148 | int second = callingTime % 60; 149 | return (minute < 10 ? "0" + minute : minute) + 150 | ":" + 151 | (second < 10 ? "0" + second : second); 152 | } 153 | 154 | private void stopTimer() { 155 | if (onGoingCallTimer != null) { 156 | onGoingCallTimer.cancel(); 157 | } 158 | 159 | callingTime = 0; 160 | } 161 | 162 | @Override 163 | protected void onDestroy() { 164 | super.onDestroy(); 165 | 166 | phoneCallManager.destroy(); 167 | } 168 | } 169 | -------------------------------------------------------------------------------- /app/src/main/java/com/ajiew/phonecallapp/phonecallui/PhoneCallManager.java: -------------------------------------------------------------------------------- 1 | package com.ajiew.phonecallapp.phonecallui; 2 | 3 | import android.content.Context; 4 | import android.media.AudioManager; 5 | import android.os.Build; 6 | import android.telecom.Call; 7 | import android.telecom.VideoProfile; 8 | 9 | import androidx.annotation.RequiresApi; 10 | 11 | 12 | @RequiresApi(api = Build.VERSION_CODES.M) 13 | public class PhoneCallManager { 14 | 15 | public static Call call; 16 | 17 | private Context context; 18 | private AudioManager audioManager; 19 | 20 | public PhoneCallManager(Context context) { 21 | this.context = context; 22 | 23 | audioManager = (AudioManager) context.getSystemService(Context.AUDIO_SERVICE); 24 | } 25 | 26 | /** 27 | * 接听电话 28 | */ 29 | public void answer() { 30 | if (call != null) { 31 | call.answer(VideoProfile.STATE_AUDIO_ONLY); 32 | openSpeaker(); 33 | } 34 | } 35 | 36 | /** 37 | * 断开电话,包括来电时的拒接以及接听后的挂断 38 | */ 39 | public void disconnect() { 40 | if (call != null) { 41 | call.disconnect(); 42 | } 43 | } 44 | 45 | /** 46 | * 打开免提 47 | */ 48 | public void openSpeaker() { 49 | if (audioManager != null) { 50 | audioManager.setMode(AudioManager.MODE_IN_CALL); 51 | audioManager.setSpeakerphoneOn(true); 52 | } 53 | } 54 | 55 | /** 56 | * 销毁资源 57 | */ 58 | public void destroy() { 59 | call = null; 60 | context = null; 61 | audioManager = null; 62 | } 63 | } 64 | -------------------------------------------------------------------------------- /app/src/main/java/com/ajiew/phonecallapp/phonecallui/PhoneCallService.java: -------------------------------------------------------------------------------- 1 | package com.ajiew.phonecallapp.phonecallui; 2 | 3 | import android.os.Build; 4 | import android.telecom.Call; 5 | import android.telecom.InCallService; 6 | 7 | import androidx.annotation.RequiresApi; 8 | 9 | import com.ajiew.phonecallapp.ActivityStack; 10 | 11 | 12 | /** 13 | * 监听电话通信状态的服务,实现该类的同时必须提供电话管理的 UI 14 | * 15 | * @author aJIEw 16 | * @see PhoneCallActivity 17 | * @see android.telecom.InCallService 18 | */ 19 | @RequiresApi(api = Build.VERSION_CODES.M) 20 | public class PhoneCallService extends InCallService { 21 | 22 | private final Call.Callback callback = new Call.Callback() { 23 | @Override 24 | public void onStateChanged(Call call, int state) { 25 | super.onStateChanged(call, state); 26 | 27 | switch (state) { 28 | case Call.STATE_ACTIVE: { 29 | 30 | break; 31 | } 32 | 33 | case Call.STATE_DISCONNECTED: { 34 | ActivityStack.getInstance().finishActivity(PhoneCallActivity.class); 35 | break; 36 | } 37 | 38 | } 39 | } 40 | }; 41 | 42 | @Override 43 | public void onCallAdded(Call call) { 44 | super.onCallAdded(call); 45 | 46 | call.registerCallback(callback); 47 | PhoneCallManager.call = call; 48 | 49 | CallType callType = null; 50 | 51 | if (call.getState() == Call.STATE_RINGING) { 52 | callType = CallType.CALL_IN; 53 | } else if (call.getState() == Call.STATE_CONNECTING) { 54 | callType = CallType.CALL_OUT; 55 | } 56 | 57 | if (callType != null) { 58 | Call.Details details = call.getDetails(); 59 | String phoneNumber = details.getHandle().getSchemeSpecificPart(); 60 | PhoneCallActivity.actionStart(this, phoneNumber, callType); 61 | } 62 | } 63 | 64 | @Override 65 | public void onCallRemoved(Call call) { 66 | super.onCallRemoved(call); 67 | 68 | call.unregisterCallback(callback); 69 | PhoneCallManager.call = null; 70 | } 71 | 72 | public enum CallType { 73 | CALL_IN, 74 | CALL_OUT, 75 | } 76 | } 77 | -------------------------------------------------------------------------------- /app/src/main/res/drawable/ic_phone_call_in.xml: -------------------------------------------------------------------------------- 1 | 6 | 9 | 10 | -------------------------------------------------------------------------------- /app/src/main/res/drawable/ic_phone_call_out.xml: -------------------------------------------------------------------------------- 1 | 6 | 9 | 10 | -------------------------------------------------------------------------------- /app/src/main/res/drawable/ic_phone_hang_up.xml: -------------------------------------------------------------------------------- 1 | 6 | 9 | 10 | -------------------------------------------------------------------------------- /app/src/main/res/drawable/ic_phone_pick_up.xml: -------------------------------------------------------------------------------- 1 | 6 | 9 | 12 | 15 | 18 | 21 | 24 | 27 | 30 | 31 | -------------------------------------------------------------------------------- /app/src/main/res/layout/activity_main.xml: -------------------------------------------------------------------------------- 1 | 2 | 5 | 6 | 14 | 15 | 22 | 23 | 31 | 32 | 41 | -------------------------------------------------------------------------------- /app/src/main/res/layout/activity_phone_call.xml: -------------------------------------------------------------------------------- 1 | 2 | 9 | 10 | 15 | 16 | 26 | 27 | 28 | 39 | 40 | 41 | 42 | 46 | 47 | 58 | 59 | 63 | 64 | 76 | 77 | 92 | 93 | 94 | 95 | -------------------------------------------------------------------------------- /app/src/main/res/layout/view_phone_call.xml: -------------------------------------------------------------------------------- 1 | 2 | 8 | 9 | 20 | 21 |