Coder Social home page Coder Social logo

shounakmulay / telephony Goto Github PK

View Code? Open in Web Editor NEW
132.0 4.0 119.0 264 KB

Flutter plugin for telephony features like query device sms directory, listen for incoming messages, retrieve various network parameters, etc.

Home Page: https://telephony.shounakmulay.dev

License: MIT License

Kotlin 41.65% Swift 0.45% Objective-C 0.57% Dart 56.54% Ruby 0.79%
flutter telephony plugin android sms-messages

telephony's Introduction

Telephony

Thank you for checking out the Telephony plugin. Unfortunately, this plugin is no longer actively maintained.

❗ This plugin currently only works on Android Platform

A Flutter plugin to use telephony features such as

  • Send SMS Messages
  • Query SMS Messages
  • Listen for incoming SMS
  • Retrieve various network parameters
  • Start phone calls

This plugin tries to replicate some of the functionality provided by Android's Telephony class.

Check the Features section to see the list of implemented and missing features.

Get Started

Usage

To use this plugin add telephony as a dependency in your pubspec.yaml file.

Versions 0.0.9 and lower are not null safe.
Versions 0.1.0 and above opt into null safety.

Setup

Import the telephony package

import 'package:telephony/telephony.dart';

Retrieve the singleton instance of telephony by calling

final Telephony telephony = Telephony.instance;

Although this plugin will check and ask for permissions at runtime, it is advisable to manually ask for permissions before calling any other functions.

The plugin will only request those permission that are listed in the AndroidManifest.xml.

Manually request permission using

bool permissionsGranted = await telephony.requestPhoneAndSmsPermissions;

You can also request SMS or Phone permissions separately using requestSmsPermissions or requestPhonePermissions respectively.

❗ Requires SEND_SMS permission. Add the following permission in your AndroidManifest.xml

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

SMS can either be sent directly or via the default SMS app.

Send SMS directly from your app:

telephony.sendSms(
	to: "1234567890",
	message: "May the force be with you!"
	);

If you want to listen to the status of the message being sent, provide SmsSendStatusListener to the sendSms function.

final SmsSendStatusListener listener = (SendStatus status) {
	// Handle the status
	};
	
telephony.sendSms(
	to: "1234567890",
	message: "May the force be with you!",
	statusListener: listener
	);

If the body of the message is longer than the standard SMS length limit of 160 characters, you can send a multipart SMS by setting the isMultipart flag.

Send SMS via the default SMS app:

telephony.sendSmsByDefaultApp(to: "1234567890", message: "May the force be with you!");

❗ Requires READ_SMS permission. Add the following permission in your AndroidManifest.xml

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

Use one of getInboxSms(), getSentSms() or getDraftSms() functions to query the messages on device.

You can provide the list of SmsColumns that need to be returned by the query.

If not explicitly specified, defaults to [ SmsColumn.ID, SmsColumn.ADDRESS, SmsColumn.BODY, SmsColumn.DATE ]

Provide a SmsFilter to filter the results of the query. Functions like a SQL WHERE clause.

Provide a list of OrderBy objects to sort the results. The level of importance is determined by the position of OrderBy in the list.

All paramaters are optional.

List<SmsMessage> messages = await telephony.getInboxSms(
		columns: [SmsColumn.ADDRESS, SmsColumn.BODY],
		filter: SmsFilter.where(SmsColumn.ADDRESS)
				 .equals("1234567890")
				 .and(SmsColumn.BODY)
				 .like("starwars"),
		sortOrder: [OrderBy(SmsColumn.ADDRESS, sort: Sort.ASC),
			    OrderBy(SmsColumn.BODY)]
		);

❗ Requires READ_SMS permission. Add the following permission in your AndroidManifest.xml

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

Works similar to SMS queries.

All columns are returned with every query. They are [ ConversationColumn.SNIPPET, ConversationColumn.THREAD_ID, ConversationColumn.MSG_COUNT ]

Uses ConversationFilter instead of SmsFilter.

List<SmsConversation> messages = await telephony.getConversations(
		filter: ConversationFilter.where(ConversationColumn.MSG_COUNT)
					  .equals("4")
					  .and(ConversationColumn.THREAD_ID)
					  .greaterThan("12"),
		sortOrder: [OrderBy(ConversationColumn.THREAD_ID, sort: Sort.ASC)]
		);

❗ Requires RECEIVE_SMS permission.

  1. To listen to incoming SMS add the RECEIVE_SMS permission to your AndroidManifest.xml file and register the BroadcastReceiver.
<manifest>
	<uses-permission android:name="android.permission.RECEIVE_SMS"/>

	<application>
		...
		...

		<receiver android:name="com.shounakmulay.telephony.sms.IncomingSmsReceiver"
		    android:permission="android.permission.BROADCAST_SMS" android:exported="true">
		    <intent-filter>
			<action android:name="android.provider.Telephony.SMS_RECEIVED"/>
		    </intent-filter>
		</receiver>

	</application>
</manifest>
  1. Create a top-level static function to handle incoming messages when app is not is foreground.

    ⚠️ Avoid heavy computations in the background handler as Android system may kill long running operations in the background.

backgrounMessageHandler(SmsMessage message) async {
	//Handle background message	
}

void main() {
  runApp(MyApp());
}
  1. Call listenIncomingSms with a foreground MessageHandler and pass in the static backgrounMessageHandler.
telephony.listenIncomingSms(
		onNewMessage: (SmsMessage message) {
			// Handle message
		},
		onBackgroundMessage: backgroundMessageHandler
	);

