
在android应用中实现即使应用完全关闭也能检测到来电的功能,核心在于利用android的前台服务(foreground service)机制。前台服务通过在通知栏显示一个持续通知,告知用户应用正在后台运行,从而获得系统更高的优先级,有效避免被系统杀死。结合开机广播接收器,可以确保服务在设备启动后自动运行,实现类似truecaller的持久化来电监听。
随着Android系统版本的演进,为了优化电池续航和系统性能,对后台任务的执行施加了越来越严格的限制。传统的后台服务(Background Service)在应用被关闭后很容易被系统杀死。对于需要持续运行,且用户感知到的任务(如音乐播放、导航、来电检测等),Android提供了“前台服务”(Foreground Service)机制。
前台服务与普通服务的最大区别在于它会向用户显示一个持续的通知。这个通知告诉用户应用正在后台执行某项任务,因此系统会给予前台服务更高的优先级,使其更不容易被杀死,从而保证任务的持续性。对于像来电检测这样需要在应用完全关闭后依然能工作的场景,前台服务是实现此功能的关键。
要实现来电检测的前台服务,我们需要一个服务类来监听电话状态,并在应用启动时或开机时启动这个服务。
在 AndroidManifest.xml 文件中声明必要的权限:
<uses-permission android:name="android.permission.READ_PHONE_STATE" />
<uses-permission android:name="android.permission.FOREGROUND_SERVICE" />
<uses-permission android:name="android.permission.RECEIVE_BOOT_COMPLETED" />
<uses-permission android:name="android.permission.POST_NOTIFICATIONS" /> <!-- For Android 13+ -->
<application
android:allowBackup="true"
android:icon="@mipmap/ic_launcher"
android:label="@string/app_name"
android:roundIcon="@mipmap/ic_launcher_round"
android:supportsRtl="true"
android:theme="@style/Theme.MyApp">
<!-- 声明你的服务 -->
<service
android:name=".CallDetectionService"
android:enabled="true"
android:exported="false"
android:foregroundServiceType="phoneCall" /> <!-- Android 10+ 需指定服务类型 -->
<!-- 声明你的广播接收器 -->
<receiver
android:name=".BootReceiver"
android:enabled="true"
android:exported="false">
<intent-filter>
<action android:name="android.intent.action.BOOT_COMPLETED" />
<category android:name="android.intent.category.DEFAULT" />
</intent-filter>
</receiver>
<!-- ... 其他组件 ... -->
</application>注意:
这个服务将负责监听电话状态并处理来电事件。
import android.app.Notification;
import android.app.NotificationChannel;
import android.app.NotificationManager;
import android.app.Service;
import android.content.Context;
import android.content.Intent;
import android.os.Build;
import android.os.IBinder;
import android.telephony.PhoneStateListener;
import android.telephony.TelephonyManager;
import android.util.Log;
import androidx.annotation.Nullable;
import androidx.core.app.NotificationCompat;
public class CallDetectionService extends Service {
private static final String TAG = "CallDetectionService";
public static final String CHANNEL_ID = "CallDetectionServiceChannel";
private TelephonyManager telephonyManager;
private PhoneStateListener phoneStateListener;
@Override
public void onCreate() {
super.onCreate();
Log.d(TAG, "Service onCreate");
// 创建通知渠道,Android 8.0 (API 26) 及以上版本需要
createNotificationChannel();
telephonyManager = (TelephonyManager) getSystemService(Context.TELEPHONY_SERVICE);
phoneStateListener = new PhoneStateListener() {
@Override
public void onCallStateChanged(int state, String phoneNumber) {
super.onCallStateChanged(state, phoneNumber);
switch (state) {
case TelephonyManager.CALL_STATE_RINGING:
Log.d(TAG, "Incoming call: " + phoneNumber);
// 在这里处理来电逻辑,例如显示自定义浮窗、播放提示音等
// 注意:在后台显示UI可能需要SYSTEM_ALERT_WINDOW权限
break;
case TelephonyManager.CALL_STATE_OFFHOOK:
Log.d(TAG, "Call answered or dialing: " + phoneNumber);
break;
case TelephonyManager.CALL_STATE_IDLE:
Log.d(TAG, "Call ended or idle.");
break;
}
}
};
// 注册电话状态监听器
if (telephonyManager != null) {
telephonyManager.listen(phoneStateListener, PhoneStateListener.LISTEN_CALL_STATE);
}
}
@Override
public int onStartCommand(Intent intent, int flags, int startId) {
Log.d(TAG, "Service onStartCommand");
// 构建前台服务通知
Notification notification = new NotificationCompat.Builder(this, CHANNEL_ID)
.setContentTitle("来电检测服务")
.setContentText("正在后台运行,检测来电...")
.setSmallIcon(R.drawable.ic_launcher_foreground) // 替换为你的应用图标
.setPriority(NotificationCompat.PRIORITY_LOW) // 设置较低优先级,减少干扰
.build();
// 启动前台服务
startForeground(1, notification); // 1 是通知的唯一ID
// 返回 START_STICKY 表示服务被系统杀死后会自动尝试重启
return START_STICKY;
}
@Override
public void onDestroy() {
super.onDestroy();
Log.d(TAG, "Service onDestroy");
// 解注册电话状态监听器,防止内存泄漏
if (telephonyManager != null && phoneStateListener != null) {
telephonyManager.listen(phoneStateListener, PhoneStateListener.LISTEN_NONE);
}
}
@Nullable
@Override
public IBinder onBind(Intent intent) {
// 本例中不使用绑定服务,所以返回null
return null;
}
// 为 Android 8.0 (API 26) 及以上版本创建通知渠道
private void createNotificationChannel() {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
NotificationChannel serviceChannel = new NotificationChannel(
CHANNEL_ID,
"来电检测服务通道",
NotificationManager.IMPORTANCE_DEFAULT // 可以根据需求设置重要性
);
NotificationManager manager = getSystemService(NotificationManager.class);
if (manager != null) {
manager.createNotificationChannel(serviceChannel);
}
}
}
}为了确保服务在设备重启后依然能工作,我们需要一个广播接收器来监听 ACTION_BOOT_COMPLETED 广播。
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.os.Build;
import android.util.Log;
public class BootReceiver extends BroadcastReceiver {
private static final String TAG = "BootReceiver";
@Override
public void onReceive(Context context, Intent intent) {
// 检查是否是开机完成广播
if (Intent.ACTION_BOOT_COMPLETED.equals(intent.getAction())) {
Log.d(TAG, "Boot completed, starting CallDetectionService.");
Intent serviceIntent = new Intent(context, CallDetectionService.class);
// 对于 Android 8.0 (API 26) 及以上版本,必须使用 startForegroundService() 启动前台服务
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
context.startForegroundService(serviceIntent);
} else {
context.startService(serviceIntent);
}
}
}
}你可以在应用的主 Activity 中,例如 onCreate 方法或用户点击某个按钮时,启动这个服务。
import android.content.Intent;
import android.content.pm.PackageManager;
import android.os.Build;
import android.os.Bundle;
import android.widget.Button;
import android.widget.Toast;
import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;
import androidx.core.app.ActivityCompat;
import androidx.core.content.ContextCompat;
import static android.Manifest.permission.READ_PHONE_STATE;
import static android.Manifest.permission.POST_NOTIFICATIONS; // For Android 13+
public class MainActivity extends AppCompatActivity {
private static final int PERMISSION_REQUEST_CODE = 1001;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Button startServiceButton = findViewById(R.id.startServiceButton);
startServiceButton.setOnClickListener(v -> requestPermissionsAndStartService());
}
private void requestPermissionsAndStartService() {
// 检查并请求运行时权限
if (ContextCompat.checkSelfPermission(this, READ_PHONE_STATE) != PackageManager.PERMISSION_GRANTED ||
(Build.VERSION.SDK_INT >= Build.VERSION_CODES.TIRAMISU &&
ContextCompat.checkSelfPermission(this, POST_NOTIFICATIONS) != PackageManager.PERMISSION_GRANTED)) {
String[] permissions;
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.TIRAMISU) {
permissions = new String[]{READ_PHONE_STATE, POST_NOTIFICATIONS};
} else {
permissions = new String[]{READ_PHONE_STATE};
}
ActivityCompat.requestPermissions(this, permissions, PERMISSION_REQUEST_CODE);
} else {
startCallDetectionService();
}
}
@Override
public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
super.onRequestPermissionsResult(requestCode, permissions, grantResults);
if (requestCode == PERMISSION_REQUEST_CODE) {
boolean allPermissionsGranted = true;
for (int result : grantResults) {
if (result != PackageManager.PERMISSION_GRANTED) {
allPermissionsGranted = false;
break;
}
}
if (allPermissionsGranted) {
startCallDetectionService();
} else {
Toast.makeText(this, "权限被拒绝,无法启动服务", Toast.LENGTH_SHORT).show();
}
}
}
private void startCallDetectionService() {
Intent serviceIntent = new Intent(this, CallDetectionService.class);
// 对于 Android 8.0 (API 26) 及以上版本,必须使用 startForegroundService() 启动前台服务
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
startForegroundService(serviceIntent);
} else {
startService(serviceIntent);
}
Toast.makeText(this, "来电检测服务已启动", Toast.LENGTH_SHORT).show();
}
}通过结合Android的前台服务(Foreground Service)和开机广播接收器(Boot Receiver),我们可以有效地实现在应用完全关闭后依然能够持久化检测到来电的功能。前台服务通过显示一个持续通知来提升其在系统中的优先级,
以上就是Android 应用后台来电检测:利用前台服务实现持久监听的详细内容,更多请关注php中文网其它相关文章!
每个人都需要一台速度更快、更稳定的 PC。随着时间的推移,垃圾文件、旧注册表数据和不必要的后台进程会占用资源并降低性能。幸运的是,许多工具可以让 Windows 保持平稳运行。
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号