Android MediaPlayer - setPlaybackParams throws a security exception - android

I'm trying to play a video faster/slower via the following block of code.
videoView.setOnPreparedListener(new MediaPlayer.OnPreparedListener() {
#Override
public void onPrepared(MediaPlayer mp) {
socket.send(positionID + ":playState:ready:empty");
player = mp;
player.setPlaybackParams(new PlaybackParams().setSpeed(1.0f));
}
});
I'm passing '1' as the parameter at the moment just for testing, which is supposed to be normal playback speed. But I get the following error regardless of what number I pass.
01-04 18:49:17.308 24548-24548/com.spectiv.slave E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.spectiv.slave, PID: 24548
java.lang.SecurityException
at android.media.MediaPlayer.setPlaybackParams(Native Method)
at com.spectiv.slave.videoActivity$3.onPrepared(videoActivity.java:80)
at android.widget.VideoView$2.onPrepared(VideoView.java:432)
at android.media.MediaPlayer$EventHandler.handleMessage(MediaPlayer.java:2830)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:148)
at android.app.ActivityThread.main(ActivityThread.java:5417)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:726)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:616)
I'm working targeting API level 23 with a compiled SDK version of 24 and I'm running the application on an Odroid C2. Any help is greatly appreciated.
EDIT - This error doesn't happen on an emulator. I have no idea what's different about the Android running on this Odroid C2. They were both Marshmallow.

I would try with
player.setPlaybackParams(player.getPlaybackParams().setSpeed(1.0f))
assuming that the video is playing without setting the playback params

Just wanted to put this as an answer for anyone searching. The error only happens on this specific piece of hardware (Odroid C2). Running the code in an emulator works.

I got the same problem on C2.
Try release media player onDestroyView() function of your fragment.
or release media player quicker than that.
It appears because pervious media player is not correctly released.

You have not started the Media Player..
player = mp;
player .start()
player.setPlaybackParams(new PlaybackParams().setSpeed(1.0f));

Related

onBackPressed sometimes or always called automaticaly when starting activity