Preferably should be called early in app lifecycle.

  1. If you do not wish to receive incoming SMS when the app is in background, just do not pass the onBackgroundMessage paramater.

    Alternatively if you prefer to expecility disable background execution, set the listenInBackground flag to false.

telephony.listenIncomingSms(
		onNewMessage: (SmsMessage message) {
			// Handle message
		},
		listenInBackground: false
	);
  1. As of the 1.12 release of Flutter, plugins are automatically registered. This will allow you to use plugins as you normally do even in the background execution context.
backgrounMessageHandler(SmsMessage message) async {
		// Handle background message
		
		// Use plugins
		Vibration.vibrate(duration: 500);
	}

Fetch various metrics such as network type, sim state, etc.

// Check if a device is capable of sending SMS
bool canSendSms = await telephony.isSmsCapable;

// Get sim state
SimState simState = await telephony.simState;

Check out the detailed documentation to know all possible metrics and their values.

Executing in background

If you want to call the telephony methods in background, you can do in the following ways.

1. Using only Telephony.instance

If you want to continue using Telephony.instance in the background, you will need to make sure that once the app comes back to the front, it again calls Telephony.instance.

backgrounMessageHandler(SmsMessage message) async {
	// Handle background message
	Telephony.instance.sendSms(to: "123456789", message: "Message from background")
}

void main() {
  runApp(MyApp());
}

class _MyAppState extends State<MyApp> {
  String _message;
  // This will not work as the instance will be replaced by
  // the one in background.
  final telephony = Telephony.instance;
  
   @override
  void initState() {
    super.initState();
    // You should make sure call to instance is made every time 
    // app comes to foreground
    final inbox = Telephony.instance.getInboxSms()
  }

2. Use backgroundInstance

If you cannot make sure that the call to instance would be made every time app comes to foreground, or if you would prefer to maintain a separate background instance, you can use Telephony.backgroundInstance in the background execution context.

backgrounMessageHandler(SmsMessage message) async {
	// Handle background message
	Telephony.backgroundInstance.sendSms(to: "123456789", message: "Message from background")
}

void main() {
  runApp(MyApp());
}

class _MyAppState extends State<MyApp> {
  String _message;
  final telephony = Telephony.instance;
  
   @override
  void initState() {
    super.initState();
    final inbox = telephony.getInboxSms()
  }

Features

telephony's People

Contributors

blacklizard avatar faizann avatar mabsten avatar meomap avatar michealreed avatar shounak-mulay avatar shounakmulay avatar thoughtworks-tcaceres avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar

telephony's Issues

Read inbox throws casting problem

While trying to read SMS using the following code, I get a casting problem.

List messages = await telephony.getInboxSms()

The error log says,
Unhandled Exception: type 'List<Object?>' is not a subtype of type 'List<LinkedHashMap<dynamic, dynamic>>?' in type cast

Telephony.getInboxSms (package:telephony/telephony.dart:177:22)

Sender

RaisedButton(onPressed: () async {
Telephony telephony = Telephony.instance;
bool permissionsGranted = await telephony.requestSmsPermissions;
if(permissionsGranted != false){
await telephony.sendSms(
 to: "+251904094817", 
// from: "7809" like this 
message: "May the force be with you!");
} else {print("sh*t error"); } })

bro I wanted to send these sms from one sender phone number, it is logical?

Mark selected received messages as read

Hi, thanks for the amazing work,
Is there a way to mark some message in receive handler as read or even delete them?
Is there any delete message functionality currently available?

An error occurs when send SMS in background

Hi Team,

When receive SMS �in Background, I send another SMS but I got this error:
_[ERROR:flutter/lib/ui/ui_dart_state.cc(177)] Unhandled Exception: MissingPluginException(No implementation found for method sendSms on channel plugins.shounakmulay.com/foreground_sms_channel)
E/flutter (24790): #0 MethodChannel._invokeMethod (package:flutter/src/services/platform_channel.dart:157:7)
E/flutter (24790):
E/flutter (24790): #1 MethodChannel.invokeMethod (package:flutter/src/services/platform_channel.dart:332:12)
E/flutter (24790): #2 Telephony.sendSms (package:telephony/telephony.dart:315:30)
E/flutter (24790): #3 forwardMessages (package:FwSms/main.dart:59:19)
E/flutter (24790):
E/flutter (24790): #4 onBackgroundMessage (package:FwSms/main.dart:76:3)
E/flutter (24790): #5 _flutterSmsSetupBackgroundChannel. (package:telephony/telephony.dart:27:30)
E/flutter (24790): #6 MethodChannel._handleAsMethodCall (package:flutter/src/services/platform_channel.dart:430:55)
E/flutter (24790): #7 MethodChannel.setMethodCallHandler. (package:flutter/src/services/platform_channel.dart:383:34)
E/flutter (24790): #8 _DefaultBinaryMessenger.handlePlatformMessage (package:flutter/src/services/binding.dart:283:33)
E/flutter (24790): #9 _invoke3. (dart:ui/hooks.dart:280:15)
E/flutter (24790): #10 _rootRun (dart:async/zone.dart:1190:13)
E/flutter (24790): #11 _CustomZone.run (dart:async/zone.dart:1093:19)
E/flutter (24790): #12 _CustomZone.runGuarded (dart:async/zone.dart:997:7)
E/flutter (24790): #13 _invoke3 (dart:ui/hooks.dart:279:10)
E/flutter (24790): #14 dispatchPlatformMessage (dart:ui/hooks.dart:154:5)

If I open the app, it works fine.

Thank you very much.

Best,
Cuong

Error with Flutter 2.2.0

Hi. Since I updated Flutter to 2.2.0 I get this error and can't use this package.
Error: telephony-0.1.3\android\src\main\kotlin\com\shounakmulay\telephony\sms\SmsMethodCallHandler.kt: (52, 62): Expecting a parameter declaration

Listen for events when app is in foreground not work anymore after background isolate is started

Problem reproduction:

