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

[Help] BackgroundTask is never executed #85

Closed
ronaldG19 opened this issue Sep 22, 2019 · 5 comments
Closed

[Help] BackgroundTask is never executed #85

ronaldG19 opened this issue Sep 22, 2019 · 5 comments
Assignees

Comments

@ronaldG19
Copy link

ronaldG19 commented Sep 22, 2019

Describe the bug
Cloned the example project, it only showed the notification without any controls and the music was not played. Integrated into my own project after 3 days of peeking there is no nay notification bar shown or music played.

Minimal reproduction project

@override
  void initState() {
    WidgetsBinding.instance.addObserver(this);
    map = widget.musicHelper.map;
    _thumPercent = 0.0;
     swiperIndex = widget.musicHelper.index;
     defaultSongIndex = swiperIndex;
      songUrl = widget.musicHelper.map[widget.musicHelper.index]['url'];      
       _controller = PageController(initialPage: swiperIndex);
        _start();
    super.initState();    
  }
  Future<void> _start()async{
    await connect();
    await _initAudioService();
    _servicePlay();
  }
   _initAudioService(){
    AudioService.start(
      backgroundTask:()async{
        _backgroundPlayer();
      },
      resumeOnClick: true,
      androidNotificationChannelName: 'Example Project',
      notificationColor: 0x161b21,
      androidNotificationIcon: 'mipmap/ic_launcher'
    );
    }
  void _backgroundPlayer()async{
    print('background service');
    AudioServiceBackground.run(
      onStart: run,
      onPlay: _play,
      onPause: _pause,
      onStop: _pause,
      onPrepare: _initAudioPlayer
      //onClick: 
    );
  }
  Future<void> run()async{
    print('Audio run service');
    MediaItem mediaItem = MediaItem(
      id: map[swiperIndex]['serial'],
      album: 'Unknown',
      artUri:map[swiperIndex]['cover'],
      title: map[swiperIndex]['name'],
      artist: map[swiperIndex]['by']
    );
    AudioServiceBackground.setMediaItem(mediaItem);
    _play();
    await completer.future;
    _durationSubscription?.cancel();
    _positionSubscription?.cancel();
    _playerStateSubscription?.cancel();
    _playerCompleteSubscription?.cancel();
    _audioServiceSubscription?.cancel();
    //cancelSubscriptions
  }

To Reproduce
Steps to reproduce the behavior:

  1. AudioService.connect
  2. Started the plugin by AudioService.start
  3. BackgroundTask not executed
  4. What seems to be errors
SVC-Creating service CreateServiceData{token=android.os.BinderProxy@7f8eced className=com.ryanheise.audioservice.AudioService
packageName=inc.taipan.acapure intent=null}

then