i have problem with my app in some devices (HUAWEI P10 Lite, rockchip A95XR3). Maybe more in future.
According to users, when opening the Video Player Activity, the app immediately crashes.
I think, when they open the Video Player Activity, they quickly press the back button when Activity is not ready. So I tried to use my Oppo Realme 5Pro device and then tried to hit the back button with lightning speed, but it didn't crash (I tried several times). And I also tried running it on the emulator according to the Android version with problems 8.0.0 and 9.
Stack Trace:
Fatal Exception: java.lang.NullPointerException: Attempt to invoke virtual method 'void c.d.b.a.t0.b()' on a null object reference
at com.**cencored**.C_Video_Player.ReleasePlayer(Act_Video_Player.java:163)
at com.**cencored**.C_Video_Player.onBackPressed(Act_Video_Player.java:405)
at android.app.Activity.onKeyUp(Activity.java:3161)
at android.view.KeyEvent.dispatch(KeyEvent.java:2779)
at androidx.core.view.KeyEventDispatcher.activitySuperDispatchKeyEventPre28(KeyEventDispatcher.java:137)
at androidx.core.view.KeyEventDispatcher.dispatchKeyEvent(KeyEventDispatcher.java:87)
at androidx.core.app.ComponentActivity.dispatchKeyEvent(ComponentActivity.java:133)
at androidx.appcompat.app.AppCompatActivity.dispatchKeyEvent(AppCompatActivity.java:558)
at androidx.appcompat.view.WindowCallbackWrapper.dispatchKeyEvent(WindowCallbackWrapper.java:59)
at androidx.appcompat.app.AppCompatDelegateImpl$AppCompatWindowCallback.dispatchKeyEvent(AppCompatDelegateImpl.java:2814)
at com.android.internal.policy.DecorView.dispatchKeyEvent(DecorView.java:415)
at android.view.ViewRootImpl$ViewPostImeInputStage.processKeyEvent(ViewRootImpl.java:5191)
at android.view.ViewRootImpl$ViewPostImeInputStage.onProcess(ViewRootImpl.java:5063)
at android.view.ViewRootImpl$InputStage.deliver(ViewRootImpl.java:4581)
at android.view.ViewRootImpl$InputStage.onDeliverToNext(ViewRootImpl.java:4634)
at android.view.ViewRootImpl$InputStage.forward(ViewRootImpl.java:4600)
at android.view.ViewRootImpl$AsyncInputStage.forward(ViewRootImpl.java:4727)
at android.view.ViewRootImpl$InputStage.apply(ViewRootImpl.java:4608)
at android.view.ViewRootImpl$AsyncInputStage.apply(ViewRootImpl.java:4784)
at android.view.ViewRootImpl$InputStage.deliver(ViewRootImpl.java:4581)
at android.view.ViewRootImpl$InputStage.onDeliverToNext(ViewRootImpl.java:4634)
at android.view.ViewRootImpl$InputStage.forward(ViewRootImpl.java:4600)
at android.view.ViewRootImpl$InputStage.apply(ViewRootImpl.java:4608)
at android.view.ViewRootImpl$InputStage.deliver(ViewRootImpl.java:4581)
at android.view.ViewRootImpl$InputStage.onDeliverToNext(ViewRootImpl.java:4634)
at android.view.ViewRootImpl$InputStage.forward(ViewRootImpl.java:4600)
at android.view.ViewRootImpl$AsyncInputStage.forward(ViewRootImpl.java:4760)
at android.view.ViewRootImpl$ImeInputStage.onFinishedInputEvent(ViewRootImpl.java:4921)
at android.view.inputmethod.InputMethodManager$PendingEvent.run(InputMethodManager.java:2599)
at android.view.inputmethod.InputMethodManager.invokeFinishedInputEventCallback(InputMethodManager.java:2160)
at android.view.inputmethod.InputMethodManager.finishedInputEvent(InputMethodManager.java:2151)
at android.view.inputmethod.InputMethodManager$ImeInputEventSender.onInputEventFinished(InputMethodManager.java:2574)
at android.view.InputEventSender.dispatchInputEventFinished(InputEventSender.java:141)
at android.os.MessageQueue.nativePollOnce(MessageQueue.java)
at android.os.MessageQueue.next(MessageQueue.java:379)
at android.os.Looper.loop(Looper.java:144)
at android.app.ActivityThread.main(ActivityThread.java:7523)
at java.lang.reflect.Method.invoke(Method.java)
at com.android.internal.os.Zygote$MethodAndArgsCaller.run(Zygote.java:245)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:921)
If I see Stack Trace through Firebase Crashlytics, it looks like onBackPressed has been called, but according to the user they don't press the back button.
Below this is part of the code that is related to the problem.
private void ReleasePlayer() {
exoPlayer.release(); //Line 163
isVideoPrepared ="no";
TextError.setVisibility(GONE);
TextReconnecting.setVisibility(GONE);
TextTryCount.setVisibility(GONE);
}
#Override
public void onBackPressed() {
super.onBackPressed();
exoPlayerView.setVisibility(GONE);
forInfo.setVisibility(GONE);
forAds.setVisibility(GONE);
forControl.setVisibility(GONE);
ReleasePlayer(); //Line 405
finish();
}
On the stack trace above also not mentioned onCreate, so of course the exoplayer has not been initialized yet.
The real question is, what are the problems with the above devices? or maybe in my code?

MediaPlayer crashes on setDataSource with R.raw audio

I'm making an Audio Player app that will load some predefined audios from inside its raw resource folder.
I've sent the test APK for some people to test it, and it worked on 99% of the cases. But then, I started to get some crash reports on Crashlytics for a single device, the OnePlus A5000, running Android 8.1.0.
The stacktrace on crashlytics is as follows:
Fatal Exception: java.lang.IllegalStateException
at android.media.MediaPlayer._setDataSource(MediaPlayer.java)
at android.media.MediaPlayer.setDataSource(MediaPlayer.java:1270)
at com.example.home.MediaPlayerHolder.loadMedia(MediaPlayerHolder.kt:56)
at com.example.home.HomePresenter.playSound(HomePresenter.kt:26)
at com.example.home.HomeFragment.onPlaySelected(HomeFragment.kt:178)
at com.example.home.SoundItemAdapter$ViewHolder$bind$1.onClick(SoundItemAdapter.kt:30)
package names were changed for privacy reasons
This is happening almost every time he clicks on the sound item play button. It also happens on the first time he clicks on any sound item.
I've tried to reproduce this crash on some devices, all of then have API <= 25, but I had no success doing so. All of them ran without an issue. I'm clueless of the probable cause of this error, or even if it's an edge case problem, or if there's indeed something wrong with my code.
This is how I'm loading the audio on the MediaPlayer:
if (mediaPlayer?.isPlaying == true) {
mediaPlayer?.release()
mediaPlayer = null
}
if (mediaPlayer == null) {
mediaPlayer = MediaPlayer()
}
val fileDescriptor = context.resources.openRawResourceFd(resource)
mediaPlayer?.setDataSource(fileDescriptor.fileDescriptor, fileDescriptor.startOffset, fileDescriptor.length)
fileDescriptor.close()
mediaPlayer?.prepare()
mediaPlayer?.start()
The reason was you can't start services in the background anymore after API 26. So you have to start ForegroundService above API 26.

