0

I'm developing an Android application that automatically picks up incoming calls on a device (let's call it Device B). After picking up the call, I want to play a predefined audio file after a 10-second delay so that the caller (Device A) hears the audio.

I've managed to create an auto pickup service. but currently, I'm facing issue in the audio plays on Device A (the caller).




package com.example.auto_pick_call;

import android.Manifest;
import android.app.Service;
import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.media.MediaPlayer;
import android.media.AudioManager;
import android.os.Build;
import android.os.Handler;
import android.os.IBinder;
import android.telecom.TelecomManager;
import android.util.Log;
import android.widget.Toast;

import androidx.core.content.ContextCompat;

public class AutoPickupService extends Service {

    private static final String TAG = "AutoPickupService";
    private MediaPlayer mediaPlayer;
    private AudioManager audioManager;

    @Override
    public void onCreate() {
        super.onCreate();
        Log.d(TAG, "Service Created");
        audioManager = (AudioManager) getSystemService(Context.AUDIO_SERVICE);
    }

    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {
        Log.d(TAG, "Service Started");

        // Check if we should play the audio
        if (intent != null && intent.getBooleanExtra("PLAY_AUDIO", false)) {
            playAudioWithDelay();
        }

        return START_STICKY;
    }

    private void playAudioWithDelay() {
        new Handler().postDelayed(new Runnable() {
            @Override
            public void run() {
                playAudio();
            }
        }, 10000); // 10 seconds delay
    }

    private void playAudio() {
        audioManager.setMode(AudioManager.MODE_IN_CALL);
        audioManager.setSpeakerphoneOn(false);
        mediaPlayer = MediaPlayer.create(this, R.raw.audio_file);
        mediaPlayer.start();
    }
    @Override
    public void onDestroy() {
        super.onDestroy();
        if (mediaPlayer != null) {
            mediaPlayer.release();
        }
        Log.d(TAG, "Service Destroyed");
    }

    @Override
    public IBinder onBind(Intent intent) {
        // This service is not designed to bind with an activity
        return null;
    }
}

0

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.