Aman Malhotra
Aman Malhotra

Reputation: 3186

How to listen to Phone Calls in flutter App?

I'll try to ask it in as simple a way as I can. If my app is running in foreground and, I get a phone call at that very moment, is there any way I can call a function/perform an operation when this happens?

// My App is open at any random time call received
(if call_Received) { // How do I do this bit via dart code?
 sample()
}

void sample() { // Any random function
  // Some code to perform
}

Upvotes: 16

Views: 10049

Answers (4)

Mr Random
Mr Random

Reputation: 2218

I personally use flutter_phone_state plugin and it works fine for me. But the package on the pub pub.dev is outdated and no longer maintained. So add below git url on pubspec.yaml instead.

  flutter_phone_state:
    git:
      url: https://github.com/SimformSolutionsPvtLtd/flutter_phone_state.git
      ref: feature/null-safety

Documentation link

Upvotes: 0

ABV
ABV

Reputation: 895

Please check https://pub.dev/packages/phone_state. I believe it will work for you. If you still having an issue with that, Please let me know.

Example snippet:

import 'dart:io';
import 'package:flutter/material.dart';
import 'package:permission_handler/permission_handler.dart';
import 'package:phone_state/phone_state.dart';

main() {
  runApp(
    const MaterialApp(
      home: Example(),
    ),
  );
}

class Example extends StatefulWidget {
  const Example({Key? key}) : super(key: key);

  @override
  _ExampleState createState() => _ExampleState();
}

class _ExampleState extends State<Example> {
  PhoneStateStatus status = PhoneStateStatus.NOTHING;
  bool granted = false;

  Future<bool> requestPermission() async {
    var status = await Permission.phone.request();

    switch (status) {
      case PermissionStatus.denied:
      case PermissionStatus.restricted:
      case PermissionStatus.limited:
      case PermissionStatus.permanentlyDenied:
        return false;
      case PermissionStatus.granted:
        return true;
    }
  }

  @override
  void initState() {
    super.initState();
    if (Platform.isIOS) setStream();
  }

  void setStream() {
    PhoneState.phoneStateStream.listen((event) {
      setState(() {
        if (event != null) {
          status = event;
        }
      });
    });
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: const Text("Phone State"),
        centerTitle: true,
      ),
      body: Center(
        child: Column(
          mainAxisAlignment: MainAxisAlignment.center,
          crossAxisAlignment: CrossAxisAlignment.center,
          children: [
            if (Platform.isAndroid)
              MaterialButton(
                child: const Text("Request permission of Phone"),
                onPressed: !granted
                    ? () async {
                        bool temp = await requestPermission();
                        setState(() {
                          granted = temp;
                          if (granted) {
                            setStream();
                          }
                        });
                      }
                    : null,
              ),
            const Text(
              "Status of call",
              style: TextStyle(fontSize: 24),
            ),
            Icon(
              getIcons(),
              color: getColor(),
              size: 80,
            )
          ],
        ),
      ),
    );
  }

  IconData getIcons() {
    switch (status) {
      case PhoneStateStatus.NOTHING:
        return Icons.clear;
      case PhoneStateStatus.CALL_INCOMING:
        return Icons.add_call;
      case PhoneStateStatus.CALL_STARTED:
        return Icons.call;
      case PhoneStateStatus.CALL_ENDED:
        return Icons.call_end;
    }
  }

  Color getColor() {
    switch (status) {
      case PhoneStateStatus.NOTHING:
      case PhoneStateStatus.CALL_ENDED:
        return Colors.red;
      case PhoneStateStatus.CALL_INCOMING:
        return Colors.green;
      case PhoneStateStatus.CALL_STARTED:
        return Colors.orange;
    }
  }
}

Upvotes: 1

Hossein Sajadinia
Hossein Sajadinia

Reputation: 594

you can use https://pub.flutter-io.cn/packages/phone_state_i but you must customize this package because you will receive a build error when you want to build apk. so customize the package and change compileSdkVersion from 27 to 28. for more information, you can see issues part of package.

Upvotes: 0

Richa Shah
Richa Shah

Reputation: 974

As https://pub.dev/packages/phonecallstate#-example-tab-package is not working u can use new package phone_state_i 0.0.3 with https://pub.dev/packages/phone_state_i#-readme-tab-

import 'package:phone_state_i/phone_state_i.dart';

phoneStateCallEvent.listen((PhoneStateCallEvent event) {
      print('Call is Incoming/Connected' + event.stateC);
      //event.stateC has values "true" or "false"
});

Upvotes: 0

Related Questions