Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Background Services But not working in background( It will not work when you complete remove the app from task manager.). Only Work When you have Pause mode/application was still alive Mode. #3

Open
teamrahul opened this issue Dec 31, 2024 · 13 comments
Labels
bug Something isn't working

Comments

@teamrahul
Copy link

teamrahul commented Dec 31, 2024

Is it work for
flutter_background_service: ^5.1.0
flutter_local_notifications: ^18.0.1
flutter_background_messenger: ^0.0.2

Background Service in android??.

import 'dart:async';
import 'dart:io';
import 'dart:ui';
import 'package:flutter/material.dart';
import 'package:flutter_background_service/flutter_background_service.dart';
import 'package:flutter_local_notifications/flutter_local_notifications.dart';
import 'package:sms_background/bgservice/bg_service.dart';

import '../utils/color.dart'; // Custom colors or just use default

// Initialize the background service

Future initializeService() async {
final service = FlutterBackgroundService();

const AndroidNotificationChannel channel = AndroidNotificationChannel(
'my_foreground', // id
'MY FOREGROUND SERVICE', // title
description: 'This channel is used for important notifications.',
importance: Importance.low,
enableVibration: false,
enableLights: true,
ledColor: primary, // Customize if needed
);

final FlutterLocalNotificationsPlugin flutterLocalNotificationsPlugin =
FlutterLocalNotificationsPlugin();

if (Platform.isIOS || Platform.isAndroid) {
await flutterLocalNotificationsPlugin.initialize(
const InitializationSettings(
iOS: DarwinInitializationSettings(),
android: AndroidInitializationSettings('@mipmap/ic_launcher'),
),
);
}

await flutterLocalNotificationsPlugin
.resolvePlatformSpecificImplementation<
AndroidFlutterLocalNotificationsPlugin>()
?.createNotificationChannel(channel);

await service.configure(
androidConfiguration: AndroidConfiguration(
onStart: onStart,
autoStart: true,
isForegroundMode: true,
notificationChannelId: 'my_foreground',
initialNotificationTitle: 'Service Running',
initialNotificationContent: 'Sending SMS...',
foregroundServiceNotificationId: 888,
foregroundServiceTypes: [AndroidForegroundType.dataSync],
),
iosConfiguration: IosConfiguration(
autoStart: true,
onForeground: onStart,
onBackground: onIosBackground,
),
);
}

@pragma('vm:entry-point')
Future onIosBackground(ServiceInstance service) async {
WidgetsFlutterBinding.ensureInitialized();
DartPluginRegistrant.ensureInitialized();
return true;
}

@pragma('vm:entry-point')
void onStart(ServiceInstance service) async {
DartPluginRegistrant.ensureInitialized();
final FlutterLocalNotificationsPlugin flutterLocalNotificationsPlugin =
FlutterLocalNotificationsPlugin();

if (service is AndroidServiceInstance) {
service.on('setAsForeground').listen((event) {
service.setAsForegroundService();
});

service.on('setAsBackground').listen((event) {
  service.setAsBackgroundService();
});

}

service.on('stopService').listen((event) {
service.stopSelf();
});

// Listen for data from the main isolate
service.on('data').listen((event) async {
if (event != null && event['recipients'] != null) {
String message = event['message']??'';
List recipients = List.from(event['recipients']);
debugPrint('Received recipients in background service: ${recipients.length}');
//if (recipients.isNotEmpty) {
await sendBulkSMSWithProgress(recipients, message, flutterLocalNotificationsPlugin, service);
//}
}
});
}

Future sendBulkSMSWithProgress(
List recipients,
String message,
FlutterLocalNotificationsPlugin flutterLocalNotificationsPlugin,
ServiceInstance service) async {
int batchSize = 100; // Send 100 messages at a time
int totalSent = 0;
int totalFailed = 0;

// Show a notification for SMS sending progress
flutterLocalNotificationsPlugin.show(
888,
'Sending SMS',
'Sending in progress...',
const NotificationDetails(
android: AndroidNotificationDetails(
'SMS',
'Data Sync',
icon: '@drawable/ic_sms_notify',
ongoing: true,
),
),
);

MessagingExample mMessagingExample = MessagingExample();
List smsList = ['+91xxxxxxxxxx','+9xxxxxxxxxx','+91xxxxxxxxxx','+91xxxxxxxxxx','+91xxxxxxxxxx'];
for(int i=0;i<smsList.length;i++){
bool isSms = await mMessagingExample.sendSMS(smsList[i],message);
String title = isSms == true?'Success: ${smsList[i]}':'Failed ${smsList[i]}';

if(isSms){
  totalSent += (i+1);
}else{
  totalFailed += (i+1);
}

// Update progress notification after each batch
flutterLocalNotificationsPlugin.show(
  888,
  title,
  'Sent $totalSent messages, failed $totalFailed',
  const NotificationDetails(
    android: AndroidNotificationDetails(
      'SMS',
      'Data Sync',
      icon: '@drawable/ic_sms_notify',
      ongoing: true,
    ),
  ),
);

// Delay between batches to avoid overwhelming the system
await Future.delayed(Duration(seconds: 40));

}

// Notify user when done
flutterLocalNotificationsPlugin.show(
888,
'SMS Sent',
'Successfully sent $totalSent messages!',
const NotificationDetails(
android: AndroidNotificationDetails(
'SMS',
'Data Sync',
icon: '@drawable/ic_sms_notify',
ongoing: false,
),
),
);

service.stopSelf(); // Stop the service after the task is complete
}


