Giter Club home page Giter Club logo

flutter-phone-state-background's Introduction

phone_state_background

A flutter plugin to handle Phone Call State and execute a Dart callback in background.

Warning

This plugin only supported in android platform.


IOS Implementation

Corrently IOS is not supported. Unfortunately I'm not familiar with IOS development neither with Switf/ObjC languages, so if you wish to help any PR will be welcome.


Android

After importing this plugin to your project as usual, add the following to your AndroidManifest.xml within the <manifest></manifest> tags:

<uses-permission android:name="android.permission.READ_PHONE_STATE" />
<uses-permission android:name="android.permission.READ_CALL_LOG" />

Also, apparently it is necessary to register the broadcast receiver manually, otherwise an error will be throw saying that our receiver does not exist inside the app. Within the <application></application> tags:,

<receiver android:name="me.sodipto.phone_state_background.PhoneStateBackgroundServiceReceiver"
    android:exported="false">
    <intent-filter>
        <action android:name="android.intent.action.PHONE_STATE" />
    </intent-filter>
</receiver>

Getting started

All you need to start using our package after installing it, is defining a callback which must be a top level function or static function, that will be called by our plugin when any incoming or outgoing call events are detected.

@pragma('vm:entry-point') // Be sure to annotate your callback function to avoid issues in release mode on Flutter >= 3.3.0 void phoneStateBackgroundCallbackHandler(PhoneStateBackgroundEvent event, String number, int duration)

This callback handler must accept 3 arguments:

  • phoneStateBackgroundEvent: The event type detect by our plugin in background.

  • number: The incoming/outgoin number that is triggering the phone state call.

  • duration: An integer that represents the duration of the call in seconds.

The PhoneStateBackgroundEvent is an enum with four possible values:

Event Value Description
incomingstart Indicates an incoming call.
incomingmissed Indicates an incoming call missed.
incomingreceived Indicates an incoming call received.
incomingend Indicates an incoming call end.
outgoingstart Indicates an outgoing call start.
outgoingend Indicates an outgoing call end.

Since all this process happens in background in a Dart Isolate, there's no guarantee that the current OS will call the registered callback as soon as an event is triggered or that the callback will ever be called at all, each OS handle background services with different policies. Make sure to ask user permission before calling the PhoneStateBackground.initialize method of our plugin. Check the example to see a simple implementation of it.

/// Defines a callback that will handle all background incoming events
@pragma('vm:entry-point') // Be sure to annotate your callback function to avoid issues in release mode on Flutter >= 3.3.0
Future<void> phoneStateBackgroundCallbackHandler(
  PhoneStateBackgroundEvent event,
  String number,
  int duration,
) async {
  switch (event) {
    case PhoneStateBackgroundEvent.incomingstart:
      print('Incoming call start, number: $number, duration: $duration s');
      break;
    case PhoneStateBackgroundEvent.incomingmissed:
      print('Incoming call missed, number: $number, duration: $duration s');
      break;
    case PhoneStateBackgroundEvent.incomingreceived:
      print('Incoming call received, number: $number, duration: $duration s');
      break;
    case PhoneStateBackgroundEvent.incomingend:
      print('Incoming call ended, number: $number, duration $duration s');
      break;
    case PhoneStateBackgroundEvent.outgoingstart:
      print('Ougoing call start, number: $number, duration: $duration s');
      break;
    case PhoneStateBackgroundEvent.outgoingend:
      print('Ougoing call ended, number: $number, duration: $duration s');
      break;
  }
}

flutter-phone-state-background's People

Contributors

sodipto avatar

Stargazers

Uri Patton avatar Rahul Roy avatar  avatar Sirajul Islam avatar Leó Takács avatar

Watchers

Uri Patton avatar  avatar

flutter-phone-state-background's Issues

Outgoing call Duration Issue

When I dial the call which is basically Outgoing so before the receiver answers the call the call duration starts

phoneStateBackgroundCallbackHandler never responds

It run
"await PhoneStateBackground.initialize(phoneStateBackgroundCallbackHandler);"
and completed without any problem, but phoneStateBackgroundCallbackHandler never responds to phone calls.
I added