  • Setup listenIncomingSms with both options of onNewMessage and onBackgroundMessage specified as illustrated at

    telephony.listenIncomingSms(

  • Open example app, simulate an sms event. onNewMessage is triggered as expected.

  • Send app to background, resend. onBackgroundMessage is triggered and background isolate is started.

  • Bring app back to front, resend. onNewMessage at dart side shows no sign of receiving event.

It seems that foregroundSmsChannel?.invokeMethod(ON_MESSAGE, args) at android side don't work anymore after isolate is executed.

I think the problem is at flutter side that is related to this issue flutter/flutter#23904

Example Code Not Working

I copied the example code and added the necessary permissions in manifest and still didn't receive message in onMessage and in onBackgroundMessage. Any help would be appreciated. Plugin isn't asking for permissions too.

 Future<void> initPlatformState() async {
    // Platform messages may fail, so we use a try/catch PlatformException.
    // If the widget was removed from the tree while the asynchronous platform
    // message was in flight, we want to discard the reply rather than calling
    // setState to update our non-existent appearance.

    final bool result = await telephony.requestPhoneAndSmsPermissions;

    if (result != null && result) {
      telephony.listenIncomingSms(
          onNewMessage: onMessage, onBackgroundMessage: onBackgroundMessage);
    }

    if (!mounted) return;
  }

Fails on latest version of flutter/dart

Because no versions of path_provider match >2.0.1 <3.0.0 and path_provider 2.0.1 depends on path_provider_platform_interface ^2.0.0, path_provider ^2.0.1 requires path_provider_platform_interface ^2.0.0.
And because path_provider_platform_interface >=2.0.0 depends on platform ^3.0.0 and telephony >=0.0.8 depends on platform ^2.2.1, path_provider ^2.0.1 is incompatible with telephony >=0.0.8.
So, because musicplayer depends on both telephony ^0.0.8 and path_provider ^2.0.1, version solving failed.
pub get failed (1; So, because musicplayer depends on both telephony ^0.0.8 and path_provider ^2.0.1, version solving failed.)

ensureInitializationComplete must be called after startInitialization

Hi. I am trying to get SMS details when the app is in background or not running. after I receive the SMS, the app crashes in bckground. Please help me fix this.

STEPS RO REPRODUCE

  1. clone the Telephony Example project
  2. run the project in VSCODE without debug mode.
  3. Receive SMS while in app or while the app is in background (They give the same error).

I run this on android 8 on LG H990 (LG V20)

Then I get this error:

E/AndroidRuntime(25457): FATAL EXCEPTION: main
E/AndroidRuntime(25457): Process: com.example.sms, PID: 25457
E/AndroidRuntime(25457): java.lang.RuntimeException: Unable to start receiver com.shounakmulay.telephony.sms.IncomingSmsReceiver: java.lang.IllegalStateException: ensureInitializationComplete must be called after startInitialization
E/AndroidRuntime(25457): 	at android.app.ActivityThread.handleReceiver(ActivityThread.java:3329)
E/AndroidRuntime(25457): 	at android.app.ActivityThread.-wrap17(Unknown Source:0)
E/AndroidRuntime(25457): 	at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1696)
E/AndroidRuntime(25457): 	at android.os.Handler.dispatchMessage(Handler.java:105)
E/AndroidRuntime(25457): 	at android.os.Looper.loop(Looper.java:164)
E/AndroidRuntime(25457): 	at android.app.ActivityThread.main(ActivityThread.java:6710)
E/AndroidRuntime(25457): 	at java.lang.reflect.Method.invoke(Native Method)
E/AndroidRuntime(25457): 	at com.android.internal.os.Zygote$MethodAndArgsCaller.run(Zygote.java:240)
E/AndroidRuntime(25457): 	at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:770)
E/AndroidRuntime(25457): Caused by: java.lang.IllegalStateException: ensureInitializationComplete must be called after startInitialization
E/AndroidRuntime(25457): 	at io.flutter.embedding.engine.loader.FlutterLoader.ensureInitializationComplete(FlutterLoader.java:174)
E/AndroidRuntime(25457): 	at com.shounakmulay.telephony.sms.IncomingSmsReceiver.processInBackground(IncomingSmsHandler.kt:77)
E/AndroidRuntime(25457): 	at com.shounakmulay.telephony.sms.IncomingSmsReceiver.processIncomingSms(IncomingSmsHandler.kt:69)
E/AndroidRuntime(25457): 	at com.shounakmulay.telephony.sms.IncomingSmsReceiver.onReceive(IncomingSmsHandler.kt:46)
E/AndroidRuntime(25457): 	at android.app.ActivityThread.handleReceiver(ActivityThread.java:3318)
E/AndroidRuntime(25457): 	... 8 more

Flutter Doctor output:

Doctor summary (to see all details, run flutter doctor -v):
[√] Flutter (Channel stable, 1.22.0, on Microsoft Windows [Version 10.0.18363.1198], locale en-US)
 
[√] Android toolchain - develop for Android devices (Android SDK version 29.0.3)
[√] Android Studio (version 3.6)
[√] VS Code (version 1.51.1)
[√] Connected device (1 available)

• No issues found!

Problem during Gradle task 'assembleRelease'

Hi,

I am relatively new to flutter apps, rather for mobile apps.

Thank you so much for providing the Telephony plugin, that made life easier for me.
I am using all the features provided by Telephony and testing on MI A2 (Android 10) phone. While the debug version works smoothly, building APK (release mode) gradle fails with long list of information that does not give any clue. Giving below a glimpse

**Running Gradle task 'assembleRelease'...

FAILURE: Build failed with an exception.

