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

onStop error #203

Closed
o4x opened this issue Mar 6, 2020 · 8 comments
Closed

onStop error #203

o4x opened this issue Mar 6, 2020 · 8 comments
Assignees

Comments

@o4x
Copy link

o4x commented Mar 6, 2020

Describe the bug
When I call onStop method i get this error.

PlatformException (PlatformException(error, Attempt to invoke interface method 'void io.flutter.embedding.engine.plugins.activity.ActivityPluginBinding.removeRequestPermissionsResultListener(io.flutter.plugin.common.PluginRegistry$RequestPermissionsResultListener)' on a null object reference, null))

and after that when i want to start again It crashes.

Error messages

E/MethodChannel#ryanheise.com/audioServiceBackground(26360): Failed to handle method call
E/MethodChannel#ryanheise.com/audioServiceBackground(26360): java.lang.NullPointerException: Attempt to invoke interface method 'void io.flutter.embedding.engine.plugins.activity.ActivityPluginBinding.removeRequestPermissionsResultListener(io.flutter.plugin.common.PluginRegistry$RequestPermissionsResultListener)' on a null object reference
E/MethodChannel#ryanheise.com/audioServiceBackground(26360): 	at boaventura.com.devel.br.flutteraudioquery.FlutterAudioQueryPlugin.tearDown(FlutterAudioQueryPlugin.java:205)
E/MethodChannel#ryanheise.com/audioServiceBackground(26360): 	at boaventura.com.devel.br.flutteraudioquery.FlutterAudioQueryPlugin.onDetachedFromEngine(FlutterAudioQueryPlugin.java:135)
E/MethodChannel#ryanheise.com/audioServiceBackground(26360): 	at io.flutter.embedding.engine.FlutterEnginePluginRegistry.remove(FlutterEnginePluginRegistry.java:244)
E/MethodChannel#ryanheise.com/audioServiceBackground(26360): 	at io.flutter.embedding.engine.FlutterEnginePluginRegistry.remove(FlutterEnginePluginRegistry.java:252)
E/MethodChannel#ryanheise.com/audioServiceBackground(26360): 	at io.flutter.embedding.engine.FlutterEnginePluginRegistry.removeAll(FlutterEnginePluginRegistry.java:260)
E/MethodChannel#ryanheise.com/audioServiceBackground(26360): 	at io.flutter.embedding.engine.FlutterEnginePluginRegistry.destroy(FlutterEnginePluginRegistry.java:116)
E/MethodChannel#ryanheise.com/audioServiceBackground(26360): 	at io.flutter.embedding.engine.FlutterEngine.destroy(FlutterEngine.java:267)
E/MethodChannel#ryanheise.com/audioServiceBackground(26360): 	at com.ryanheise.audioservice.AudioServicePlugin$BackgroundHandler.onMethodCall(AudioServicePlugin.java:677)
E/MethodChannel#ryanheise.com/audioServiceBackground(26360): 	at io.flutter.plugin.common.MethodChannel$IncomingMethodCallHandler.onMessage(MethodChannel.java:231)
E/MethodChannel#ryanheise.com/audioServiceBackground(26360): 	at io.flutter.embedding.engine.dart.DartMessenger.handleMessageFromDart(DartMessenger.java:93)
E/MethodChannel#ryanheise.com/audioServiceBackground(26360): 	at io.flutter.embedding.engine.FlutterJNI.handlePlatformMessage(FlutterJNI.java:642)
E/MethodChannel#ryanheise.com/audioServiceBackground(26360): 	at android.os.MessageQueue.nativePollOnce(Native Method)
E/MethodChannel#ryanheise.com/audioServiceBackground(26360): 	at android.os.MessageQueue.next(MessageQueue.java:376)
E/MethodChannel#ryanheise.com/audioServiceBackground(26360): 	at android.os.Looper.loop(Looper.java:244)
E/MethodChannel#ryanheise.com/audioServiceBackground(26360): 	at android.app.ActivityThread.main(ActivityThread.java:6706)
E/MethodChannel#ryanheise.com/audioServiceBackground(26360): 	at java.lang.reflect.Method.invoke(Native Method)

@ryanheise ryanheise self-assigned this Mar 7, 2020
@ryanheise ryanheise added this to To do in audio_service via automation Mar 7, 2020
@ryanheise
Copy link
Owner

You aren't supposed to call onStop because it's a callback. Do you mean when you call AudioService.stop?

@o4x
Copy link
Author

o4x commented Mar 7, 2020

You aren't supposed to call onStop because it's a callback. Do you mean when you call AudioService.stop?

yes,

Screenshot_20200307-072054

@ryanheise
Copy link
Owner

Your error message indicates an error with another plugin, although I'm unfamiliar with it. I would suggest reporting the bug with that project.

@o4x
Copy link
Author

o4x commented Mar 7, 2020

there aren't another plugin in my background

import 'dart:async';
import 'package:audio_service/audio_service.dart';
import 'package:just_audio/just_audio.dart';
import 'package:flutter/material.dart';


void myBackgroundTaskEntrypoint() {
  AudioServiceBackground.run(() => CustomAudioPlayer());
}

class CustomAudioPlayer extends BackgroundAudioTask {
final _queue = <MediaItem>[];
  int _queueIndex = -1;
  AudioPlayer _audioPlayer = new AudioPlayer();
  Completer _completer = Completer();
  BasicPlaybackState _skipState;
  bool _playing;

  bool get hasNext => _queueIndex + 1 < _queue.length;

  bool get hasPrevious => _queueIndex > 0;

  MediaItem get mediaItem => _queue[_queueIndex];