<uses-permission android:name="android.permission.READ_PHONE_STATE" />
  <uses-permission android:name="android.permission.READ_CALL_LOG" />
  <uses-permission android:name="android.permission.CALL_PHONE" />
  <application
....
      <receiver android:name="me.sodipto.phone_state_background.PhoneStateBackgroundServiceReceiver"
          android:exported="false">
          <intent-filter>
              <action android:name="android.intent.action.PHONE_STATE" />
          </intent-filter>

to AndroidManifest.xml, what else did I miss?

probleme in release mode

[When I am in debug mode, the caller package works fine, but when I switch to release mode, it cannot find the caller package. What should I do?

E/flutter (31645): [ERROR:flutter/shell/common/shell.cc(89)] Dart Error: Dart_LookupLibrary: library 'package:phone_state_background/phone_state_background.dart' not found.
E/flutter (31645): [ERROR:flutter/runtime/dart_isolate.cc(668)] Could not resolve main entrypoint function.
E/flutter (31645): [ERROR:flutter/runtime/dart_isolate.cc(168)] Could not run the run main Dart entrypoint.
E/flutter (31645): [ERROR:flutter/runtime/runtime_controller.cc(417)] Could not create root isolate.
E/flutter (31645): [ERROR:flutter/shell/common/shell.cc(606)] Could not launch engine with configuration.

phoneStateBackgroundCallbackHandler; Unhandled Exception: RangeError (length): Invalid value

@sodipto I often have this problem when I make a call. I don't understand the error.

): Ougoing call start, number: 1800, duration: 0 s
I/flutter ( 2586): Ougoing call ended, number: 1800, duration: 2 s

E/flutter ( 2586): [ERROR:flutter/runtime/dart_vm_initializer.cc(41)] Unhandled Exception: RangeError (length): Invalid value: Only valid value is 0: 1
E/flutter ( 2586): #0 phoneStateBackgroundCallbackHandler (package:eurgencev1/main.dart)
E/flutter ( 2586):

Need Help

how to communicate with phoneStateBackgroundCallbackHandler call back to UI i.e. when outgoing call start button will be disable and after disconnect the call the button will be enable.

androidPackage issue

If you are the author of this plugin, fix the androidPackage entry or move the main class to any of locations used above. Otherwise, please contact the author of this plugin and consider using a different plugin in the meanwhile.
the issue is in plugin name too large more than 23 words

No implementation found for method hasPermission on channel

test() async {
try {
await audioRecorder.hasPermission();
} catch (e) {
print(e);
}
}

Future phoneStateBackgroundCallbackHandler(
PhoneStateBackgroundEvent event,
String number,
int duration,
) async {
switch (event) {
case PhoneStateBackgroundEvent.incomingstart:
test();
print("telephone sonne appel entrant");
break;
case PhoneStateBackgroundEvent.incomingmissed:
//
break;
case PhoneStateBackgroundEvent.incomingreceived:
//
break;
case PhoneStateBackgroundEvent.incomingend:
//
print("Appel terminé");
break;
case PhoneStateBackgroundEvent.outgoingstart:
//
break;
case PhoneStateBackgroundEvent.outgoingend:
//
break;
}
}

Future Lencement_appel() async {
test(bool); // return true
final permission = await PhoneStateBackground.checkPermission();
if (permission != true) return;
await PhoneStateBackground.initialize(phoneStateBackgroundCallbackHandler);
}

//********* error ********** //

I/flutter ( 4489): MissingPluginException(No implementation found for method hasPermission on channel com.llfbandit.record/messages)

Recover phone number

Thank you for this package. How can I retrieve the incoming caller number while the phone is ringing? I want to access the phone number and display it on the screen.

WhatsApp calls?

I testing application on my clients physical devices (Samsung).
It is working very good, but sometimes I have event "incomingmissed" without number and with duration 0.
Probably this is when client using WhatsApp call.
It happens that after this event the applications going to sleep.

Anybody have problem like this?

READ_CALL_LOG opt out

Hey, thanks for making this plugin, it will come handy in one of my projects!

I have a suggestion which would make the plugin even better.

Problem