Notification from VM: {streamId: Isolate, event: {type: Event, kind: IsolateStart, isolate: {type: @Isolate, id: isolates/2459700321319607, name: _spawn, number:
2459700321319607}, timestamp: 1569184330328}}
[        ] Sending to VM service: getIsolate({isolateId: isolates/2459700321319607})
[  +56 ms] Result: {type: Isolate, id: isolates/2459700321319607, name: _spawn, number: 2459700321319607, _originNumber: 2459700321319607, startTime: 1569184330293, _heaps: {new:
{type: HeapSpace, name: new, vmName: Scavenger, collections: 0, avgCollectionPeriodMill...
[ +526 ms] Notification from VM: {streamId: Isolate, event: {type: Event, kind: IsolateRunnable, isolate: {type: @Isolate, id: isolates/2459700321319607, name: _spawn, number:
2459700321319607}, timestamp: 1569184330913}}
[        ] Sending to VM service: getIsolate({isolateId: isolates/2459700321319607})
[ +112 ms] Result: {type: Isolate, id: isolates/2459700321319607, name: _spawn, number: 2459700321319607, _originNumber: 969937779835579, startTime: 1569184330294, _heaps: {new:
{type: HeapSpace, name: new, vmName: Scavenger, collections: 0, avgCollectionPeriodMilli...
[ +300 ms] Notification from VM: {streamId: Isolate, event: {type: Event, kind: IsolateExit, isolate: {type: @Isolate, id: isolates/2459700321319607, name: _spawn, number:
2459700321319607}, timestamp: 1569184331325}}

after running flutter run -v

Runtime Environment (please complete the following information):

  • Device: Phantom 6 Plus
  • Android version: 7

Dependencies used

  line_icons: ^0.2.0
  audioplayers: ^0.13.1
  path_provider:
  http:
  marquee_flutter: ^0.1.4
  sqflite: ^1.1.6+3
  uuid:
  flutter_spinkit:
  cloud_firestore: ^0.12.9
  cached_network_image: ^1.1.1
  data_connection_checker: ^0.3.4
  badges: ^1.1.0
  bottom_navy_bar: ^5.2.0
  shared_preferences: ^0.5.3+4
  flare_flutter: ^1.5.5
  frideos: ^0.7.0+1
  flutter_slidable: ^0.5.3
  flushbar: ^1.8.2
  youtube_player_flutter: ^4.1.0
  path:
  seekbar: ^0.0.2
  firebase_auth: ^0.14.0+4
  google_sign_in: ^4.0.7
  flutter_auth_buttons:
  admob_flutter: ^0.3.1
  onesignal:
  url_launcher: ^5.1.2
  share: ^0.6.2+1
  flare_splash_screen: ^2.1.3
  audio_service: ^0.3.1

Flutter SDK version

[✓] Flutter (Channel dev, v1.10.5, on Linux, locale en_US.UTF-8)
    • Flutter version 1.10.5 at /home/go/Downloads/flutter
    • Framework revision 3cf88fed6d (4 days ago), 2019-09-18 23:09:41 -0400
    • Engine revision 33ad6757e8
    • Dart version 2.6.0 (build 2.6.0-dev.1.0 cb80ea7ba9)

 
[✓] Android toolchain - develop for Android devices (Android SDK version 28.0.3)
    • Android SDK at /home/go/Android/Sdk
    • Android NDK location not configured (optional; useful for native profiling
      support)
    • Platform android-28, build-tools 28.0.3
    • ANDROID_HOME = /home/go/Android/Sdk
    • Java binary at:
      /home/go/Downloads/android-studio-ide-183.5522156-linux/android-studio/
      jre/bin/java
    • Java version OpenJDK Runtime Environment (build
      1.8.0_152-release-1343-b16-5323222)
    • All Android licenses accepted.

[✓] Android Studio (version 3.4)
    • Android Studio at
      /home/go/Downloads/android-studio-ide-183.5522156-linux/android-studio
    • Flutter plugin version 36.1.1
    • Dart plugin version 183.6270
    • Java version OpenJDK Runtime Environment (build
      1.8.0_152-release-1343-b16-5323222)

[✓] Connected device (1 available)
    • Phantom6 Plus • 0180010710900365 • android-arm64 • Android 7.1.1 (API 25)

• No issues found!
@ryanheise ryanheise self-assigned this Sep 23, 2019
@ryanheise
Copy link
Owner

If I understand correctly, the supplied example project already exhibits the problem, so I will treat that as your minimal reproduction project.

I tried switching to the dev channel to match your flutter doctor output and ran the example project. I noticed that the notification appears without any controls, but I also noticed this in the console which helps diagnose the problem:

E/flutter ( 4805): [ERROR:flutter/lib/ui/ui_dart_state.cc(148)] Unhandled Exception: ServicesBinding.defaultBinaryMessenger was accessed before the binding was initialized.
E/flutter ( 4805): If you're running an application and need to access the binary messenger before `runApp()` has been called (for example, during plugin initialization), then you need to explicitly call the `WidgetsFlutterBinding.ensureInitialized()` first.
E/flutter ( 4805): If you're running a test, you can call the `TestWidgetsFlutterBinding.ensureInitialized()` as the first line in your test's `main()` method to initialize the binding.
E/flutter ( 4805): #0      defaultBinaryMessenger.<anonymous closure> (package:flutter/src/services/binary_messenger.dart:73:7)
E/flutter ( 4805): #1      defaultBinaryMessenger (package:flutter/src/services/binary_messenger.dart:86:4)        
E/flutter ( 4805): #2      MethodChannel.binaryMessenger (package:flutter/src/services/platform_channel.dart:140:62)
E/flutter ( 4805): #3      MethodChannel.setMethodCallHandler (package:flutter/src/services/platform_channel.dart:368:5)
E/flutter ( 4805): #4      new AudioPlayer (package:audioplayer/audioplayer.dart:42:14)                            
E/flutter ( 4805): #5      new CustomAudioPlayer (package:audio_service_example/main.dart:175:34)                  
E/flutter ( 4805): #6      _backgroundAudioPlayerTask (package:audio_service_example/main.dart:162:30)             
E/flutter ( 4805): <asynchronous suspension>                                                                       
E/flutter ( 4805): #7      _runMainZoned.<anonymous closure>.<anonymous closure> (dart:ui/hooks.dart:231:25)       
E/flutter ( 4805): #8      _rootRun (dart:async/zone.dart:1124:13)                                                 
E/flutter ( 4805): #9      _CustomZone.run (dart:async/zone.dart:1021:19)                                          
E/flutter ( 4805): #10     _runZoned (dart:async/zone.dart:1516:10)                                                
E/flutter ( 4805): #11     runZoned (dart:async/zone.dart:1500:12)                                                 
E/flutter ( 4805): #12     _runMainZoned.<anonymous closure> (dart:ui/hooks.dart:223:5)                            
E/flutter ( 4805): #13     _startIsolate.<anonymous closure> (dart:isolate-patch/isolate_patch.dart:305:19)        
E/flutter ( 4805): #14     _RawReceivePortImpl._handleMessage (dart:isolate-patch/isolate_patch.dart:172:12)       

Did you not also get the same error, or are you having a different issue? In the mean time, I'll see if I can fix the above error.

@ronaldG19
Copy link
Author

ronaldG19 commented Sep 23, 2019

I already resolved that error by initializing WidgetsFlutterBinding.ensureInitialized(), resulted from WidgetBinding.
Notification problem occurred later

@ryanheise
Copy link
Owner

I don't see the call to 'ensureInitialized' in your minimal reproduction project. audio_service does call this, but since the latest commit on dev, we can see that audio_service does not call this soon enough. You can work around it by calling ensureInitialized yourself as the first line in your background task entrypoint function, but I am working on a proper fix in #86.

But looking at your example code, you need to call the start method with a top level function, not with something like () async { ... }. Documentation here:

https://pub.dev/documentation/audio_service/latest/audio_service/AudioService/start.html

The background task is specified by backgroundTask which will be run within a background isolate. This function must be a top-level or static function

@ryanheise
Copy link
Owner

@ronaldG19 I've just published 0.4.0 which addresses the ensureInitialized correctly (See #86 and note the changed API). Also let me know after trying it and also making your background task entrypoint into a top level function whether you still get any errors.

@github-actions
Copy link

This issue has been automatically locked since there has not been any recent activity after it was closed. Please open a new issue for related bugs, or use StackOverflow if you need help with audio_service.

@github-actions github-actions bot locked as resolved and limited conversation to collaborators Oct 23, 2021
Sign up for free to subscribe to this conversation on GitHub. Already have an account? Sign in.
Labels
None yet
Projects
None yet
Development

No branches or pull requests

2 participants