import 'package:flutter/cupertino.dart';
import 'package:flutter_background_messenger/flutter_background_messenger.dart';

class MessagingExample {

final messenger = FlutterBackgroundMessenger();

Future sendSMS(String mobileNumber,String message) async {
try {
final success = await messenger.sendSMS(
phoneNumber: mobileNumber,
message: message,
);

  if (success) {
    debugPrint('SMS sent successfully');
    return true;
  } else {
    debugPrint('Failed to send SMS');
    return false;
  }
} catch (e) {
  debugPrint('Error sending SMS: $e');
  return false;
}

}
}

Check the above sample

@P-yiush07
Copy link
Owner

P-yiush07 commented Dec 31, 2024

WELL IT SHOULD WORK, give it a try

@teamrahul
Copy link
Author

WELL IT SHOULD WORK, give it a try

I will try 'Failed to send SMS'.
Inside the background service.

@P-yiush07
Copy link
Owner

can you properly mention your code ?

@teamrahul
Copy link
Author

can you properly mention your code ?

Yes, you can check code
Yes, Check the above sample

@P-yiush07
Copy link
Owner

Check if SMS permissions are granted in the app settings.

also check for permission in android xml file

and Try sending to a single number first to isolate any issues.

@teamrahul
Copy link
Author

teamrahul commented Dec 31, 2024

Can you share sample.
Background Service.
Closed the app/Close the app from task manager, after that sent SMS in background. I have 10 numbers. To send SMS all 10 numbers one by one.

@P-yiush07
Copy link
Owner

In the code i can see you're using delay
await Future.delayed(Duration(seconds: 40));

and in the current version of the code, the message will be sent only if the application remains in background (task manager). It will not work when you complete remove the app from task manager.

You can try sending the message by keeping the app in foreground
thanks

@teamrahul
Copy link
Author

e any issues.

Yes.
Thank for your guidance. But your work was absolutely goods. No doubt.
Try this/update your package, 'complete remove the app from task manager'. to sending sms.

@P-yiush07
Copy link
Owner

P-yiush07 commented Dec 31, 2024

is it working when you're not closing the app (not removing from the task manager) ?

@teamrahul
Copy link
Author

is it working when you're not closing the app (not removing from the task manager) ?

### yes working without adding background service code.
Otherwise create confusion flutter_background_messenger: ^0.0.2. This background messaging service. But actually not background.....

Look
import 'package:flutter/cupertino.dart';
import 'package:flutter_background_messenger/flutter_background_messenger.dart';

class MessagingExample {

final messenger = FlutterBackgroundMessenger();

Future sendSMS(String mobileNumber,String message) async {
try {
final success = await messenger.sendSMS(
phoneNumber: mobileNumber,
message: message,
);

  if (success) {
    debugPrint('SMS sent successfully');
    return true;
  } else {
    debugPrint('Failed to send SMS');
    return false;
  }
} catch (e) {
  debugPrint('Error sending SMS: $e');
  return false;
}

}
}


Click Event to send SMS
if (await requestPermissions()) {
MessagingExample mMessagingExample = MessagingExample();
List smsList = []; //Add phone Number 10,20,30 etc.
for(int i=0;i<smsList.length;i++){
bool isSms = await mMessagingExample.sendSMS(smsList[i],'Testing Message Kindly Ignore');

    // Delay between batches to avoid overwhelming the system
    await Future.delayed(Duration(seconds: 40));
  }
}else{
  Fluttertoast.showToast(msg: 'Kindly as to permission');
}

@teamrahul teamrahul changed the title Background Services Background Services But not working in background( It will not work when you complete remove the app from task manager.). Dec 31, 2024
@P-yiush07
Copy link
Owner

Okkay got it,
means its working fine when you minimize the app/or keep it open. But it doesn't when you closes the app

right ?

@teamrahul teamrahul changed the title Background Services But not working in background( It will not work when you complete remove the app from task manager.). Background Services But not working in background( It will not work when you complete remove the app from task manager.). Only Work When you have Paus/application was still alive Mode. Dec 31, 2024
@teamrahul
Copy link
Author

Okkay got it, means its working fine when you minimize the app/or keep it open. But it doesn't when you closes the app

right ?

Yes Absolutely right.

@P-yiush07 P-yiush07 added the bug Something isn't working label Dec 31, 2024
@teamrahul teamrahul changed the title Background Services But not working in background( It will not work when you complete remove the app from task manager.). Only Work When you have Paus/application was still alive Mode. Background Services But not working in background( It will not work when you complete remove the app from task manager.). Only Work When you have Pause mode/application was still alive Mode. Dec 31, 2024
@P-yiush07
Copy link
Owner

Okkay got it, means its working fine when you minimize the app/or keep it open. But it doesn't when you closes the app
right ?

Yes Absolutely right.

I will implement the message sending even after closing the app, in next update. Thank you for using my package 😊

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
bug Something isn't working
Projects
None yet
Development

No branches or pull requests

2 participants