  • What went wrong:
    Execution failed for task ':app:lintVitalRelease'.**

As there was no issue before I added Telephony, so I re-checked updating pucspec.yami and AndriodManifest.xml step-by-stp and found that when following is added to AndroidManifest.xml, the issue crops up

    **<receiver android:name="com.shounakmulay.telephony.sms.IncomingSmsReceiver"
              android:permission="android.permission.BROADCAST_SMS" android:exported="true">
        <intent-filter>
            <action android:name="android.provider.Telephony.SMS_RECEIVED"/>
        </intent-filter>
    </receiver>**

Please note that adding above also necessitates to add following in pubspec.yami

plugin:
platforms:
android:
package: com.shounakmulay.telephony
pluginClass: TelephonyPlugin
ios:
pluginClass: TelephonyPlugin

However, once this happens even if I remove above portion, the error remains, and it leaves me baffled, can you please help?

lateinit property smsChannel has not been initialized

when uninstall app and reinstall it i have this issue :

E/AndroidRuntime(13514): kotlin.UninitializedPropertyAccessException: lateinit property smsChannel has not been initialized
E/AndroidRuntime(13514): at com.shounakmulay.telephony.TelephonyPlugin.tearDownPlugin(TelephonyPlugin.kt:68)
E/AndroidRuntime(13514): at com.shounakmulay.telephony.TelephonyPlugin.onDetachedFromEngine(TelephonyPlugin.kt:34)
E/AndroidRuntime(13514): at io.flutter.embedding.engine.FlutterEnginePluginRegistry.remove(FlutterEnginePluginRegistry.java:252)
E/AndroidRuntime(13514): at io.flutter.embedding.engine.FlutterEnginePluginRegistry.remove(FlutterEnginePluginRegistry.java:260)
E/AndroidRuntime(13514): at io.flutter.embedding.engine.FlutterEnginePluginRegistry.removeAll(FlutterEnginePluginRegistry.java:268)
E/AndroidRuntime(13514): at io.flutter.embedding.engine.FlutterEnginePluginRegistry.destroy(FlutterEnginePluginRegistry.java:112)
E/AndroidRuntime(13514): at io.flutter.embedding.engine.FlutterEngine.destroy(FlutterEngine.java:365)
E/AndroidRuntime(13514): at be.tramckrijte.workmanager.BackgroundWorker$stopEngine$1.run(BackgroundWorker.kt:117)
E/AndroidRuntime(13514): at android.os.Handler.handleCallback(Handler.java:873)
E/AndroidRuntime(13514): at android.os.Handler.dispatchMessage(Handler.java:99)
E/AndroidRuntime(13514): at android.os.Looper.loop(Looper.java:214)
E/AndroidRuntime(13514): at android.app.ActivityThread.main(ActivityThread.java:7050)
E/AndroidRuntime(13514): at java.lang.reflect.Method.invoke(Native Method)
E/AndroidRuntime(13514): at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:494)
E/AndroidRuntime(13514): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:965)

Multi-sim Sending Support

Good Day.

I want to thank you for this plugin. I am going over the documentation, but cant seem to find if this plugin currently supports multi sim? Specifically, is there a way to select sim slot 1 or slot 2 in sending SMS?

Thank you.

telephony.sendSms's Future never completes

Hi, consider the following code

 await telephony.sendSms(
        to: "PHONE_NUMBER",
        message: "Sample message",
        statusListener: (status) {
          log("status = $status");
        });
  log("sent completed"); // this line never runs

if I await sendSms, the last line never runs although the message is delivered successfully.

Example code not running

Because every version of integration_test from sdk depends on flutter_driver any from sdk which depends on platform 3.0.0-nullsafety.4, every version of integration_test from sdk requires platform 3.0.0-nullsafety.4.
And because every version of telephony depends on platform ^2.0.0, integration_test from sdk is incompatible with telephony.
So, because flutter_app_sms depends on both telephony ^0.0.7 and integration_test any from sdk, version solving failed.
pub get failed (1; So, because flutter_app_sms depends on both telephony ^0.0.7 and integration_test any from sdk, version solving failed.)

i get this error when i try to run the example code. could you please help?

Listening / receiving sms does not work

Copied the entire example into a new flutter project.
android manifest minsdk 19,
permissions set, receiver included
connected my phone via usb with android studio.
loaded app and got a friend to send me an sms.
app only ever says 'latest: null'
receiver never seems to fire - adding print('hi') doesn't fire in onBackgroundMessage(), or onMessage()
any ideas?

edit: RCS was the issue.

type 'Future<dynamic>' is not a subtype of type 'FutureOr<List<dynamic>>' in type cast

Hi,

Facing the below error when I try to get inbox sms:

I/flutter (13138): AsyncSnapshot<Object?>(ConnectionState.done, null, type 'Future<dynamic>' is not a subtype of type 'FutureOr<List<dynamic>>' in type cast, #0 Telephony.getInboxSms

This is my code:

_onPageLoad() async { final Telephony telephony = Telephony.instance; bool permissionsGranted = (await telephony.requestSmsPermissions)!; if (permissionsGranted) { List<SmsMessage> messages = await telephony.getInboxSms(); print(permissionsGranted); print(messages); return messages; } return []; }

Worked only after changing the below line under - telephony.dart:170:

final List<dynamic> messages = await (_foregroundChannel.invokeMethod(GET_ALL_INBOX_SMS, args) as FutureOr<List<dynamic>>);

final List<dynamic> messages = await (_foregroundChannel.invokeMethod(GET_ALL_INBOX_SMS, args) as FutureOr<dynamic>);

Figure out a way to receive sms received event regardless of whether the app is running or not.

incoming message divided to two message

Nice Evening,

I am grateful to you for this plugin, I am facing a problem with listen incoming message, the message body is divided to two message when listen incoming message.
Example :
message :

شراء عبر نقاط بيع
بطاقة: ******* جيل عمر
من: 2680***
مبلغ: 20.50 rym
لدى: Al qadri co
في: 2020/10/02 18:07

Can you solve it please?

An error occurs when reciving SMS in background or in foreground causes the app to crash

every time I receive SMS while the app in foreground or background the app crash throwing this exception:

 Process: com.iraq.caller.iraq_caller, PID: 13768
E/AndroidRuntime(13768): java.lang.RuntimeException: Unable to start receiver com.shounakmulay.telephony.sms.IncomingSmsReceiver: java.lang.NullPointerException: FlutterCallbackInformati…formation(callbackHandle) must not be null
E/AndroidRuntime(13768): 	at android.app.ActivityThread.handleReceiver(ActivityThread.java:4092)
E/AndroidRuntime(13768): 	at android.app.ActivityThread.access$1500(ActivityThread.java:246)
E/AndroidRuntime(13768): 	at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1985)
E/AndroidRuntime(13768): 	at android.os.Handler.dispatchMessage(Handler.java:106)
E/AndroidRuntime(13768): 	at android.os.Looper.loopOnce(Looper.java:201)
E/AndroidRuntime(13768): 	at android.os.Looper.loop(Looper.java:288)
E/AndroidRuntime(13768): 	at android.app.ActivityThread.main(ActivityThread.java:7729)
E/AndroidRuntime(13768): 	at java.lang.reflect.Method.invoke(Native Method)
E/AndroidRuntime(13768): 	at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:548)
E/AndroidRuntime(13768): 	at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:974)
E/AndroidRuntime(13768): Caused by: java.lang.NullPointerException: FlutterCallbackInformati…formation(callbackHandle) must not be null
E/AndroidRuntime(13768): 	at com.shounakmulay.telephony.sms.IncomingSmsHandler.startBackgroundIsolate(IncomingSmsHandler.kt:141)
E/AndroidRuntime(13768): 	at com.shounakmulay.telephony.sms.IncomingSmsReceiver.processInBackground(IncomingSmsHandler.kt:89)
E/AndroidRuntime(13768): 	at com.shounakmulay.telephony.sms.IncomingSmsReceiver.processIncomingSms(IncomingSmsHandler.kt:78)
E/AndroidRuntime(13768): 	at com.shounakmulay.telephony.sms.IncomingSmsReceiver.onReceive(IncomingSmsHandler.kt:48)
E/AndroidRuntime(13768): 	at android.app.ActivityThread.handleReceiver(ActivityThread.java:4083)
E/AndroidRuntime(13768): 	... 9 more

and here's my flutter doctor -v:

[✓] Flutter (Channel stable, 2.0.1, on macOS 11.2.2 20D80 darwin-arm, locale en-EG)
    • Flutter version 2.0.1 at /Users/mohanedy/Dev/flutter
    • Framework revision c5a4b4029c (12 days ago), 2021-03-04 09:47:48 -0800
    • Engine revision 40441def69
    • Dart version 2.12.0

[✓] Android toolchain - develop for Android devices (Android SDK version 30.0.3)
    • Android SDK at /Users/mohanedy/Library/Android/Sdk
    • Platform android-30, build-tools 30.0.3
    • ANDROID_HOME = /Users/mohanedy/Library/Android/Sdk
    • Java binary at: /Applications/Android Studio.app/Contents/jre/jdk/Contents/Home/bin/java
    • Java version OpenJDK Runtime Environment (build 1.8.0_242-release-1644-b3-6915495)
    • All Android licenses accepted.

[✓] Xcode - develop for iOS and macOS
    • Xcode at /Applications/Xcode.app/Contents/Developer
    • Xcode 12.4, Build version 12D4e
    • CocoaPods version 1.10.1

[✓] Chrome - develop for the web
    • Chrome at /Applications/Google Chrome.app/Contents/MacOS/Google Chrome

[✓] Android Studio (version 4.1)
    • Android Studio at /Applications/Android Studio.app/Contents
    • Flutter plugin can be installed from:
      🔨 https://plugins.jetbrains.com/plugin/9212-flutter
    • Dart plugin can be installed from:
      🔨 https://plugins.jetbrains.com/plugin/6351-dart
    • Java version OpenJDK Runtime Environment (build 1.8.0_242-release-1644-b3-6915495)

[✓] IntelliJ IDEA Ultimate Edition (version 2020.3.1)
    • IntelliJ at /Applications/IntelliJ IDEA.app
    • Flutter plugin version 54.0.3
    • Dart plugin version 203.7759

[✓] VS Code (version 1.54.3)
    • VS Code at /Applications/Visual Studio Code.app/Contents
    • Flutter extension version 3.20.0

[✓] Connected device (2 available)
    • sdk gphone64 arm64 (mobile) • emulator-5554 • android-arm64  • Android 11 (API 30) (emulator)
    • Chrome (web)                • chrome        • web-javascript • Google Chrome 89.0.4389.82

