Flutter and native android method in alarm manager callback function

141 views
Skip to first unread message

Aleš Benčina

unread,
Jun 22, 2020, 8:58:32 AM6/22/20
to Flutter Development (flutter-dev)

I am having an issue calling background function which is written for android specific. 

My use case - press on the button, schedule the SMS (with alarm manager), call callback function, and send SMS.


I'm feeling stuck a bit so I hope someone can show me what can I do to make it right. Also if I put await platform.invokeMethod('sendsms') on button press, the method fires. So I am doing something wrong when trying to fire the method in the backend.


Here is also a gist with all files: https://gist.github.com/benzo11/901c1885fff46e37d954a139dbbf0470


Thank you in advance!


 // In the widget state class
 Future<void> _sendSms() async {
    await AndroidAlarmManager.oneShotAt(
      DateTime.now().add(const Duration(seconds: 1)),
      1,
      printHello, // callback function which triggers
      alarmClock: true,
    );
  }

// Top level 
  void printHello() async {
    final DateTime now = DateTime.now();
    final int isolateId = Isolate.current.hashCode;
    print("[$now] Hello, world! isolate=${isolateId} function='$printHello'");

    // Method undefined in isolate
    var result = await platform.invokeMethod('sendsms').then((res) {
      print(res);
    });
  }

public class MainActivity extends FlutterActivity {
    public static final String TAG = "AlarmExampleMainActivity";
    private static final String CHANNEL = "samples.flutter.dev/battery";

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        AndroidAlarmManagerPlugin
                .registerWith(registrarFor("io.flutter.plugins.androidalarmmanager.AndroidAlarmManagerPlugin"));
    }

    @Override
    public void configureFlutterEngine(@NonNull FlutterEngine flutterEngine) {
        super.configureFlutterEngine(flutterEngine);
        new MethodChannel(flutterEngine.getDartExecutor().getBinaryMessenger(), CHANNEL)
                .setMethodCallHandler((call, result) -> {
                    // Note: this method is invoked on the main thread.
                    if (call.method.equals("sendsms")) {
                        String rez = sendSMS();
                        result.success(rez);
                    } else {
                        result.notImplemented();
                    }
                });
    }

    private String sendSMS() {
        String phoneNo = "009981111";
        String msg = "Message body";

        SmsManager smsManager = SmsManager.getDefault();
        smsManager.sendTextMessage(phoneNo, null, msg, null, null);

        return "Sent";
    }
}
Reply all
Reply to author
Forward
0 new messages