Skip to content

Commit

Permalink
refactor: improve android performances
Browse files Browse the repository at this point in the history
  • Loading branch information
ekasetiawans committed Jun 14, 2023
1 parent 9fac941 commit 13f73a8
Show file tree
Hide file tree
Showing 10 changed files with 156 additions and 174 deletions.
Expand Up @@ -44,7 +44,7 @@ android {
defaultConfig {
// TODO: Specify your own unique Application ID (https://developer.android.com/studio/build/application-id.html).
applicationId "id.flutter.example"
minSdkVersion flutter.minSdkVersion
minSdkVersion 19
targetSdkVersion flutter.targetSdkVersion
versionCode flutterVersionCode.toInteger()
versionName flutterVersionName
Expand Down
Expand Up @@ -26,6 +26,6 @@ subprojects {
project.evaluationDependsOn(':app')
}

task clean(type: Delete) {
tasks.register("clean", Delete) {
delete rootProject.buildDir
}
14 changes: 8 additions & 6 deletions packages/flutter_background_service/example/lib/main.dart
Expand Up @@ -30,14 +30,16 @@ Future<void> initializeService() async {
final FlutterLocalNotificationsPlugin flutterLocalNotificationsPlugin =
FlutterLocalNotificationsPlugin();

if (Platform.isIOS) {
if (Platform.isIOS || Platform.isAndroid) {
await flutterLocalNotificationsPlugin.initialize(
const InitializationSettings(
iOS: IOSInitializationSettings(),
iOS: DarwinInitializationSettings(),
android: AndroidInitializationSettings('ic_bg_service_small'),
),
);
}


await flutterLocalNotificationsPlugin
.resolvePlatformSpecificImplementation<
AndroidFlutterLocalNotificationsPlugin>()
Expand Down Expand Up @@ -139,10 +141,10 @@ void onStart(ServiceInstance service) async {
);

// if you don't using custom notification, uncomment this
// service.setForegroundNotificationInfo(
// title: "My App Service",
// content: "Updated at ${DateTime.now()}",
// );
service.setForegroundNotificationInfo(
title: "My App Service",
content: "Updated at ${DateTime.now()}",
);
}
}

Expand Down
10 changes: 5 additions & 5 deletions packages/flutter_background_service/example/pubspec.yaml
Expand Up @@ -42,12 +42,12 @@ dependencies:
flutter_background_service_android: ^4.0.0
# The following adds the Cupertino Icons font to your application.
# Use with the CupertinoIcons class for iOS style icons.
cupertino_icons: ^1.0.2
device_info_plus: ^3.2.2
shared_preferences: ^2.0.15
cupertino_icons: ^1.0.5
device_info_plus: ^9.0.2
shared_preferences: ^2.1.2

# optional if you wish to use a custom foreground service notification
flutter_local_notifications: ^9.9.1
flutter_local_notifications: ^14.1.1

dev_dependencies:
flutter_test:
Expand All @@ -58,7 +58,7 @@ dev_dependencies:
# activated in the `analysis_options.yaml` file located at the root of your
# package. See that file for information about deactivating specific lint
# rules and activating additional ones.
flutter_lints: ^1.0.0
flutter_lints: ^2.0.1

# For information on the generic Dart part of this file, see the
# following page: https://dart.dev/tools/pub/pubspec
Expand Down

This file was deleted.

This file was deleted.

Expand Up @@ -8,6 +8,7 @@
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.app.Service;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.os.Build;
Expand Down Expand Up @@ -38,13 +39,13 @@
import io.flutter.plugin.common.JSONMethodCodec;
import io.flutter.plugin.common.MethodCall;
import io.flutter.plugin.common.MethodChannel;
import io.flutter.plugin.common.PluginRegistry;

public class BackgroundService extends Service implements MethodChannel.MethodCallHandler {
private static final String TAG = "BackgroundService";
private static final String LOCK_NAME = BackgroundService.class.getName()
+ ".Lock";
public static volatile WakeLock lockStatic = null; // notice static
final Map<Integer, IBackgroundService> listeners = new HashMap<>();
AtomicBoolean isRunning = new AtomicBoolean(false);
private FlutterEngine backgroundEngine;
private MethodChannel methodChannel;
Expand All @@ -56,32 +57,6 @@ public class BackgroundService extends Service implements MethodChannel.MethodCa
private String notificationChannelId;
private int notificationId;
private Handler mainHandler;
private final IBackgroundServiceBinder.Stub binder = new IBackgroundServiceBinder.Stub() {

@Override
public void bind(int id, IBackgroundService service) {
synchronized (listeners) {
listeners.put(id, service);
}
}

@Override
public void unbind(int id) {
synchronized (listeners) {
listeners.remove(id);
}
}

@Override
public void invoke(String data) {
try {
JSONObject call = new JSONObject(data);
receiveData(call);
} catch (Exception e) {
e.printStackTrace();
}
}
};

synchronized public static PowerManager.WakeLock getLock(Context context) {
if (lockStatic == null) {
Expand All @@ -97,25 +72,20 @@ synchronized public static PowerManager.WakeLock getLock(Context context) {

@Override
public IBinder onBind(Intent intent) {
return binder;
return null;
}

@Override
public boolean onUnbind(Intent intent) {
final int binderId = intent.getIntExtra("binder_id", 0);
if (binderId != 0) {
synchronized (listeners) {
listeners.remove(binderId);
}
}

return super.onUnbind(intent);
}

@Override
public void onCreate() {
super.onCreate();

FlutterBackgroundServicePlugin.servicePipe.addListener(listener);

config = new Config(this);
mainHandler = new Handler(Looper.getMainLooper());

Expand Down Expand Up @@ -151,9 +121,17 @@ public void onDestroy() {

methodChannel = null;
dartEntrypoint = null;
FlutterBackgroundServicePlugin.servicePipe.removeListener(listener);
super.onDestroy();
}

private final Pipe.PipeListener listener = new Pipe.PipeListener() {
@Override
public void onReceived(JSONObject object) {
receiveData(object);
}
};

private void createNotificationChannel() {
if (SDK_INT >= Build.VERSION_CODES.O) {
CharSequence name = "Background Service";
Expand Down Expand Up @@ -223,6 +201,10 @@ private void runService() {

isRunning.set(true);
backgroundEngine = new FlutterEngine(this);

// remove FlutterBackgroundServicePlugin (because its only for UI)
backgroundEngine.getPlugins().remove(FlutterBackgroundServicePlugin.class);

backgroundEngine.getServiceControlSurface().attachToService(BackgroundService.this, null, config.isForeground());

methodChannel = new MethodChannel(backgroundEngine.getDartExecutor().getBinaryMessenger(), "id.flutter/background_service_android_bg", JSONMethodCodec.INSTANCE);
Expand All @@ -234,6 +216,7 @@ private void runService() {
long backgroundHandle = config.getBackgroundHandle();
args.add(String.valueOf(backgroundHandle));


backgroundEngine.getDartExecutor().executeDartEntrypoint(dartEntrypoint, args);

} catch (UnsatisfiedLinkError e) {
Expand Down Expand Up @@ -316,34 +299,15 @@ public void onMethodCall(@NonNull MethodCall call, @NonNull MethodChannel.Result
if (method.equalsIgnoreCase("stopService")) {
isManuallyStopped = true;
WatchdogReceiver.remove(this);

try {
synchronized (listeners) {
for (Integer key : listeners.keySet()) {
IBackgroundService listener = listeners.get(key);
if (listener != null) {
listener.stop();
}
}
}
} catch (Exception e) {
e.printStackTrace();
}

stopSelf();
result.success(true);
return;
}

if (method.equalsIgnoreCase("sendData")) {
try {
synchronized (listeners) {
for (Integer key : listeners.keySet()) {
IBackgroundService listener = listeners.get(key);
if (listener != null) {
listener.invoke(call.arguments.toString());
}
}
if (FlutterBackgroundServicePlugin.mainPipe.hasListener()){
FlutterBackgroundServicePlugin.mainPipe.invoke((JSONObject) call.arguments);
}

result.success(true);
Expand Down

0 comments on commit 13f73a8

Please sign in to comment.