Первым шагом было написание build.gradle.kts большая часть, если не все, уже была там iirc, использованная конфигурация включает следующее:
Код: Выделить всё
minSdk = 26
targetSdk = 34
Код: Выделить всё
Код: Выделить всё
public class BootCompletedReceiver extends BroadcastReceiver {
@Override
public void onReceive(Context context, Intent intent) {
if (intent != null && intent.getAction().equals(Intent.ACTION_BOOT_COMPLETED)) {
Intent serviceIntent = new Intent(context, ScreeningService.class);
context.startForegroundService(serviceIntent);
}
}
}
Код: Выделить всё
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
EdgeToEdge.enable(this);
setContentView(R.layout.activity_main);
//Intent serviceIntent = new Intent(MainActivity.this, ScreeningService.class);
Intent serviceIntent = new Intent(getApplicationContext(), ScreeningService.class);
startForegroundService(serviceIntent);
ViewCompat.setOnApplyWindowInsetsListener(findViewById(R.id.main), (v, insets) -> {
Insets systemBars = insets.getInsets(WindowInsetsCompat.Type.systemBars());
v.setPadding(systemBars.left, systemBars.top, systemBars.right, systemBars.bottom);
return insets;
});
}
Код: Выделить всё
public class ScreeningService extends CallScreeningService {
private static final String CHANNEL_ID = "call_screening_channel";
private String karen = "123456"; // omissis in StackOverflow, it has my other phone number with itnernational prefix
@Override
public void onCreate() {
super.onCreate();
createNotificationChannel();
}
@Override
public int onStartCommand(Intent intent, int flags, int startId) {
super.onStartCommand(intent, flags, startId);
Notification notification = createNotification();
startForeground(1, notification);
return START_STICKY;
}
private Notification createNotification() {
Context context = this;
NotificationCompat.Builder notificationBuilder = new NotificationCompat.Builder(context, CHANNEL_ID);
notificationBuilder.setContentTitle("Call Screening Alert");
notificationBuilder.setContentText("Call from Blacklisted Number");
notificationBuilder.setSmallIcon(R.drawable.app_icon);
notificationBuilder.setStyle(new NotificationCompat.BigTextStyle().bigText("Call from a blacklisted number"));
notificationBuilder.setPriority(NotificationCompat.PRIORITY_HIGH);
return notificationBuilder.build();
}
private void createNotificationChannel() {
//if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
CharSequence name = "Call Screening Channel";
String description = "Channel for call screening notifications";
int importance = NotificationManager.IMPORTANCE_HIGH;
NotificationChannel channel = new NotificationChannel(CHANNEL_ID, name, importance);
channel.setDescription(description);
NotificationManager notificationManager = getSystemService(NotificationManager.class);
notificationManager.createNotificationChannel(channel);
//}
}
@Nullable
@Override
public IBinder onBind(Intent intent) {
return null;
}
@Override
public void onScreenCall(Call.Details callDetails) {
String callingNumber = callDetails.getHandle().getSchemeSpecificPart();
Log.d("CallScreeningService", "onScreenCall called with number: " + callingNumber);
if (callingNumber != null && callingNumber.equals(karen)) {
// Decline the call if it's from your black list
CallResponse callResponse = new CallResponse.Builder()
.setDisallowCall(true)
.setRejectCall(true)
.setSkipCallLog(true)
.setSkipNotification(true)
.build();
respondToCall(callDetails, callResponse);
} else {
// Allow the call otherwise
CallResponse callResponse = new CallResponse.Builder()
.setDisallowCall(false)
.setRejectCall(false)
.build();
respondToCall(callDetails, callResponse);
}
}
}
Вторая ошибка, которая может быть связана с предыдущей: Я не могу запустить onScreenCall Я добавил запись в журнал и точки останова, но он никогда не выполняет проверку входящих вызовов, поэтому, вероятно, служба на самом деле не запущена, но приложение по какой-то причине всегда находится в активном режиме. В целях тестирования я установил номер для блокировки, но логика, которую я бы реализовал, другая, однако, если я не смогу пройти этот тривиальный шаг, бессмысленно писать более сложный дизайн.
Я предполагаю, что мне понадобится подходящий телефон на чистом Android для тестирования, а затем адаптировать свой код к другим устройствам, например, к моему с оболочкой EMUI, и кто знает, какие еще оболочки существуют для тестирования. Несмотря на это, я считаю, что телефоны REalme в некоторой степени популярны, поэтому лучше, если я исправлю это с самого начала.
Подробнее здесь: https://stackoverflow.com/questions/787 ... er-invoked