  BasicPlaybackState _stateToBasicState(AudioPlaybackState state) {
    switch (state) {
      case AudioPlaybackState.none:
        return BasicPlaybackState.none;
      case AudioPlaybackState.stopped:
        return BasicPlaybackState.stopped;
      case AudioPlaybackState.paused:
        return BasicPlaybackState.paused;
      case AudioPlaybackState.playing:
        return BasicPlaybackState.playing;
      case AudioPlaybackState.connecting:
        return _skipState ?? BasicPlaybackState.connecting;
      case AudioPlaybackState.completed:
        return BasicPlaybackState.stopped;
      default:
        throw Exception("Illegal state");
    }
  }

  @override
  Future<void> onStart() async {
    var playerStateSubscription = _audioPlayer.playbackStateStream
        .where((state) => state == AudioPlaybackState.completed)
        .listen((state) {
      _handlePlaybackCompleted();
    });
    var eventSubscription = _audioPlayer.playbackEventStream.listen((event) {
      final state = _stateToBasicState(event.state);
      if (state != BasicPlaybackState.stopped) {
        _setState(
          state: state,
          position: event.position.inMilliseconds,
        );
      }
    });

    AudioServiceBackground.setQueue(_queue);
    await _completer.future;
    await playerStateSubscription.cancel();
    await eventSubscription.cancel();
  }

  void _handlePlaybackCompleted() {
    if (hasNext) {
      onSkipToNext();
    } else {
      onStop();
    }
  }

  void playPause() {
    if (AudioServiceBackground.state.basicState == BasicPlaybackState.playing)
      onPause();
    else
      onPlay();
  }

  @override
  Future<void> onSkipToNext() => _skip(1);

  @override
  Future<void> onSkipToPrevious() => _skip(-1);

  Future<void> _skip(int offset) async {
    final newPos = _queueIndex + offset;
    if (!(newPos >= 0 && newPos < _queue.length)) return;
    if (_playing == null) {
      // First time, we want to start playing
      _playing = true;
    } else if (_playing) {
      // Stop current item
      await _audioPlayer.stop();
    }
    // Load next item
    _queueIndex = newPos;
    AudioServiceBackground.setMediaItem(mediaItem);
    _skipState = offset > 0
        ? BasicPlaybackState.skippingToNext
        : BasicPlaybackState.skippingToPrevious;
    await _audioPlayer.setFilePath(mediaItem.id);
    _skipState = null;
    // Resume playback if we were playing
    if (_playing) {
      onPlay();
    } else {
      _setState(state: BasicPlaybackState.paused);
    }
  }

  @override
  void onPlay() async {
    if (_skipState == null) {
      _playing = true;
      _audioPlayer.play();
    }
  }

  @override
  void onPause() {
    if (_skipState == null) {
      _playing = false;
      _audioPlayer.pause();
    }
  }

  @override
  void onSeekTo(int position) {
    _audioPlayer.seek(Duration(milliseconds: position));
  }

  @override
  void onClick(MediaButton button) {
    playPause();
  }

  @override
  void onStop() {
    _audioPlayer.stop();
    _setState(state: BasicPlaybackState.stopped);
    _completer.complete();
  }


  
  @override
  void onAddQueueItem(MediaItem mediaItem) async {
    _queue.add(mediaItem);
    AudioServiceBackground.setQueue(_queue);
    await onSkipToNext();
  }

  void _setState({@required BasicPlaybackState state, int position}) {
    if (position == null) {
      position = _audioPlayer.playbackEvent.position.inMilliseconds;
    }
    AudioServiceBackground.setState(
      controls: getControls(state),
      systemActions: [MediaAction.seekTo],
      basicState: state,
      position: position,
    );
  }

  List<MediaControl> getControls(BasicPlaybackState state) {
    if (_playing) {
      return [
        skipToPreviousControl,
        pauseControl,
        stopControl,
        skipToNextControl
      ];
    } else {
      return [
        skipToPreviousControl,
        playControl,
        stopControl,
        skipToNextControl
      ];
    }
  }

}


MediaControl playControl = MediaControl(
  androidIcon: 'drawable/ic_action_play_arrow',
  label: 'Play',
  action: MediaAction.play,
);
MediaControl pauseControl = MediaControl(
  androidIcon: 'drawable/ic_action_pause',
  label: 'Pause',
  action: MediaAction.pause,
);
MediaControl skipToNextControl = MediaControl(
  androidIcon: 'drawable/ic_action_skip_next',
  label: 'Next',
  action: MediaAction.skipToNext,
);
MediaControl skipToPreviousControl = MediaControl(
  androidIcon: 'drawable/ic_action_skip_previous',
  label: 'Previous',
  action: MediaAction.skipToPrevious,
);
MediaControl stopControl = MediaControl(
  androidIcon: 'drawable/ic_action_stop',
  label: 'Stop',
  action: MediaAction.stop,
);

@ryanheise
Copy link
Owner

Flutter loads every plugin into each Flutter engine. So even if you're not using the plugin in the background, the fact that you've declared it in your pubspec.yaml means that it will be loaded into the background Flutter engine, too. If a plugin has problems being loaded in this context, you can raise the issue with the developer of that plugin.

@o4x
Copy link
Author

o4x commented Mar 7, 2020

This is strange

Everything is working fine until I add flutter_audio_query: "^ 0.3.4 + 1" to pubspec.yaml

@ryanheise
Copy link
Owner

That is the very plugin your error message above is about. The stack trace will be helpful to the developer of that plugin since it gives the line number and the file name where the error occurs.

@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 22, 2021
Sign up for free to subscribe to this conversation on GitHub. Already have an account? Sign in.
Labels
None yet
Projects
audio_service
  
Done
Development

No branches or pull requests

2 participants