Voice Call Recording in Android 5.1

I have an application whcih records incoming and outgoing voice calls and it is working fine on devices with marshmallow or higher versions.But when i tried running it on android 5.1.1 it gives me error and app stops responding.
The error shown in logcat is-ava.lang.RuntimeException: Unable to start service com.android.hitech.calls.Unused.MyRecordingService#2cb0b090 with Intent { cmp=com.android.hitech.calls/.Unused.MyRecordingService (has extras) }: java.lang.IllegalStateException
at android.app.ActivityThread.handleServiceArgs(ActivityThread.java:2925)
at android.app.ActivityThread.access$2100(ActivityThread.java:151)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1408)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:135)
at android.app.ActivityThread.main(ActivityThread.java:5268)
at java.lang.reflect.Method.invoke(Native Method)
at java.lang.reflect.Method.invoke(Method.java:372)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:902)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:697)
Caused by: java.lang.IllegalStateException
at android.media.MediaRecorder.start(Native Method)
at com.android.hitech.calls.Unused.MyRecordingService.onStartCommand(MyRecordingservice.java:88)
at android.app.ActivityThread.handleServiceArgs(ActivityThread.java:2908)
My code for recording the voice calls is-
recorder = new MediaRecorder();
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
System.out.println("Present in MIC");
recorder.setAudioSource(MediaRecorder.AudioSource.MIC);
} else {
recorder.setAudioSource(MediaRecorder.AudioSource.VOICE_CALLS);
}
recorder.setOutputFormat(MediaRecorder.OutputFormat.MPEG_4);
recorder.setAudioEncoder(MediaRecorder.AudioEncoder.AAC);
recorder.setAudioEncodingBitRate(16);
recorder.setAudioSamplingRate(44100);
recorder.setOnErrorListener(this);
recorder.setOnInfoListener(this);
try {
recorder.prepare();
recorder.start();
} catch (IOException e) {
e.printStackTrace();
}
Edit- I did as suggested in the answer below but i am the error is still there.The call state is being called only once now by tweaking code a little bit but the app still crashes and even exception is the same.
Because in android 5.1 android system triggers CALL_STATE twice every time...!! i.e. once your NEW_OUTGOING_CALL is started or if any incoming call STATE_RINGING , STATE_ONHOOK and STATE_IDLE gets triggered twice..!! You have to manage it via code.
You can find reference what the problem is over 5.1 here... This is causing error

Getting a lot of crashes from android youtube player api

