Kotlin in Flutter application causing Crash - android

Since the last flutter update there has been an issue when I try to use the media player plugin witch uses Kotlin.
When you hit the button and it is suppose to play the audio file, it causes the application to crash.
fun play(url: String) {
player.reset()
channel.invokeMethod("onPosition", 0.0)
player.setDataSource(url)
player.prepareAsync()
channel.invokeMethod("onIsLoading", null)
task?.cancel()
task = object : TimerTask() {
override fun run() {
if (player.isPlaying) {
session.setPlaybackState(PlaybackStateCompat.Builder()
.setState(PlaybackStateCompat.STATE_PLAYING, player.currentPosition.toLong(), 1f)
.build())
channel.invokeMethod("onPosition", player.currentPosition.toDouble() / player.duration.toDouble())
}
}
}
timer.schedule(task, 0, 100)
}
it was suggested that I add this in.
activity.runOnUiThread(java.lang.Runnable {
channel.invokeMethod(...)
})
but I if I do I get
Unresolved Reference: activity
This is the error message.
java.lang.RuntimeException: Methods marked with #UiThread must be executed on the main thread. Current thread: Timer-0
at io.flutter.embedding.engine.FlutterJNI.ensureRunningOnMainThread(FlutterJNI.java:605)
at io.flutter.embedding.engine.FlutterJNI.dispatchPlatformMessage(FlutterJNI.java:515)
at io.flutter.embedding.engine.dart.DartMessenger.send(DartMessenger.java:76)
at io.flutter.embedding.engine.dart.DartExecutor.send(DartExecutor.java:166)
at io.flutter.view.FlutterNativeView.send(FlutterNativeView.java:155)
at io.flutter.plugin.common.MethodChannel.invokeMethod(MethodChannel.java:98)
at io.flutter.plugin.common.MethodChannel.invokeMethod(MethodChannel.java:84)
at live.exit.musicplayer.MusicPlayer$play$1.run(MusicPlayer.kt:49)
at java.util.TimerThread.mainLoop(Timer.java:562)
at java.util.TimerThread.run(Timer.java:512)
I am at a bit of a loss, this is suppose to be playing audio.
I know NOTHING about kotlin.

I think you're using ragotrebor music-player plugin (https://gitlab.com/ragotrebor). Looking at their history a merge was made about a month ago which should fix this issue.
Just update to the latest version of the plugin and you should be good to go!
Background
It's related to a change in flutter to fix a bug which caused FlutterJNI (Java Native Interface) to crash intermittently when certain methods were executed outside of the main thread. Flutter was changed to thrown an exception in all cases, to avoid this intermittent crash and force developers to run methods correctly on the UI thread. Unfortunately this caused many existing plugins to crash and developers were required to update their source code.
Reference links
Change with discussion: https://github.com/flutter/engine/commit/2c9e37c34e79475bbde7c8163eb5e56cdb9662a
Found through this thread discussing a fix for a specific plugin: https://github.com/flutter/flutter/issues/34993).
Merge request details for music player plugin that fixed this issue: https://gitlab.com/exitlive/music-player/commit/693131a7f0d29b3ee42ba9fa2a5ce65aef7652fb

Related

Unity GoogleMobileAdsMediationTestSuite throws exception setAdListener must be called on the main UI thread

