How to answer in incoming call programmatically in Android?

AndroidApps/ApplicationsMobile Development

This example demonstrates how to answer in incoming call programmatically in Android.

Step 1 − Create a new project in Android Studio, go to File ⇒ New Project and fill all required details to create a new project.

Step 2 − Add the following code to res/layout/activity_main.xml.

<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout
   xmlns:android="http://schemas.android.com/apk/res/android"
   xmlns:tools="http://schemas.android.com/tools"
   xmlns:app="http://schemas.android.com/apk/res-auto"
   android:layout_width="match_parent"
   android:layout_height="match_parent"
   tools:context=".MainActivity">
   <TextView
      android:layout_width="wrap_content"
      android:layout_height="wrap_content"
      android:text="Hello World!"
      app:layout_constraintBottom_toBottomOf="parent"
      app:layout_constraintLeft_toLeftOf="parent"
      app:layout_constraintRight_toRightOf="parent"
      app:layout_constraintTop_toTopOf="parent" />
</androidx.constraintlayout.widget.ConstraintLayout>

Step 3 − Add the following code to src/MainActivity.java

package com.app.sample;
import androidx.appcompat.app.AppCompatActivity;
import android.content.Context;
import android.content.Intent;
import android.os.Build;
import android.os.Bundle;
public class MainActivity extends AppCompatActivity {
   @Override
   protected void onCreate(Bundle savedInstanceState) {
      super.onCreate(savedInstanceState);
      setContentView(R.layout.activity_main);
   }
   public void acceptCall() {
      Context context = null;
      if (Build.VERSION.SDK_INT >= 21) {
         Intent answerCalintent = new Intent(context, AcceptCallActivity.class);
         answerCalintent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TASK | Intent.FLAG_ACTIVITY_EXCLUDE_FROM_RECENTS);
         answerCalintent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
         context.startActivity(answerCalintent);
      }
       else {
         Intent intent = new Intent(context, AcceptCallActivity.class);
         intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TASK | Intent.FLAG_ACTIVITY_EXCLUDE_FROM_RECENTS);
         intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
         context.startActivity(intent);
      }
   }
}

Step 4 − Add the following code to src/AcceptCallActivity.java

package com.app.sample;
import android.app.Activity;
import android.app.KeyguardManager;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.media.AudioManager;
import android.os.Build;
import android.os.Bundle;
import android.telephony.TelephonyManager;
import android.view.KeyEvent;
import android.view.WindowManager;
import java.io.IOException;
import java.util.logging.Logger;
public class AcceptCallActivity extends Activity {
   private static Logger logger =
   Logger.getLogger(String.valueOf(AcceptCallActivity.class));
   private static final String MANUFACTURER_HTC = "HTC";
   private KeyguardManager keyguardManager;
   private AudioManager audioManager;
   private CallStateReceiver callStateReceiver;
   @Override
   protected void onCreate(Bundle savedInstanceState) {
      super.onCreate(savedInstanceState);
      keyguardManager = (KeyguardManager) getSystemService(Context.KEYGUARD_SERVICE);
      audioManager = (AudioManager) getSystemService(Context.AUDIO_SERVICE);
   }
   @Override
   protected void onResume() {
      super.onResume();
      registerCallStateReceiver();
      updateWindowFlags();
      acceptCall();
   }
   @Override
   protected void onPause() {
      super.onPause();
      if (callStateReceiver != null) {
         unregisterReceiver(callStateReceiver);
         callStateReceiver = null;
      }
   }
   private void registerCallStateReceiver() {
      callStateReceiver = new CallStateReceiver();
      IntentFilter intentFilter = new IntentFilter();
      intentFilter.addAction(TelephonyManager.ACTION_PHONE_STATE_CHANGED);
      registerReceiver(callStateReceiver, intentFilter);
   }
   private void updateWindowFlags() {
      if (keyguardManager.inKeyguardRestrictedInputMode()) {
         getWindow().addFlags( WindowManager.LayoutParams.FLAG_DISMISS_KEYGUARD | WindowManager.LayoutParams.FLAG_TURN_SCREEN_ON | WindowManager.LayoutParams.FLAG_SHOW_WHEN_LOCKED);
      } else {
         getWindow().clearFlags( WindowManager.LayoutParams.FLAG_DISMISS_KEYGUARD | WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON | WindowManager.LayoutParams.FLAG_SHOW_WHEN_LOCKED);
      }
   }
   private void acceptCall() {
      boolean broadcastConnected = MANUFACTURER_HTC.equalsIgnoreCase(Build.MANUFACTURER) && !audioManager.isWiredHeadsetOn();
      if (broadcastConnected) {
         broadcastHeadsetConnected(false);
      }
      try {
         try {
            Runtime.getRuntime().exec("input keyevent " + Integer.toString(KeyEvent.KEYCODE_HEADSETHOOK));
         }
         catch (IOException e) {
            String enforcedPerm = "android.permission.CALL_PRIVILEGED";
            Intent btnDown = new Intent(Intent.ACTION_MEDIA_BUTTON).putExtra( Intent.EXTRA_KEY_EVENT, new KeyEvent(KeyEvent.ACTION_DOWN, KeyEvent.KEYCODE_HEADSETHOOK));
            Intent btnUp = new Intent(Intent.ACTION_MEDIA_BUTTON).putExtra( Intent.EXTRA_KEY_EVENT, new KeyEvent(KeyEvent.ACTION_UP, KeyEvent.KEYCODE_HEADSETHOOK));
            sendOrderedBroadcast(btnDown, enforcedPerm);
            sendOrderedBroadcast(btnUp, enforcedPerm);
         }
      }
      finally {
         if (broadcastConnected) {
               broadcastHeadsetConnected(false);
         }
      }
   }
   private void broadcastHeadsetConnected(boolean connected) {
      Intent i = new Intent(Intent.ACTION_HEADSET_PLUG);
      i.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY);
      i.putExtra("state", connected ? 1 : 0);
      i.putExtra("name", "mysms");
      try {
         sendOrderedBroadcast(i, null);
      }
      catch (Exception e) {
      }  
   }
   private class CallStateReceiver extends BroadcastReceiver {
      @Override
      public void onReceive(Context context, Intent intent) {
         finish();
      }
   }
}

Step 5 − Add the following code to Manifests/AndroidManifest.xml

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"  package="com.app.sample" >
   <application
      android:allowBackup="true"
      android:icon="@mipmap/ic_launcher"
      android:label="@string/app_name"
      android:roundIcon="@mipmap/ic_launcher_round"
      android:supportsRtl="true"
      android:theme="@style/AppTheme" >
      <activity android:name=".MainActivity" >
         <intent-filter>
            <action android:name="android.intent.action.MAIN" />
            <category android:name="android.intent.category.LAUNCHER" />
         </intent-filter>
      </activity>
   </application>
</manifest>

Let's try to run your application. I assume you have connected your actual Android Mobile device with your computer. To run the app from the android studio, open one of your project's activity files and click Run  icon from the toolbar. Select your mobile device as an option and then check your mobile device which will display your default screen −

Click here to download the project code.

raja
Published on 15-Nov-2019 10:18:45
Advertisements