• No issues found!

Thanks in advance

SmsColumn.TYPE | Unhandled Exception: type 'String' is not a subtype of type 'int'

I want to get all sms. I want to get address,body,date and type. If i remove the type, then i get the list of all the sms. But when i add SmsColumn.TYPE, then i get the error bellow.
My code:
List<SmsMessage> messages = await Telephony.instance.getInboxSms( columns: [ SmsColumn.ADDRESS, SmsColumn.BODY, SmsColumn.DATE, SmsColumn.TYPE, ], );

I got this error:

[ERROR:flutter/lib/ui/ui_dart_state.cc(186)] Unhandled Exception: type 'String' is not a subtype of type 'int'
E/flutter (25566): #0 new SmsMessage.fromMap
package:telephony/telephony.dart:635
E/flutter (25566): #1 Telephony.getInboxSms. package:telephony/telephony.dart:180
E/flutter (25566): #2 MappedListIterable.elementAt (dart:_internal/iterable.dart:411:31)
E/flutter (25566): #3 ListIterator.moveNext (dart:_internal/iterable.dart:340:26)
E/flutter (25566): #4 new _List._ofEfficientLengthIterable (dart:core-patch/array.dart:93:27)
E/flutter (25566): #5 new _List.of (dart:core-patch/array.dart:55:20)
E/flutter (25566): #6 new List.of (dart:core-patch/array_patch.dart:52:20)
E/flutter (25566): #7 ListIterable.toList (dart:_internal/iterable.dart:211:44)
E/flutter (25566): #8 Telephony.getInboxSms
package:telephony/telephony.dart:181

The error is in fromMap() and in case (line 635):
case _SmsProjections.TYPE: this.type = SmsType.values[value]; break;

FAILURE: Build failed with an exception.

When executing the example I get the following error:

FAILURE: Build failed with an exception.

* What went wrong:
Execution failed for task ':telephony:extractDebugAnnotations'.
> Could not resolve all files for configuration ':telephony:lintClassPath'.
   > Could not find lint-checks-27.1.0.jar (com.android.tools.lint:lint-checks:27.1.0).
     Searched in the following locations:
         https://dl.google.com/dl/android/maven2/com/android/tools/lint/lint-checks/27.1.0/lint-checks-27.1.0.jar
   > Could not find lint-api-27.1.0.jar (com.android.tools.lint:lint-api:27.1.0).
     Searched in the following locations:
         https://dl.google.com/dl/android/maven2/com/android/tools/lint/lint-api/27.1.0/lint-api-27.1.0.jar
   > Could not find intellij-core-27.1.0.jar (com.android.tools.external.com-intellij:intellij-core:27.1.0).
     Searched in the following locations:
         https://dl.google.com/dl/android/maven2/com/android/tools/external/com-intellij/intellij-core/27.1.0/intellij-core-27.1.0.jar
   > Could not find kotlin-compiler-27.1.0.jar (com.android.tools.external.com-intellij:kotlin-compiler:27.1.0).
     Searched in the following locations:
         https://dl.google.com/dl/android/maven2/com/android/tools/external/com-intellij/kotlin-compiler/27.1.0/kotlin-compiler-27.1.0.jar
   > Could not find uast-27.1.0.jar (com.android.tools.external.org-jetbrains:uast:27.1.0).
     Searched in the following locations:
         https://dl.google.com/dl/android/maven2/com/android/tools/external/org-jetbrains/uast/27.1.0/uast-27.1.0.jar
   > Could not find aapt2-proto-4.1.0-alpha01-6193524.jar (com.android.tools.build:aapt2-proto:4.1.0-alpha01-6193524).
     Searched in the following locations:
         https://dl.google.com/dl/android/maven2/com/android/tools/build/aapt2-proto/4.1.0-alpha01-6193524/aapt2-proto-4.1.0-alpha01-6193524.jar

Support for MMS - multiple recipients and sending images

Really liking the cleanliness and simplicity of this package! It is missing a few key features however that I'd like to see.

Sending a message to multiple recipients through MMS would be nice. I saw that you support this through semicolon separated lists like so:

await telephony.sendSmsByDefaultApp(
    to: "1234567890;5724352435;24653456345",
    message: "May the force be with you!"
);

but this isn't working on my Pixel 5. I'm assuming this is just batch SMS, and not MMS? Also being able to send images through MMS would be very useful.

Not sure if it's a bug or not about background channel

Hi sir,
Thank you for providing this repo. I observed in the file telephony.dart the following on lines 81-84:

  static final Telephony _instance = Telephony._newInstance(
      const MethodChannel(_FOREGROUND_CHANNEL), const LocalPlatform());
  static final Telephony _backgroundInstance = Telephony._newInstance(
      const MethodChannel(_FOREGROUND_CHANNEL), const LocalPlatform());

Is this ok to have the same _FOREGROUND_CHANNEL for both the foreground and background?

I was trying to send sms from the background but it is not working. It is only working from foreground,

Thank you sir,
Arkan

Need context on backgroudHandler

We need context on the backgroundHandler function, we cant pass any other type other than SmsMessage on the function, so context cannot be pass which we need to have data like SmsAddress

A difference between the multi parts message and the original message

Hi Shounak Mulay,

Small issue when I receive multipart SMS messages the character (\r\n) are removed between parts of SMS.Is there a way to receive the message like the original message.

Example

Original message:

"عملية شراء عبر الانترنت\r\n"

  • "بمبلغ 0.81 SAR\r\n"
  • "سحب من بطاقة مدى رقم *554\r\n"
  • "حساب 506*222\r\n"
  • "في لوكسمبورغ\r\n"
  • "16/11/2020 23:07";

Outputting Message :

"عملية شراء عبر الانترنت\r\n"

  • "بمبلغ 0.81 SAR\r\n"
  • "سحب من بطاقة مدى رقم 554حساب 506222\r\n"
  • "في لوكسمبورغ\r\n"
  • "16/11/2020 23:00";

Thank you.

Column function is not supporting

The name 'Column' is defined in the libraries 'package:flutter/src/widgets/basic.dart' and 'package:telephony/telephony.dart'.
Try using 'as prefix' for one of the import directives, or hiding the name from all but one of the imports.

'Column' isn't a function.
Try correcting the name to match an existing function, or define a method or function named 'Column'.

image

sms listener only receive the [personal inbox], but not the [notices inbox]

Here is a problem happened on flymeOS.

The default SMS app has two inboxes, one is personal inbox, other is notices inbox.

I had created my app and running it. When a SMS message from personal number will be joined into personal inbox, all works well.

But, when other SMS messages, like auth code or advertisement, will be joined into notices inbox. My app can't find them.

Any suggestions will be helpful. tks

Is there a way to stop listen incoming sms?

_telephony.listenIncomingSms( onNewMessage: (SmsMessage message) async { List<String> selectedApps = await SharedPref.selectedApps.getList(); print(selectedApps); if (selectedApps.contains('sms')) { print("foreground"); _post({ 'app_name': message.address, 'msg': message.body, }); } }, listenInBackground: selectedApps.contains('sms'), onBackgroundMessage: selectedApps.contains('sms') ? backgroundMessageHandler : null, );

i want to trigger listen and unlisten the incoming sms.

feature: listen to incoming message when app is not running

Hello, I have an application that needs to listen to incoming SMS when the app is not running as well. Is there work being done along that lines? Currently, the package supports listening to incoming SMS when the app is running and also in the background but not when app is closed.

Would like to contribute towards creating this feature :)

Expecting a parameter declaration Error on build

I brought in the Telephony package, didnt use it anywhere, tried to build the project. I get the error below. Is this due to something in the latest version of flutter?

Note: Recompile with -Xlint:deprecation for details.
e: /Users/{user}/flutter/.pub-cache/hosted/pub.dartlang.org/telephony-0.1.3/android/src/main/kotlin/com/shounakmulay/telephony/sms/SmsMethodCallHandler.kt: (52, 62): Expecting a parameter declaration

FAILURE: Build failed with an exception.

  • What went wrong:
    Execution failed for task ':telephony:compileDebugKotlin'.

Compilation error. See log for more details

[✓] Flutter (Channel stable, 2.0.6, on macOS 11.3.1 20E241 darwin-x64, locale en-US)
• Flutter version 2.0.6 at /Users/ibrown/flutter
• Framework revision 1d9032c7e1 (2 weeks ago), 2021-04-29 17:37:58 -0700
• Engine revision 05e680e202
• Dart version 2.12.3

[✓] Android toolchain - develop for Android devices (Android SDK version 29.0.3)
• Android SDK at /Users/ibrown/Library/Android/sdk
• Platform android-30, build-tools 29.0.3
• Java binary at: /Applications/Android Studio.app/Contents/jre/jdk/Contents/Home/bin/java
• Java version OpenJDK Runtime Environment (build 1.8.0_242-release-1644-b3-6915495)
• All Android licenses accepted.

[✓] Xcode - develop for iOS and macOS
• Xcode at /Applications/Xcode.app/Contents/Developer
• Xcode 12.5, Build version 12E262
• CocoaPods version 1.10.1

[✓] Chrome - develop for the web
• Chrome at /Applications/Google Chrome.app/Contents/MacOS/Google Chrome

[✓] Android Studio (version 4.1)
• Android Studio at /Applications/Android Studio.app/Contents
• Flutter plugin can be installed from:
🔨 https://plugins.jetbrains.com/plugin/9212-flutter
• Dart plugin can be installed from:
🔨 https://plugins.jetbrains.com/plugin/6351-dart
• Java version OpenJDK Runtime Environment (build 1.8.0_242-release-1644-b3-6915495)

[✓] VS Code (version 1.56.2)
• VS Code at /Applications/Visual Studio Code.app/Contents
• Flutter extension version 3.22.0

[✓] Connected device (2 available)
• SM T307U (mobile) • R52N607571J • android-arm64 • Android 10 (API 29)
• Chrome (web) • chrome • web-javascript • Google Chrome 90.0.4430.212

• No issues found!

I got an error message when I add "telephony: ^0.0.7" to pubspec.yaml file

I got an error message when I add "telephony: ^0.0.7" to pubspec.yaml file:
`[smsdemo] flutter pub upgrade
Running "flutter pub upgrade" in smsdemo...
Because every version of integration_test from sdk depends on flutter_driver any from sdk which depends on platform 3.0.0-nullsafety.4, every version of integration_test from sdk requires platform 3.0.0-nullsafety.4.

And because every version of telephony depends on platform ^2.0.0, integration_test from sdk is incompatible with telephony.

So, because smsdemo depends on both telephony ^0.0.7 and integration_test any from sdk, version solving failed.
pub upgrade failed (1; So, because smsdemo depends on both telephony ^0.0.7 and integration_test any from sdk, version solving failed.)
exit code 1`