I tried to implement MediationTestSuite into my Unity Game, but I got this exception and therefore couldn't see MediationTestSuite
Exception:
java.lang.IllegalStateException: setAdListener must be called on the main UI thread.
at lr.b(:com.google.android.gms.policy_ads_fdr_dynamite#21001000#21001000.272763194.272763194:1)
at com.google.android.gms.ads.nonagon.shim.f.a(:com.google.android.gms.policy_ads_fdr_dynamite#21001000#21001000.272763194.272763194:14)
at com.google.android.gms.ads.nonagon.shim.g.a(:com.google.android.gms.policy_ads_fdr_dynamite#21001000#21001000.272763194.272763194:4)
at com.google.android.gms.ads.internal.client.ap.a(:com.google.android.gms.policy_ads_fdr_dynamite#21001000#21001000.272763194.272763194:62)
at ff.onTransact(:com.google.android.gms.policy_ads_fdr_dynamite#21001000#21001000.272763194.272763194:4)
at android.os.Binder.transact(Binder.java:667)
My code is
public void OnButtonClick()
{
GoogleMobileAdsMediationTestSuite.Api.MediationTestSuite.Show();
}
Binded on single button in scene.
​​​I've tried to do this directly in Update method by dispatching this call, also tried to create empty Unity project and by adding into it only GoogleMobileAds-v4.1.0 + GoogleMobileAdsUnityAdsMediation + GoogleMobileAdsMediationTestSuite all downloaded directly from Google links.
Is there something I'm missing here, or is it just MediationTestSuite that is bugged and calles some UI stuff in separate thread?
It's definetely not a duplicate of AdMob Interstitial and error isLoaded must be called on the main UI thread since it's in Unity and I do not have access to MeditationTestSuite library code.
Well. It was all simple. Apparentely MediationTestSuite throws this kind of exception when you unity build doesn't have "development build" mark. But I did have it. The case was that I should've used assembleDebug in gradle build tasks.
I've got this problem because I builded my android manually by exporting into android project instead of building with unity.

Espresso test error: AppNotIdleException

I turned off all animations on developer options.
But I still get this exception when trying to click on one of the buttons.
My app is indeed active and not idle entirely, but I can't change it.
android.support.test.espresso.AppNotIdleException: Looped for 6930
iterations over 60 SECONDS. The following Idle Conditions failed .
at dalvik.system.VMStack.getThreadStackTrace(Native Method)
at java.lang.Thread.getStackTrace(Thread.java:580)
at android.support.test.espresso.base.DefaultFailureHandler.getUserFriendlyError(DefaultFailureHandler.java:92)
at android.support.test.espresso.base.DefaultFailureHandler.handle(DefaultFailureHandler.java:56)
at android.support.test.espresso.ViewInteraction.runSynchronouslyOnUiThread(ViewInteraction.java:184)
at android.support.test.espresso.ViewInteraction.doPerform(ViewInteraction.java:115)
at android.support.test.espresso.ViewInteraction.perform(ViewInteraction.java:87)
I have been struggling with this problem for the last few days.
Here is a method that I used to identify "violators":
private void dumpThreads() {
int activeCount = Thread.activeCount();
Thread[] threads = new Thread[activeCount];
Thread.enumerate(threads);
for (Thread thread : threads) {
System.err.println(thread.getName() + ": " + thread.getState());
for (StackTraceElement stackTraceElement : thread.getStackTrace()) {
System.err.println("\t" + stackTraceElement);
}
}
}
In my case, Facebook SDK was using the AsyncTask thread pool.
In my case this problem was happening with AnimatedVectorDrawable and caused by an objectAnimator that was set to repeat the animation infinitely (android:repeatCount="infinite"). .
The problem was also present only on older platform versions. Tests were perfectly working on Android 9 while the problem was reproducible on Android 5 and 6 (not sure about 7 and 8 at the moment).
I believe, the root cause of the problem is the same as for indeterminate progress bars (covered in this SO question). However, I haven't found any nice solution, only workarounds.
One of the workarounds is to detect that the animation is turned off (animator duration is 0) in the setting and don't start the animation. Of course, this only works for platform versions where the animation does not autostart.
private fun startIconAnimation(imageView: ImageView) {
if (areAnimationsEnabled()) {
(imageView.drawable as Animatable).start()
}
}
private fun areAnimationsEnabled(): Boolean {
val animatorDurationScale = Settings.Global.getFloat(
requireContext().contentResolver,
Settings.Global.ANIMATOR_DURATION_SCALE,
1.0f
)
return animatorDurationScale != 0.0f
}
Note: API level 26 introduced a static method ValueAnimator.areAnimatorsEnabled() which would have been handy if the problem was not happening only on the older platform versions.
As per answer by MaciejGórski to the similar question:
It was a bug in my app code, where SwipeRefreshLayout animated
itself indefinitely. Due to a bug in this
component,
the refresh state was not even showing.
In my case I clicked "save" button running long request in a test. To complete the test I had to add idle() after save() method. But often it was not enough, a loader continued drawing and the test failed. Then I increased a duration: idle(10000) and got the error: androidx.test.espresso.AppNotIdleException: Looped for 238 iterations over 10 SECONDS. The following Idle Conditions failed DELAY_HAS_PAST..
I wrote: idle(5000). Instead of Espresso I use Kakao and Kaspresso.

Error while creating a new activity in Android Studio

Every time I create a new activity in Android Studio, I get an error like this:
Read access is allowed from event dispatch thread or inside read-action only (see com.intellij.openapi.application.Application.runReadAction())
Details: Current thread: Thread[ApplicationImpl pooled thread 17,4,main] 1345722054;
dispatch thread: false; isDispatchThread(): false
SystemEventQueueThread: Thread[AWT-EventQueue-0 1.3#AI-141.2178183, eap:false,6,main] 2033877427
It doesn't cause any problem though, and the activity is created like it should normally be. So what is the problem?
There is no evidence that this log is related to your application.
it has something to do with android studio (intellij) which you can easily ignore as long as everything is working fine for you.

Running ExtractDecodeEditEncodeMuxTest outside of testcase on Android

I am trying to add functionality to extract, decode, edit, encode and mux a video on Android. Therefore, I found some very useful implementation, which is part of the Android CTS ExtractDecodeEditEncodeMuxTest. Unfortunately, the code only works if it is executed as part of the testcase. I tried to execute it from a normal activity and get:
E/ExtractDecodeEditEncodeMuxTest (18781): java.lang.IllegalStateException:
Failed to stop the muxer
W/System.err(18781): java.lang.RuntimeException:
Surface frame wait timed out
W/System.err(18781): at ...OutputSurface.awaitNewImage(OutputSurface.java:216)
Any ideas, why the output surface does not receive the frames?
UPDATE:
Here are the log files for the working test case and the non-working implementation. The code for both is exactly the same. The only difference is that the working one is an AndroidTestCase and the other one is running in the application within an IntentService.
It seems that the whole thing stops extracting and decoding after about 6 frames. Any ideas?
Working Testcase Logoutput
Non-Working Log Output
morelikely you need to run it in separate thread
public static void runTest(ExtractDecodeEditEncodeMuxTest test) throws Throwable {
test.setOutputFile();
TestWrapper wrapper = new TestWrapper(test);
Thread th = new Thread(wrapper, "codec test");
th.start();
th.join();
if (wrapper.mThrowable != null) {
throw wrapper.mThrowable;
}
}
Thank's to fadden, I was able to resolve this issue. I am using an intent service now and start a thread without looper there, which works fine.
For running the code in an Android service, this means that the wrapping thread has to be started from a custom thread. Starting a thread within a thread is probably not the very best solution, but it actually solves the problem.

Error calling method on NPObject! in Android 2.2

I'm using addJavascriptInterface within my Android application to allow JavaScript to invoke functions I've created in my native Java application.
This worked well in Android 2.1, however in Android 2.2 I receive the error message "Error calling method on NPObject!"
When I instrument the method call the internals of the native method are getting called, however the exception is being throw in JavaScript.
I was getting this exact error:
Uncaught Error: Error calling method on NPObject!
Turns out I was attempting to invoke a JavascriptInterface function from a webview like so:
AndroidJS.populateField(field);
and on the Java side, the function didn't accept a parameter:
public void populateField() {}
Simply allowing the Java function to accept a parameter solved this error for me.
E.g.,
public void populateField(String field) {}
This may not be, and probably is not, the only reason this error could be thrown. This is simply how I resolved my specific scenario. Hope this helps! :)
OK, I have same problem as well, just in today.
What I did is putting code in UI Thread, like code below :
/**
* 給網頁Javascript呼叫的method
* Method for Javascript in HTML
* #param java.lang.String - Playlist ID
*/
public int callListByPID(final String pId)
{
Log.i(Constants.TAG, "PAD Playlist ID from HTML: "+pId);
runOnUiThread(new Runnable()
{
public void run()
{
// Put your code here...
}
});
return 1;
}
This solved my problem, and hope it can help some body... :-)
In my experience this problem is caused by Javascript interfaces bringing back objects that Javascript doesn't automatically identify.
In Android this is caused by wrappers like Boolean or Long in comparison to their native versions boolean and long.
//This will fail
public Long getmyLongVal() {
return 123456789;
}
//This will work
public long getMyNativeLongVal() {
return 123456789;
}
So remove your wrapper classes to any methods being used by Javascript if you want to avoid NPObject errors.
Here's a twist I found on this problem that could be useful for some of the folks running into this problem (and it likely explains intermittent failures that seem to defy explanation)...
If any exceptions are thrown (and not caught) in the return handler code prior to allowing the javascript interface callback to return clean, it will propagate back as a failed call and you will also get this error - and it would have nothing to do with missing functions or parameters.
The easiest way to find this case (whether or not you use this in your final implementation) is to push whatever handler code you have back onto the UI thread (the callback will not be on the UI thread) - this will allow the callback to return clean and any subsequent exceptions that occur will propagate properly up until you catch them or until the app crashes. Either way you will see exactly what is really happening. Otherwise the uncaught exception passes back to javascript where it will not be handled or reported in any way (unless you specifically built error trapping code into the JS you were executing).
Good Luck All.
bh
I had the same problem with Javascript-to-Java interface (WebView.addJavascriptInterface).
In Android 2.1 everything worked just fine but in Android 2.2 Javascript failed to call methods from this interface. It returned an error: Uncaught Error: Error calling method on NPObject!
It seems that on Android 2.2, the WebView has problem with Boolean data type returned from interface functions.
Changing:
public Boolean test_func() { return true; }
... to:
public int test_func() { return 1; }
... solved the problem.
This I believe is no longer supported anymore ( Always game NPObject error ) .
Please refer to the answer in this thread
Visit open an activity from a CordovaPlugin

Categories

Resources