android oreo 获取服务中的来电号码

android oreo get incoming call number in service

我正在实施代码以在 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);

 }
}

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

我不确定这里的根本原因,但是,您实际上不需要 PhoneStateListener 来获取来电号码。虽然它应该是 return 这个数字,但在某些设备上它 return 是空字符串几次或者可能总是。你可以做的是从意图中获取数字:

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 中始终为空。您可以从 Intent 中获取号码,保存它,并在以后需要时在 PhoneStateListener 中使用您自己保存的号码。

请尝试这是否适合您。

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>

来自android9,需要读取通话记录权限。缺少权限。

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