安卓Oreo如何在服务中获取来电号码

3
我正在实现Android Oreo版本中获取来电号码的代码。为此,我在服务中使用了广播接收器。以下是我迄今为止完成的代码。
public class CallService extends Service {
private static final int ID_SERVICE = 101;
BroadcastReceiver brSms;

public class MyReceiver extends BroadcastReceiver {

    @Override
    public void onReceive(Context context, Intent intent) {
        TelephonyManager telephony = (TelephonyManager)context.getSystemService(Context.TELEPHONY_SERVICE);
        telephony.listen(new PhoneStateListener(){
            @Override
            public void onCallStateChanged(int state, String incomingNumber) {
                super.onCallStateChanged(state, incomingNumber);
                System.out.println("incomingNumber : "+incomingNumber);
                Toast.makeText(context,""+incomingNumber,Toast.LENGTH_LONG).show();
            }
        },PhoneStateListener.LISTEN_CALL_STATE);
    }
}


@Override
public int onStartCommand(Intent intent, int flags, int startId) {
    super.onStartCommand(intent, flags, startId);
    return START_STICKY;
}

@Nullable
@Override
public IBinder onBind(Intent intent) {
    return null;
}

@Override
public void onCreate() {
    super.onCreate();



    IntentFilter filter = new IntentFilter();
    filter.addAction("android.intent.action.PHONE_STATE");
    brSms = new MyReceiver();
    registerReceiver(brSms, filter);




    // Create the Foreground Service
    NotificationManager notificationManager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
    String channelId = Build.VERSION.SDK_INT >= Build.VERSION_CODES.O ? createNotificationChannel(notificationManager) : "";
    NotificationCompat.Builder notificationBuilder = new NotificationCompat.Builder(this, channelId);
    Notification notification = notificationBuilder.setOngoing(true)
            .setSmallIcon(R.mipmap.ic_launcher)
            .setPriority(PRIORITY_MIN)
            .setCategory(NotificationCompat.CATEGORY_SERVICE)
            .build();

    startForeground(ID_SERVICE, notification);
}

@RequiresApi(Build.VERSION_CODES.O)
private String createNotificationChannel(NotificationManager notificationManager){
    String channelId = "my_service_channelid";
    String channelName = "My Foreground Service";
    NotificationChannel channel = new NotificationChannel(channelId, channelName, NotificationManager.IMPORTANCE_HIGH);
    channel.setImportance(NotificationManager.IMPORTANCE_NONE);
    channel.setLockscreenVisibility(Notification.VISIBILITY_PRIVATE);
    notificationManager.createNotificationChannel(channel);
    return channelId;
}
@Override
public void onDestroy() {
    unregisterReceiver(brSms);

 }
}

代码无法运行。我尝试了堆栈溢出中提供的各种选项。我已经在我的清单文件中添加了前台服务的权限。即使应用程序关闭或被用户杀死,我如何获取来电号码?


你能否检查一下你在BroadcastReceiver中的代码是否在来电时被调用了?通常情况下,这并不需要一个Service。你是如何在AndroidManifest文件中注册你的BroadcastReceiver的? - BWappsAndmore
前台服务被调用,因为Android Oreo不允许广播接收器在应用程序被用户杀死后工作。此外,清单中的接收器声明会出现编译错误,因为它是在服务中创建的。 - swapnil gandhi
3个回答

2
请尝试一下是否能够运行。

BroadcastReceiver.java

public class MyReceiver extends BroadcastReceiver {

    @Override
    public void onReceive(Context context, Intent intent) {
        String state = intent.getStringExtra(TelephonyManager.EXTRA_STATE);
        if (state != null) {
           if (state == TelephonyManager.EXTRA_STATE_RINGING) {
              String incomingNumber = intent.getStringExtra(TelephonyManager.EXTRA_INCOMING_NUMBER);
              if (incomingNumber != null) {
               Log.d("incomingNumber", incomingNumber);
               // do what you want with the incomingNumber
              }
           }
        }
    }
}

AndroidManifest.xml

<receiver
    android:name=".MyReceiver"
    android:enabled="true"
    android:exported="true">
    <intent-filter>
         <action android:name="android.intent.action.PHONE_STATE" />
    </intent-filter>
         <intent-filter>
             <action android:name="android.intent.action.READ_CALL_LOG" />
         </intent-filter>
</receiver>

Android 33: 已弃用 // intent.getStringExtra(TelephonyManager.EXTRA_INCOMING_NUMBER) // 配套可穿戴设备的应用程序应改用InCallService API来检索通话的电话号码。 // 执行呼叫筛选的应用程序应改用CallScreeningService API。 - matheszabi

1

我不确定这里的根本原因,但是,实际上您并不需要PhoneStateListener来获取来电号码。虽然它应该返回号码,但在某些设备上,它会多次或始终返回空字符串。您可以从意图中获取号码:

if(intent.getExtras() != null){
    String number = 
    intent.getExtras().getString(TelephonyManager.EXTRA_INCOMING_NUMBER, "-1")
}
if(!number.equals(-1) || !number.equals("")){
    //Toast it or do stuff here
}

这个意图可能没有数字或为空字符串,因此在执行任何操作之前,请检查它们。最终将传递带有传入数字的意图。您应该忽略其他意图。这相当依赖于设备。例如,在某些设备上,总是有2个没有数字的意图,第3个带有数字。此外,在PhoneStateListener中始终为空。您可以从意图中获取号码,保存它,并在以后需要时在PhoneStateListener中使用自己保存的号码。


-1

从Android 9开始,需要读取通话记录权限。但是该权限缺失。

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

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接