I want to trigger my code on incoming call and I don't need to see the number.

Currently the plugin forces me to declare android.permission.READ_CALL_LOG permission, which would be excessive for my app's functionality and would cause an obvious mistrust from the user's side.

Solution

Allow to use plugin to use without android.permission.READ_CALL_LOG, making its declaration optional.

probleme in mode release

I still have the same problem. I just installed a new project. I copied your code online to insert into my code on VSCode. I ran 'flutter run --release'. I use android 12

I/flutter (19983): #98 Element.updateChild (package:flutter/src/widgets/framework.dart:3682)
I/flutter (19983): #99 ComponentElement.performRebuild (package:flutter/src/widgets/framework.dart:4993)
I/flutter (19983): Permission true
W/FlutterJNI(19983): FlutterJNI.loadLibrary called more than once
W/FlutterJNI(19983): FlutterJNI.prefetchDefaultFontManager called more than once
W/FlutterJNI(19983): FlutterJNI.init called more than once
W/FlutterJNI(20904): FlutterJNI.loadLibrary called more than once
W/FlutterJNI(20904): FlutterJNI.init called more than once
E/flutter (20904): [ERROR:flutter/shell/common/shell.cc(89)] Dart Error: Dart_LookupLibrary: library 'package:phone_state_background/phone_state_background.dart' not found.
E/flutter (20904): [ERROR:flutter/runtime/dart_isolate.cc(668)] Could not resolve main entrypoint function.
E/flutter (20904): [ERROR:flutter/runtime/dart_isolate.cc(168)] Could not run the run main Dart entrypoint.
E/flutter (20904): [ERROR:flutter/runtime/runtime_controller.cc(417)] Could not create root isolate.
E/flutter (20904): [ERROR:flutter/shell/common/shell.cc(606)] Could not launch engine with configuration.

Outdated version of Kotlin

I am getting the following error when using the plugin:

FAILURE: Build failed with an exception.

* What went wrong:
The Android Gradle plugin supports only Kotlin Gradle plugin version 1.5.20 and higher.
The following dependencies do not satisfy the required version:
project ':phone_state_background' -> org.jetbrains.kotlin:kotlin-gradle-plugin:1.3.50

* Try:
> Run with --stacktrace option to get the stack trace.
> Run with --info or --debug option to get more log output.
> Run with --scan to get full insights.

Error: java.lang.ClassCastException: java.lang.Integer cannot be cast to java.lang.Long

Hello,

I have a problem with your package. When I run it on a real device, this error occurs:

PlatformException (PlatformException(error, java.lang.Integer cannot be cast to java.lang.Long, null, java.lang.ClassCastException: java.lang.Integer cannot be cast to java.lang.Long
	at me.sodipto.phone_state_background.PhoneStateBackgroundPlugin.onMethodCall(PhoneStateBackgroundPlugin.kt:56)
	at io.flutter.plugin.common.MethodChannel$IncomingMethodCallHandler.onMessage(MethodChannel.java:258)
	at io.flutter.embedding.engine.dart.DartMessenger.invokeHandler(DartMessenger.java:295)
	at io.flutter.embedding.engine.dart.DartMessenger.lambda$dispatchMessageToQueue$0$io-flutter-embedding-engine-dart-DartMessenger(DartMessenger.java:322)
	at io.flutter.embedding.engine.dart.DartMessenger$$ExternalSyntheticLambda0.run(Unknown Source:12)
	at android.os.Handler.handleCallback(Handler.java:873)
	at android.os.Handler.dispatchMessage(Handler.java:99)
	at android.os.Looper.loop(Looper.java:216)
	at android.app.ActivityThread.main(ActivityThread.java:7266)
	at java.lang.reflect.Method.invoke(Native Method)
	at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:494)
	at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:975)
))

These are my values when the application crashes:
Screenshot 2023-07-07 at 17 52 44

The method onEventCallback!.toRawHandle() in lib/phone_state_background.dart on line 32 returns int, but line 56 in android/src/main/kotlin/me/sodipto/phone_state_background/PhoneStateBackgroundPlugin.kt expects long.

Can you please fix the conversion so it works with int values as well?

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.