I am using version 1.2.1 (tried with latest version 1.2.2) of android's youtube player api. It works fine on most of the devices. However now and then, I keep on getting crashes on crashlytics. I am getting the following crashes
Fatal Exception: java.lang.IllegalStateException: android.os.TransactionTooLargeException
at com.google.android.youtube.api.jar.client.RemoteEmbeddedPlayer.x(SourceFile:558)
at bpd.w(SourceFile:576)
at tef.onTransact(SourceFile:390)
at android.os.Binder.transact(Binder.java:395)
at com.google.android.youtube.player.internal.d$a$a.r(Unknown Source)
at com.google.android.youtube.player.internal.s.h(Unknown Source)
at com.google.android.youtube.player.YouTubePlayerView.e(Unknown Source)
at com.google.android.youtube.player.YouTubePlayerSupportFragment.onSaveInstanceState(Unknown Source)
at android.support.v4.app.Fragment.performSaveInstanceState(Fragment.java:1936)
at android.support.v4.app.FragmentManagerImpl.saveFragmentBasicState(FragmentManager.java:1654)
at android.support.v4.app.FragmentManagerImpl.saveAllState(FragmentManager.java:1722)
at android.support.v4.app.Fragment.performSaveInstanceState(Fragment.java:1938)
at android.support.v4.app.FragmentManagerImpl.saveFragmentBasicState(FragmentManager.java:1654)
at android.support.v4.app.FragmentManagerImpl.saveAllState(FragmentManager.java:1722)
at android.support.v4.app.FragmentActivity.onSaveInstanceState(FragmentActivity.java:527)
at com.newshunt.news.activities.NewsBaseActivity.onSaveInstanceState(NewsBaseActivity.java:56)
at com.newshunt.news.activities.NewsDetailsActivity.onSaveInstanceState(NewsDetailsActivity.java:613)
at android.app.Activity.performSaveInstanceState(Activity.java:1388)
at android.app.Instrumentation.callActivityOnSaveInstanceState(Instrumentation.java:1286)
at android.app.ActivityThread.callCallActivityOnSaveInstanceState(ActivityThread.java:4588)
at android.app.ActivityThread.performStopActivityInner(ActivityThread.java:3960)
at android.app.ActivityThread.handleStopActivity(ActivityThread.java:4023)
at android.app.ActivityThread.access$1200(ActivityThread.java:181)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1498)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:145)
at android.app.ActivityThread.main(ActivityThread.java:6117)
at java.lang.reflect.Method.invoke(Method.java)
at java.lang.reflect.Method.invoke(Method.java:372)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1399)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1194)
Also getting crashes for the following exception.
Fatal Exception: java.lang.IllegalStateException: android.os.DeadObjectException
at com.google.android.apps.youtube.api.jar.a.eo.surfaceDestroyed(SourceFile:236)
at android.view.SurfaceView.updateWindow(SurfaceView.java:589)
at android.view.SurfaceView.onWindowVisibilityChanged(SurfaceView.java:237)
at android.view.View.dispatchDetachedFromWindow(View.java:12854)
at android.view.ViewGroup.dispatchDetachedFromWindow(ViewGroup.java:2757)
at android.view.ViewGroup.dispatchDetachedFromWindow(ViewGroup.java:2757)
at android.view.ViewGroup.removeViewInternal(ViewGroup.java:3844)
at android.view.ViewGroup.removeViewInternal(ViewGroup.java:3819)
at android.view.ViewGroup.removeView(ViewGroup.java:3751)
at com.google.android.youtube.player.YouTubePlayerView$1.b(Unknown Source)
at com.google.android.youtube.player.internal.r.h(Unknown Source)
at com.google.android.youtube.player.internal.r$e.onServiceDisconnected(Unknown Source)
at android.app.LoadedApk$ServiceDispatcher.doDeath(LoadedApk.java:1111)
at android.app.LoadedApk$ServiceDispatcher$RunConnection.run(LoadedApk.java:1125)
at android.os.Handler.handleCallback(Handler.java:725)
at android.os.Handler.dispatchMessage(Handler.java:92)
at android.os.Looper.loop(Looper.java:176)
at android.app.ActivityThread.main(ActivityThread.java:5317)
at java.lang.reflect.Method.invokeNative(Method.java)
at java.lang.reflect.Method.invoke(Method.java:511)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1102)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:869)
at dalvik.system.NativeStart.main(NativeStart.java)
The crash happens to appear in specific versions of youtube application like 5.2.27. Although there are a lot of issues filed for these crashes, there has been no reply from the youtube developers on how to mitigate this issue.
Some of the fellow developers have suggested the following workarounds
1) Use loadVideo instead of cueVideo. But I cannot use this workaround because loadVideo always autoplays the video which is not a requirement of my application. Also someone mentioned that with loadVideo also, this problem is happening although in some different version.
2) Put check in the code to check the youtube application version and then put the specific code. Now the problem with this approach is that I have to check each and every version of youtube app ever released and check which versions are causing the issue which is not a good workaround.
Now is there any fix which I can apply to avoid this issue or are the youtube developers planning to release some jar which internally takes care of all these issues?
I reduced the bug occurrence by putting youtube calls (like youtubePlayer.loadVideo(), cueVideo(), getCurrentTimeMillis() etc.) in a try catch block and catch the IllegalStateException exception then reinitialize youtube player.
To create a new instance of the YoutubePlayer just call the initialize() method in the catch block.
Example:
if (youtubePlayer != null) {
try {
youtubePlayer.loadVideo(videoId);
} catch (IllegalStateException e) {
initialize(API_KEY, this);
}
}
but the bug still occurred , I worked around it by catching these exceptions and restart activity. This uncaught exceptions and to catch them you need to use UncaughtExceptionHandler
example :
private Thread.UncaughtExceptionHandler defaultUEH;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
defaultUEH = Thread.getDefaultUncaughtExceptionHandler();
// setup handler for uncaught exception
Thread.setDefaultUncaughtExceptionHandler(_unCaughtExceptionHandler);
}
private Thread.UncaughtExceptionHandler _unCaughtExceptionHandler =
new Thread.UncaughtExceptionHandler() {
#Override
public void uncaughtException(Thread thread, Throwable ex) {
Log.e(TAG, "uncaughtException: ", ex);
PendingIntent myActivity = PendingIntent.getActivity(getApplicationContext(),
192837, new Intent(getApplicationContext(), MainActivity.class),
PendingIntent.FLAG_ONE_SHOT);
AlarmManager alarmManager;
alarmManager = (AlarmManager)getSystemService(Context.ALARM_SERVICE);
alarmManager.set(AlarmManager.ELAPSED_REALTIME_WAKEUP,
15000, myActivity );
System.exit(2);
// re-throw critical exception further to the os (important)
defaultUEH.uncaughtException(thread, ex);
}
};
The android YouTube Player API is not stable, there are known bugs in it. The team from YouTube said that they will release a new version of the library.
For now, the best solution I have found is to build my own library.