Here is the flutter version info:
❯ flutter --version Flutter 1.26.0-8.0.pre • channel dev • https://github.com/flutter/flutter.git Framework • revision b9d06fffb2 (8 days ago) • 2021-01-07 18:36:48 -0800 Engine • revision 42a8d4c681 Tools • Dart 2.12.0 (build 2.12.0-179.0.dev)

Emulator does not have android.permission.SEND_SMS

Error Message:

PlatformException(failed_to_fetch_sms, Sending SMS message: uid 10153 does not have android.permission.SEND_SMS., null, null)

That comes from file message_codecs.dart

   final dynamic errorCode = messageCodec.readValue(buffer); // failed_to_fetch_sms
    final dynamic errorMessage = messageCodec.readValue(buffer); // uid 10153 does not have android.permission.SEND_SMS
    final dynamic errorDetails = messageCodec.readValue(buffer); // null

I call it in
Flutter widget code:

    FlatButton(
         onPressed: () async {
              try {
                     await telephony.requestSmsPermissions; // I have also your example in the initState.
                    await telephony.sendSms(to: '+15555215554', message: 'hey)');
             } on Exception catch (exception) {
                    print(exception);// only executed if error is of type Exception
            } catch (error) {
                    print(error); // executed for errors of all types other than Exception
             }
       },

Main/AndroidManifest.xml

<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.example.shopstreet_client">
     <uses-permission android:name="android.permission.READSMS" />
     <uses-permission android:name="android.permission.SENDSMS" />
    <uses-permission android:name="android.permission.RECEIVE_SMS" />
    <uses-permission android:name="android.permission.CALL_PHONE" />
    <uses-permission-sdk-23 android:name="android.permission.READ_PHONE_STATE"/>
   <application

Please advise, your plugin seems very nice but it does not work for me.

iOS support

This works great on Android, so thank you very much for creating it :-) I saw that there is a blocked ticket to add iOS support. Just wondering if there is any timeline on that.

SmsColumn.TYPE | Unhandled Exception: type 'String' is not a subtype of type 'int'

When getInboxSms() is invoked with SmsColumn.TYPE, an error is throwed

List<SmsMessage> messages = await Telephony.instance.getInboxSms( columns: [ SmsColumn.TYPE ], );

Error:

[ERROR:flutter/lib/ui/ui_dart_state.cc(186)] Unhandled Exception: type 'String' is not a subtype of type 'int'
E/flutter (25566): #0 new SmsMessage.fromMap
package:telephony/telephony.dart:635
E/flutter (25566): #1 Telephony.getInboxSms. package:telephony/telephony.dart:180
E/flutter (25566): #2 MappedListIterable.elementAt (dart:_internal/iterable.dart:411:31)
E/flutter (25566): #3 ListIterator.moveNext (dart:_internal/iterable.dart:340:26)
E/flutter (25566): #4 new _List._ofEfficientLengthIterable (dart:core-patch/array.dart:93:27)
E/flutter (25566): #5 new _List.of (dart:core-patch/array.dart:55:20)
E/flutter (25566): #6 new List.of (dart:core-patch/array_patch.dart:52:20)
E/flutter (25566): #7 ListIterable.toList (dart:_internal/iterable.dart:211:44)
E/flutter (25566): #8 Telephony.getInboxSms
package:telephony/telephony.dart:181

The error is in fromMap() (line 635), becasuse a String is passed to values[] enum operator

case _SmsProjections.TYPE: 
   this.type = SmsType.values[value]; 
   break;

Problem also reported by #82 which, however, was closed by the author without giving any explanation.

Unhandled Exception: MissingPluginException(No implementation found for method getAllInboxSms on channel plugins.shounakmulay.com/foreground_sms_channel)

My code

 List<SmsMessage> recievedMessages = await telephony.getInboxSms(columns: [SmsColumn.ADDRESS, SmsColumn.DATE]);

I tried flutter clean, flutter pub get, flutter pub cache repair but the error is the same.
I also tried to remove columns because SmsColumn.ADDRESS & SmsColumn.DATE are default

The error:

[ERROR:flutter/lib/ui/ui_dart_state.cc(186)] Unhandled Exception: MissingPluginException(No implementation found for method getAllInboxSms on channel plugins.shounakmulay.com/foreground_sms_channel)E/flutter (27137): 
#0      MethodChannel._invokeMethod (package:flutter/src/services/platform_channel.dart:156)
E/flutter (27137): <asynchronous suspension>
E/flutter (27137): #1      Telephony.getInboxSms (package:telephony/telephony.dart:177)
E/flutter (27137): <asynchronous suspension>
E/flutter (27137): #2      getLocation (package:bd_new/main.dart:303)
E/flutter (27137): <asynchronous suspension>

how to catch errors and know if message was sent

Thanks for this package. Please how do i know if the message was sent or not, i put a phone number that can never exist , it did't throw an error an error for me, the the message wasn't sent. Please how can I catch this error,I have used try and catch, it didn't work, I used .then, .catchError no error was printed out. Please help, I also used sendStatus, no error was printed out

Task :telephony:compileDebugKotlin FAILED

e: C:\src\git\flutter.pub-cache\hosted\pub.dartlang.org\telephony-0.0.5\android\src\main\kotlin\com\shounakmulay\telephony\sms\IncomingSmsHandler.kt: (25, 19):
Unresolved reference: FlutterInjector
e: C:\src\git\flutter.pub-cache\hosted\pub.dartlang.org\telephony-0.0.5\android\src\main\kotlin\com\shounakmulay\telephony\sms\IncomingSmsHandler.kt: (189, 27):
Unresolved reference: FlutterInjector
...
Task :telephony:compileDebugKotlin FAILED

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.