I am coding an alarm on my own and I would like that the alarm would wake up the phone and show the Alert Dialog. Can someone give me some insight on how to do this please?
You can use android_alarm_maganer to achive what you need. Simply run it every second or so and check if DateTime.now() meets your criteria.
Example:
import 'package:android_alarm_manager/android_alarm_manager.dart';
void checkAlarms() {
if(DateTime().now == alarm){
//Do something
}
}
main() async {
final int helloAlarmID = 0;
await AndroidAlarmManager.initialize();
runApp(...);
await AndroidAlarmManager.periodic(const Duration(seconds: 1), helloAlarmID, checkAlarms);
}
Then you can run another Activity as described here
Related
I am developing an app in flutter. I used awesome_notification package to show notifications. In awesome_notification, onActionReceivedMethod works fine when an app is in the foreground but does not work when an app is in the background. How to handle this?
#pragma("vm:entry-point")
static Future <void> onActionReceivedMethod(ReceivedAction receivedAction) async {
// code to navigate some page
} // not calling when user tap notification
Also, onMessageOpenedApp function is not triggered when tapping the notification. How to solve this? Kindly help me to resolve this.
FirebaseMessaging.onMessageOpenedApp.listen((message) async {
// code to navigate some page
}); // not calling when user tap notification
I encountered the same problem with local_notification, to pass an information from the vm entry point to the app.
I solved it by doing an isolate sent / receive like this:
//needed for isolate
import 'dart:isolate';
import 'dart:ui';
//outside main
const String channel = 'channel_key';
#pragma('vm:entry-point')
void onReceiveBackgroundResponse(NotificationResponse notificationResponse) async {
final sendPort = IsolateNameServer.lookupPortByName(channel);
sendPort?.send(notificationResponse.actionId);
}
...
//inside main
void listenNotification() {
final receivePort = ReceivePort();
IsolateNameServer.registerPortWithName(receivePort.sendPort, channel);
receivePort.asBroadcastStream().listen((event) {
print(event);
});
}
I'm trying to make my app fetch data from API every 5 seconds without refreshing the page every time.
How can I achieve it ?
For whoever is facing this error , I fixed it like this.
Timer? t;
#override
void initState() {
super.initState();
t = new Timer.periodic(timeDelay, (t) => fetchDocuments());
}
#override
void dispose() {
t?.cancel();
super.dispose();
}
This is a simple timer that runs every a HTTP lookup every 5 seconds.
import 'package:http/http.dart' as http;
import "dart:async";
void main() {
var timer = Timer.periodic(const Duration(seconds: 5), (_) async {
var album = await fetchAlbum();
print(album.body);
//Update page with data here
});
}
Future<http.Response> fetchAlbum() {
return http.get(Uri.parse('https://jsonplaceholder.typicode.com/albums/1'));
}
I have included a basic HTTP lookup from here: https://docs.flutter.dev/cookbook/networking/fetch-data
Without knowing more about your app I can't give anymore information.
I need to know how to make this stopwatch, which after 48 hours disables a widget, which in my case is a button. Can someone explain to me how to do it? What classes to use?
I tried to use this, but don't works:
var timer = Timer(Duration(seconds: 1), () => print('done'));
it seems to me that you want this button to be disabled after 2 days of the app that was installed, you need persist the date on the device so that after app-restarts the date will be itself, you need to use a package the persists the data on the device. i recommend shared_preference which is easy to use.
for your case, in the screen where you use the button you need to do this
import 'package:shared_preferences/shared_preferences.dart';
class MyFirstStatefullScreen extends StatefullWidget {
MyFirstStatefullScreenState createState() => MyFirstStatefullScreenState();
}
class MyFirstStatefullScreenState extends State<MyFirstStatefullScreen>{
// some other code that u wrote
bool shouldButtonBeActive = true;
#override
void initState() {
Future.delayed(Duration(0))
.then((_) {
SharedPreferences sharedPrefs= await SharedPreferences.getInstance();
final deadLine = sharedPrefs.getString('deadLine');
if(deadLine == null) {
// this is the first time the app has been installed on the device
// so we need to set the deadLine to N number of days after the installation
final deadLineDate = DateTime.now().add(Duration(days: 2)); // 2 days from the date that the app was installed;
sharedPrefs.setString(deadLineDate.toIso8601String()); // set it so we can check on the successfull state
return;
}
final deadLineDate = DateTime.parse(deadLine); // since we stored it as a string;
/// the deadline is set and is not null
if(DateTime.now().compareTo(deadLineDate) == 0) {
we are successfull, N hours have passed since the intial instalation, now we can disable the button
shouldButtonBeActive = false; // the button should be disabled
}
})
}
Widget build(context) {
// in your UI where you use the button
MaterialButton(
child: Text("Button"),
onPressed: shouldButtonBeActive ? func() : null
)
}
}
PS: we are using the Future inside the initState, because initState dose not allow async ( api calls, storage access) in it.
I am trying to make a simple stopwatch application and I have so far implemented a stopwatch that is working while the app is running, but I want the stopwatch to continue to work while the application is closed and then resume while I open the app again. A similar app that I can compare to is RunKeeper which tracks the time of your running activities.
Is there any simple plugins that I can use to resolve my issue or is it more complicated than that?
So far I have tried using workmanager(flutter plugin) but with workmanager I could only track background activities at a given time, not the entire time the stopwatch is active, which I want in my case.
I created a stopwatch by using a Stream that returns the time with the help of Timer.periodic(). If you quit to home screen of the phone the Stream keeps running in the background.
Stream<int> stopWatchStream() {
StreamController<int> streamController;
Timer timer;
int counter = 0;
void stopTimer() {
if (timer != null) {
timer.cancel();
timer = null;
counter = 0;
streamController.close();
}
}
void tick(_) {
counter++;
streamController.add(counter);
}
void startTimer() {
timer = Timer.periodic(Duration(milliseconds: 10), tick);
}
streamController = StreamController<int>(
onListen: startTimer,
onCancel: stopTimer,
onResume: startTimer,
onPause: stopTimer,
);
return streamController.stream;
}
How can you create a scheduled service in Flutter, which will be triggered at a specific time every day, and it will run some code? It needs to work for both Android and IOS and even if the app is terminated.
You could make use of the alarm manager package.
A simple implementation of the same would look like below.
import 'dart:async';
import 'package:android_alarm_manager/android_alarm_manager.dart';
import 'package:flutter/widgets.dart';
void doStuff() {
print("do stuff every minute");
}
Future<void> main() async {
final int periodicID = 0;
// Start the AlarmManager service.
await AndroidAlarmManager.initialize();
runApp(const Center(
child:
Text('See device log for output', textDirection: TextDirection.ltr)));
await AndroidAlarmManager.periodic(
const Duration(minutes: 1), periodicID, doStuff,
wakeup: true);
}