Android Wear Watchface and the WakeLock

I'm developing a watchface for Android Wear using the WatchFace API (extending CanvasWatchFaceService).
I've used the code from here to build a ticker that run code every second.
I'm experiencing the following problem. Every now and then the service crashes with this exception. I can't understand where it comes from, if you have any lead I'll post additional code.
01-06 11:22:00.247 12965-12965/com.my.package E/AndroidRuntime﹕ FATAL EXCEPTION: main
Process: com.my.package, PID: 12965
java.lang.NullPointerException: Attempt to invoke virtual method 'void android.os.PowerManager$WakeLock.acquire()' on a null object reference
at android.support.wearable.watchface.WatchFaceService$Engine.onCommand(WatchFaceService.java:201)
at android.service.wallpaper.WallpaperService$Engine.doCommand(WallpaperService.java:977)
at android.service.wallpaper.WallpaperService$IWallpaperEngineWrapper.executeMessage(WallpaperService.java:1191)
at com.android.internal.os.HandlerCaller$MyHandler.handleMessage(HandlerCaller.java:37)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:135)
at android.app.ActivityThread.main(ActivityThread.java:5221)
at java.lang.reflect.Method.invoke(Native Method)
at java.lang.reflect.Method.invoke(Method.java:372)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:899)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:694)
After this crash the watchface stops working and to make it start again I have to choose another watchface, then reselect mine, so it's a total show stopper!
Props to David for the lead on super. calls - it turns out that was the problem. Specifically, the CanvasWatchFaceService.Engine.onCreate method needs to call through to its ancestor, as such:
private class Engine extends CanvasWatchFaceService.Engine {
#Override
public void onCreate(SurfaceHolder holder) {
super.onCreate(holder);
// your engine initialization code here
}
// other watch face engine code
}
Without the super.onCreate(holder); call, my watch face would crash within minutes; with it, it happily ran overnight.
As an aside, this is something missing from the Android developer documentation; specifically, the Training page for Building a Watch Face Service doesn't include this ancestor call in its code sample.
The code you linked lacks some important parts, that are dotted. I.e. have you defined the update rate?
private static final long INTERACTIVE_UPDATE_RATE_MS = TimeUnit.SECONDS.toMillis(1);
Fully implemented it works well. See AnalogWatchFaceService in code samples: Wearable/Watchface face.

Categories

Resources