我正在实现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