I'm new to Android and Java development and am looking for some guidance in setting up a simple soundboard app. What I am trying to do and am having issues in getting it working effectively is handling events for multiple mediaplayers.
For example I am creating a soundboard whereby when I click a button I want all other sounds to be stopped and released from memory and the button I have just pressed to play its assigned sound. I realise that repeating code blocks is not a good programming approach, but I have tried this with arrays and switch statements too with little effect. Any guidance on how to effectively release sounds from memory when using multiple MediaPlayers would be very useful to me. I have included my code below for 4 buttons (I have over 30 on this app)
public class MainActivity extends AppCompatActivity {
private MediaPlayer Meow1,Meow2,Meow3,Meow4;
private Button meowButton1,meowButton2,meowButton3,meowButton4;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Meow1 = new MediaPlayer();
Meow1 = MediaPlayer.create(getApplicationContext(), R.raw.meow1);
// final Boolean Meow1Pause = !Meow1.isPlaying() && Meow1.getCurrentPosition() >1;
meowButton1 = (Button) findViewById(R.id.Meow1);
meowButton1.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
if (Meow1.isPlaying())
{ pauseMusic1();
} else {
Meow1.start();
}}
});
Meow1.setOnCompletionListener(new MediaPlayer.OnCompletionListener() {
#Override
public void onCompletion(MediaPlayer Meow1) {
Meow1.stop();
Meow1.reset();
Meow1.release();
}
});
Meow2 = new MediaPlayer();
Meow2 = MediaPlayer.create(getApplicationContext(), R.raw.meow2);
meowButton2 = (Button) findViewById(R.id.Meow2);
meowButton2.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
if (Meow2.isPlaying() ){
pauseMusic();
} else {
Meow2.start();
}}
});
Meow2.setOnCompletionListener(new MediaPlayer.OnCompletionListener() {
#Override
public void onCompletion(MediaPlayer Meow1) {
Meow2.stop();
Meow2.reset();
Meow2.release();
}
});
Meow3 = new MediaPlayer();
Meow3 = MediaPlayer.create(getApplicationContext(), R.raw.meow3);
meowButton3 = (Button) findViewById(R.id.Meow3);
meowButton3.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
if (Meow3.isPlaying())
{ pauseMusic();
} else {
Meow3.start();
}}
});
Meow3.setOnCompletionListener(new MediaPlayer.OnCompletionListener() {
#Override
public void onCompletion(MediaPlayer Meow1) {
Meow3.stop();
Meow3.reset();
Meow3.release();
}
});
Meow4 = new MediaPlayer();
Meow4 = MediaPlayer.create(getApplicationContext(), R.raw.meow4);
meowButton4 = (Button) findViewById(R.id.Meow4);
meowButton4.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
if (Meow4.isPlaying())
{ pauseMusic();
} else {
Meow4.start();
}}
});
}
public void pauseMusic() {
if(Meow1 != null && Meow1.isPlaying()) Meow1.pause();
if(Meow2 != null && Meow2.isPlaying()) Meow2.pause();
if(Meow3 != null && Meow3.isPlaying()) Meow3.pause();
if(Meow4 != null && Meow4.isPlaying()) Meow4.pause();
}
}
Run Compiler:
A: Logging event (FE): screen_view(_vs), Bundle[{firebase_event_origin(_o)=auto, firebase_previous_class(_pc)=SplashScreen, firebase_previous_id(_pi)=-6549553702477848745, firebase_screen_class(_sc)=MainActivity, firebase_screen_id(_si)=-6549553702477848744}]
I/zygote: Do partial code cache collection, code=124KB, data=67KB
I/zygote: After code cache collection, code=124KB, data=67KB
I/zygote: Increasing code cache capacity to 512KB
V/FA: Activity resumed, time: 6376787
D/EGL_emulation: eglMakeCurrent: 0x980fde60: ver 3 0 (tinfo 0xa3c3c290)
D/EGL_emulation: eglMakeCurrent: 0x980fde60: ver 3 0 (tinfo 0xa3c3c290)
D/EGL_emulation: eglMakeCurrent: 0x980fde60: ver 3 0 (tinfo 0xa3c3c290)
I/chatty: uid=10085(u0_a85) RenderThread identical 2 lines
D/EGL_emulation: eglMakeCurrent: 0x980fde60: ver 3 0 (tinfo 0xa3c3c290)
V/FA: Inactivity, disconnecting from the service
V/MediaPlayer: resetDrmState: mDrmInfo=null mDrmProvisioningThread=null mPrepareDrmInProgress=false mActiveDrmScheme=false
cleanDrmObj: mDrmObj=null mDrmSessionId=null
V/MediaPlayer: resetDrmState: mDrmInfo=null mDrmProvisioningThread=null mPrepareDrmInProgress=false mActiveDrmScheme=false
cleanDrmObj: mDrmObj=null mDrmSessionId=null
D/TAG1: Button 2 pressed
D/AndroidRuntime: Shutting down VM
E/AndroidRuntime: FATAL EXCEPTION: main
Process: g.convery.cat_sounds, PID: 12276
java.lang.IllegalStateException
at android.media.MediaPlayer.isPlaying(Native Method)
at g.convery.cat_sounds.MainActivity$1.onClick(MainActivity.java:97)
at android.view.View.performClick(View.java:6256)
at android.view.View$PerformClick.run(View.java:24701)
at android.os.Handler.handleCallback(Handler.java:789)
at android.os.Handler.dispatchMessage(Handler.java:98)
at android.os.Looper.loop(Looper.java:164)
at android.app.ActivityThread.main(ActivityThread.java:6541)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.Zygote$MethodAndArgsCaller.run(Zygote.java:240)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:767)
W/MediaPlayer-JNI: MediaPlayer finalized without being released
W/MediaPlayer-JNI: MediaPlayer finalized without being released
Application terminated.
LOGCAT:
05-31 09:21:30.099 12276-12288/g.convery.cat_sounds W/MediaPlayer-JNI: MediaPlayer finalized without being released
05-31 09:21:30.211 12276-12288/g.convery.cat_sounds I/chatty: uid=10085(u0_a85) FinalizerDaemon identical 33 lines
05-31 09:21:30.212 12276-12288/g.convery.cat_sounds W/MediaPlayer-JNI: MediaPlayer finalized without being released
05-31 09:21:30.283 12276-12284/g.convery.cat_sounds I/zygote: Do partial code cache collection, code=124KB, data=67KB
05-31 09:21:30.286 12276-12284/g.convery.cat_sounds I/zygote: After code cache collection, code=124KB, data=67KB
05-31 09:21:30.287 12276-12284/g.convery.cat_sounds I/zygote: Increasing code cache capacity to 512KB
05-31 09:21:31.159 12276-12307/g.convery.cat_sounds I/chatty: uid=10085(u0_a85) RenderThread identical 2 lines
05-31 09:24:41.746 12276-12276/g.convery.cat_sounds E/AndroidRuntime: FATAL EXCEPTION: main
Process: g.convery.cat_sounds, PID: 12276
java.lang.IllegalStateException
at android.media.MediaPlayer.isPlaying(Native Method)
at g.convery.cat_sounds.MainActivity$1.onClick(MainActivity.java:97)
at android.view.View.performClick(View.java:6256)
at android.view.View$PerformClick.run(View.java:24701)
at android.os.Handler.handleCallback(Handler.java:789)
at android.os.Handler.dispatchMessage(Handler.java:98)
at android.os.Looper.loop(Looper.java:164)
at android.app.ActivityThread.main(ActivityThread.java:6541)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.Zygote$MethodAndArgsCaller.run(Zygote.java:240)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:767)
05-31 09:24:47.955 12276-12288/g.convery.cat_sounds W/MediaPlayer-JNI: MediaPlayer finalized without being released
05-31 09:24:47.956 12276-12288/g.convery.cat_sounds W/MediaPlayer-JNI: MediaPlayer finalized without being released
You are using the media player after releasing it. Remove these lines from your onCompletionListener and add them to onDestroy of your activity instead
Meow1.release();
Meow2.release();
Meow3.release();
Meow4.release();
Also calling create automatically creates a new instance, you can remove these lines as well
Meow1 = new MediaPlayer();
Meow2 = new MediaPlayer();
Meow3 = new MediaPlayer();
Meow4 = new MediaPlayer();
A better approach would be to use a single media player and just change the datesource when ever user wants to play different source, but this method will take some time before it plays the audio as it will prepare the audio everytime, this would be negligible unless your audio size is quite huge
Look how you're controlling your media now:
if (Meow4.isPlaying()) {
pauseMusic();
} else {
Meow4.start();
}
The first time you call Meow4.isPlaying() you will receive IllegalStateException because your player is not initialized.
Look how your MediaPlayer state is defined and call appropriate function
The second point, when you encounter a duplicate block, you should think of a function.
Meow3 = new MediaPlayer();
Meow3 = MediaPlayer.create(getApplicationContext(), R.raw.meow3);
meowButton3 = (Button) findViewById(R.id.Meow3);
meowButton3.setOnClickListener(new View.OnClickListener() {
});
meowButton3.setOnCompletionListener...
in a function: registerPlayer(Context context, int resourceId, Button controlButton)
Or with higher level of abstraction, create a subclass of `MediaPlayer` and wrap these logic inside it
Definitely you don't want to Meow1.pause() over and over. Instead, store your MeoX in a list then loop over it:
List<MediaPlayer> players = new ArrayList<>();
players.add(Meow1);
....
public void pauseMusic() {
players.stream().filter(p -> p != null && p.isPlaying()).forEach(p -p.pause());
}
Related
I used the code from this link MediaSession onMediaButtonEvent works for a few seconds then quits - Android to capture the keyevents of the remote button and send it to the audio() function where the selection will be played by another mediaplayer.
I run into the same problems where the code will crash after a few seconds. I so far tried to do a loop and also made the audio track not to do at.stop() or do at.release but eventually it still crashes. This keeps the service alive for a bit but then will still crash. I have the code and logcat
public class PlayerService extends Service {
private MediaSessionCompat mediaSession;
AudioTrack at;
#Override
public void onCreate() {
super.onCreate();
MediaSession ms = new MediaSession(getApplicationContext(), getPackageName());
ms.setActive(true);
ms.setCallback(new MediaSession.Callback() {
#Override
public boolean onMediaButtonEvent(Intent mediaButtonIntent) {
KeyEvent keyEvent = (KeyEvent) mediaButtonIntent.getExtras().get(Intent.EXTRA_KEY_EVENT);
if (keyEvent.getAction() == KeyEvent.ACTION_DOWN) {
switch (keyEvent.getKeyCode()) {
case KeyEvent.KEYCODE_MEDIA_FAST_FORWARD:
audio("button0");
break;
case KeyEvent.KEYCODE_MEDIA_REWIND:
audio("button1");
break;
case KeyEvent.KEYCODE_MEDIA_NEXT:
audio("button2");
break;
case KeyEvent.KEYCODE_MEDIA_PREVIOUS:
audio("button3");
break;
}
}
return super.onMediaButtonEvent(mediaButtonIntent);
}
});
Intent mediaButtonIntent = new Intent(Intent.ACTION_MEDIA_BUTTON);
PendingIntent mediaButtonReceiverPendingIntent = PendingIntent.getBroadcast(getApplicationContext(), 0, mediaButtonIntent, 0);
ms.setMediaButtonReceiver(mediaButtonReceiverPendingIntent);
at = new AudioTrack(AudioManager.STREAM_MUSIC, 48000, AudioFormat.CHANNEL_OUT_STEREO, AudioFormat.ENCODING_PCM_16BIT,
AudioTrack.getMinBufferSize(48000, AudioFormat.CHANNEL_OUT_STEREO, AudioFormat.ENCODING_PCM_16BIT), AudioTrack.MODE_STREAM);
**//at.setLoopPoints(3, 10,10000000);
at.play();
at.stop();
at.release();**
}
#Override
public IBinder onBind(Intent intent) {
return null;
}
#Override
public void onDestroy() {
super.onDestroy();
mediaSession.release();
}
public void audio(String command) {
MediaPlayer player = new MediaPlayer();
try {
switch (command) {
case "button0":
player = MediaPlayer.create(this, R.raw.button0);
break;
case "button1":
player = MediaPlayer.create(this, R.raw.button1);
break;
case "button2":
player = MediaPlayer.create(this, R.raw.button2);
break;
case "button3":
player = MediaPlayer.create(this, R.raw.button3);
break;
}
player.start();
Thread.sleep(1000);
} catch (Exception e) {
e.printStackTrace();
}
}
}
My logcat log
2022-02-13 19:08:01.568 19045-19060/com.example.medialistenercopy W/MediaPlayer-JNI: MediaPlayer finalized without being released
2022-02-13 19:08:01.568 19045-19060/com.example.medialistenercopy I/MediaPlayerNative: setListener
2022-02-13 19:08:01.569 19045-19060/com.example.medialistenercopy I/MediaPlayerNative: disconnect
2022-02-13 19:08:01.580 19045-19060/com.example.medialistenercopy I/MediaPlayerNative: destructor
2022-02-13 19:08:01.581 19045-19060/com.example.medialistenercopy I/MediaPlayerNative: disconnect
2022-02-13 19:08:56.467 19045-19045/com.example.medialistenercopy D/AndroidRuntime: Shutting down VM
--------- beginning of crash
2022-02-13 18:57:56.595 17903-17903/com.example.medialistenercopy E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.example.medialistenercopy, PID: 17903
java.lang.RuntimeException: Unable to stop service com.example.medialistenercopy.PlayerService#e1c144e: java.lang.NullPointerException: Attempt to invoke virtual method 'void android.support.v4.media.session.MediaSessionCompat.release()' on a null object reference
at android.app.ActivityThread.handleStopService(ActivityThread.java:3880)
at android.app.ActivityThread.access$1700(ActivityThread.java:208)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1733)
at android.os.Handler.dispatchMessage(Handler.java:106)
at android.os.Looper.loop(Looper.java:205)
at android.app.ActivityThread.main(ActivityThread.java:6991)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:493)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:884)
Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'void android.support.v4.media.session.MediaSessionCompat.release()' on a null object reference
at com.example.medialistenercopy.PlayerService.onDestroy(PlayerService.java:114)
at android.app.ActivityThread.handleStopService(ActivityThread.java:3860)
at android.app.ActivityThread.access$1700(ActivityThread.java:208)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1733)
at android.os.Handler.dispatchMessage(Handler.java:106)
at android.os.Looper.loop(Looper.java:205)
at android.app.ActivityThread.main(ActivityThread.java:6991)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:493)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:884)
2022-02-13 18:57:56.668 17903-17903/com.example.medialistenercopy I/Process: Sending signal. PID: 17903 SIG: 9
Is the problem because the fake audio track ended too soon or because I have another mediaplayer playing sounds too. I am tweeking everything I can.
I tried to tweek the audio track and I got
2022-02-13 20:58:55.609 27560-27560/com.example.medialistenercopy V/AudioTrack: getMinFrameCount=3844: afFrameCount=1920, afSampleRate=48000, afLatency=80
2022-02-13 20:58:55.610 27560-27560/com.example.medialistenercopy V/AudioTrack: set(): streamType -1, sampleRate 48000, format 0x1, channelMask 0x3, frameCount 3844, flags #0, notificationFrames 0, sessionId 0, transferType 3, uid -1, pid -1
2022-02-13 20:58:55.610 27560-27560/com.example.medialistenercopy V/AudioTrack: Building AudioTrack with attributes: usage=1 content=2 flags=0x0 tags=[]
2022-02-13 20:58:55.619 27560-27560/com.example.medialistenercopy W/AudioTrack: Use of stream types is deprecated for operations other than volume control
2022-02-13 20:58:55.619 27560-27560/com.example.medialistenercopy W/AudioTrack: See the documentation of AudioTrack() for what to use instead with android.media.AudioAttributes to qualify your playback use case
2022-02-13 20:58:55.625 27560-27560/com.example.medialistenercopy V/AudioTrack: ~AudioTrack, releasing session id 8857 from 27560 on behalf of 27560
2022-02-13 20:58:55.626 27560-27560/com.example.medialistenercopy W/MediaAnalyticsItem: Unable to record: [1:audiotrack:0:-1::0:-1:1:0:5:android.media.audiotrack.underrunframes=1922:android.media.audiotrack.type=AUDIO_CONTENT_TYPE_MUSIC:android.media.audiotrack.usage=AUDIO_USAGE_MEDIA:android.media.audiotrack.samplerate=48000:android.media.audiotrack.channelmask=3:] [forcenew=0]
The specific reason for your crash is likely because you do not assign the field mediaSession; you've instead assigned an instance of MediaSession to a variable in a function scope inside onCreate().
I would like to call out that we recommend handling the onPlay(), onPause(), onFastForward(), etc. callbacks from MediaSession.Callback, as opposed to implementing onMediaButtonEvent(). The reason for this, is that not all actions are provided as a media button, such as seek commands, ratings or custom actions.
For more information about media sessions, see also my contextual video on this topic and the dedicated codelab.
I created a small Softkeyboard for Android Studio and now want to add Speech to Text, but I am getting this error when I start the application in the logcat:
Attempt to invoke virtual method 'android.app.ActivityThread$ApplicationThread android.app.ActivityThread.getApplicationThread()' on a null object reference
at android.app.Activity.startActivityForResult(Activity.java:5174)
The Keyboard on itself and the Speech to Text on itself worked just fine.
Source Code:
package edmt.dev.androidcustomkeyboard;
import android.app.Activity;
import android.content.ActivityNotFoundException;
import android.content.Intent;
import android.inputmethodservice.InputMethodService;
import android.inputmethodservice.Keyboard;
import android.inputmethodservice.KeyboardView;
import android.media.AudioManager;
import android.os.Bundle;
import android.speech.RecognizerIntent;
import android.support.v7.app.AppCompatActivity;
import android.view.KeyEvent;
import android.view.View;
import android.view.inputmethod.InputConnection;
import android.widget.ImageButton;
import android.widget.TextView;
import java.util.ArrayList;
import java.util.Locale;
public class OrthKeyboard extends InputMethodService implements KeyboardView.OnKeyboardActionListener {
private KeyboardView kv;
private Keyboard keyboard;
public static SpeechInnerClass SpeechInnerClass;
private boolean isCaps = false;
public static String auto_word ="";
//Press Ctrl+O
#Override
public View onCreateInputView() {
kv = (KeyboardView)getLayoutInflater().inflate(R.layout.keyboard,null);
keyboard = new Keyboard(this,R.xml.qwerty);
kv.setKeyboard(keyboard);
kv.setOnKeyboardActionListener(this);
SpeechInnerClass = new SpeechInnerClass();
return kv;
}
#Override
public void onPress(int i) {
}
#Override
public void onRelease(int i) {
}
#Override
public void onKey(int i, int[] ints) {
InputConnection ic = getCurrentInputConnection();
playClick(i);
// MainActivity.count ++;
if(i==-4222522|i==-4222521|i==-4222523|i==-4222525){
if(i==-4222522){
ic.commitText("Case 2",1);
}
if(i==-4222521){
ic.commitText("Case 1",1);
}
if(i==-4222523){
ic.commitText("Case 3",1);
}
if(i==-4222525){
SpeechInnerClass.startVoiceInput();
ic.commitText(SpeechInnerClass.output,1);
}
}
else {
switch (i) {
case Keyboard.KEYCODE_DELETE:
ic.deleteSurroundingText(1, 0);
break;
case Keyboard.KEYCODE_SHIFT:
isCaps = !isCaps;
keyboard.setShifted(isCaps);
kv.invalidateAllKeys();
break;
case Keyboard.KEYCODE_DONE:
ic.sendKeyEvent(new KeyEvent(KeyEvent.ACTION_DOWN, KeyEvent.KEYCODE_ENTER));
break;
default:
char code = (char) i;
if (Character.isLetter(code) && isCaps)
code = Character.toUpperCase(code);
ic.commitText(String.valueOf(code), 1);
SettingsActivity.count++;
if ((char) i == ' ') {
auto_word = "";
}
if (96 < i && i < 123) {
auto_word = auto_word + (char) i;
}
}
}
}
private void playClick(int i) {
AudioManager am = (AudioManager)getSystemService(AUDIO_SERVICE);
switch(i)
{
case 32:
am.playSoundEffect(AudioManager.FX_KEYPRESS_SPACEBAR);
break;
case Keyboard.KEYCODE_DONE:
case 10:
am.playSoundEffect(AudioManager.FX_KEYPRESS_RETURN);
break;
case Keyboard.KEYCODE_DELETE:
am.playSoundEffect(AudioManager.FX_KEYPRESS_DELETE);
break;
default: am.playSoundEffect(AudioManager.FX_KEYPRESS_STANDARD);
}
}
#Override
public void onText(CharSequence charSequence) {
}
#Override
public void swipeLeft() {
}
#Override
public void swipeRight() {
}
#Override
public void swipeDown() {
}
#Override
public void swipeUp() {
}
public static class SpeechInnerClass extends AppCompatActivity {
private static final int REQ_CODE_SPEECH_INPUT = 100;
public static CharSequence output = "Test";
private TextView mVoiceInputTv;
private ImageButton mSpeakBtn;
public boolean voice = false;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
if(voice=true){
startVoiceInput();
}
}
public void startVoiceInput() {
Intent intent = new Intent(RecognizerIntent.ACTION_RECOGNIZE_SPEECH);
intent.putExtra(RecognizerIntent.EXTRA_LANGUAGE_MODEL, RecognizerIntent.LANGUAGE_MODEL_FREE_FORM);
intent.putExtra(RecognizerIntent.EXTRA_LANGUAGE, Locale.getDefault());
intent.putExtra(RecognizerIntent.EXTRA_PROMPT, "Hello, How can I help you?");
try {
startActivityForResult(intent, REQ_CODE_SPEECH_INPUT);
} catch (ActivityNotFoundException a) {
}
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
switch (requestCode) {
case REQ_CODE_SPEECH_INPUT: {
if (resultCode == RESULT_OK && null != data) {
ArrayList<String> result = data.getStringArrayListExtra(RecognizerIntent.EXTRA_RESULTS);
output=(result.get(0));
}
break;
}
}
}
}
}
Full Logcat:
2019-07-14 13:23:02.202 12121-12121/? D/libEGL: Emulator has host GPU support, qemu.gles is set to 1.
2019-07-14 13:23:02.211 12121-12121/? D/libEGL: loaded /vendor/lib/egl/libEGL_emulation.so
2019-07-14 13:23:02.214 12121-12121/? D/libEGL: loaded /vendor/lib/egl/libGLESv1_CM_emulation.so
2019-07-14 13:23:02.216 12121-12121/? D/libEGL: loaded /vendor/lib/egl/libGLESv2_emulation.so
2019-07-14 13:39:26.230 12121-12121/? I/dcustomkeyboar: Not late-enabling -Xcheck:jni (already on)
2019-07-14 13:39:26.247 12121-12121/? E/dcustomkeyboar: Unknown bits set in runtime_flags: 0x8000
2019-07-14 13:39:26.247 12121-12121/? W/dcustomkeyboar: Unexpected CPU variant for X86 using defaults: x86
2019-07-14 13:39:26.339 12121-12121/edmt.dev.androidcustomkeyboard I/dcustomkeyboar: The ClassLoaderContext is a special shared library.
2019-07-14 13:39:26.451 12121-12121/edmt.dev.androidcustomkeyboard W/dcustomkeyboar: JIT profile information will not be recorded: profile file does not exits.
2019-07-14 13:39:26.461 12121-12121/edmt.dev.androidcustomkeyboard I/chatty: uid=10132(edmt.dev.androidcustomkeyboard) identical 10 lines
2019-07-14 13:39:26.462 12121-12121/edmt.dev.androidcustomkeyboard W/dcustomkeyboar: JIT profile information will not be recorded: profile file does not exits.
2019-07-14 13:39:26.484 12121-12121/edmt.dev.androidcustomkeyboard I/InstantRun: starting instant run server: is main process
2019-07-14 13:39:26.725 12121-12920/edmt.dev.androidcustomkeyboard D/OpenGLRenderer: Swap behavior 1
2019-07-14 13:39:26.726 12121-12920/edmt.dev.androidcustomkeyboard W/OpenGLRenderer: Failed to choose config with EGL_SWAP_BEHAVIOR_PRESERVED, retrying without...
2019-07-14 13:39:26.727 12121-12920/edmt.dev.androidcustomkeyboard D/OpenGLRenderer: Swap behavior 0
2019-07-14 13:39:26.739 12121-12920/edmt.dev.androidcustomkeyboard D/eglCodecCommon: setVertexArrayObject: set vao to 0 (0) 0 0
2019-07-14 13:39:26.739 12121-12920/edmt.dev.androidcustomkeyboard D/EGL_emulation: eglCreateContext: 0xd85a7cc0: maj 2 min 0 rcv 2
2019-07-14 13:39:26.758 12121-12920/edmt.dev.androidcustomkeyboard D/EGL_emulation: eglMakeCurrent: 0xd85a7cc0: ver 2 0 (tinfo 0xc61374e0)
2019-07-14 13:39:26.778 12121-12920/edmt.dev.androidcustomkeyboard W/Gralloc3: mapper 3.x is not supported
2019-07-14 13:39:26.785 12121-12920/edmt.dev.androidcustomkeyboard D/OpenGLRenderer: Setting buffer count to 3, min_undequeued 1, extraBuffers 0
2019-07-14 13:39:26.814 12121-12920/edmt.dev.androidcustomkeyboard D/EGL_emulation: eglMakeCurrent: 0xd85a7cc0: ver 2 0 (tinfo 0xc61374e0)
2019-07-14 13:39:26.835 12121-12920/edmt.dev.androidcustomkeyboard D/eglCodecCommon: setVertexArrayObject: set vao to 0 (0) 1 0
2019-07-14 13:39:26.944 12121-12920/edmt.dev.androidcustomkeyboard D/EGL_emulation: eglMakeCurrent: 0xd85a7cc0: ver 2 0 (tinfo 0xc61374e0)
2019-07-14 13:39:26.964 12121-12920/edmt.dev.androidcustomkeyboard D/OpenGLRenderer: Setting buffer count to 3, min_undequeued 1, extraBuffers 0
2019-07-14 13:39:26.967 12121-12920/edmt.dev.androidcustomkeyboard D/EGL_emulation: eglMakeCurrent: 0xd85a7cc0: ver 2 0 (tinfo 0xc61374e0)
2019-07-14 13:39:34.439 12121-12920/edmt.dev.androidcustomkeyboard D/OpenGLRenderer: Setting buffer count to 3, min_undequeued 1, extraBuffers 0
2019-07-14 13:39:34.447 12121-12920/edmt.dev.androidcustomkeyboard D/EGL_emulation: eglMakeCurrent: 0xd85a7cc0: ver 2 0 (tinfo 0xc61374e0)
2019-07-14 13:39:34.484 12121-12121/edmt.dev.androidcustomkeyboard E/InputEventReceiver: Exception dispatching input event.
2019-07-14 13:39:34.484 12121-12121/edmt.dev.androidcustomkeyboard E/MessageQueue-JNI: Exception in MessageQueue callback: handleReceiveCallback
2019-07-14 13:39:34.489 12121-12121/edmt.dev.androidcustomkeyboard E/MessageQueue-JNI: java.lang.NullPointerException: Attempt to invoke virtual method 'android.app.ActivityThread$ApplicationThread android.app.ActivityThread.getApplicationThread()' on a null object reference
at android.app.Activity.startActivityForResult(Activity.java:5174)
at android.support.v4.app.BaseFragmentActivityApi16.startActivityForResult(BaseFragmentActivityApi16.java:54)
at android.support.v4.app.FragmentActivity.startActivityForResult(FragmentActivity.java:67)
at android.app.Activity.startActivityForResult(Activity.java:5131)
at android.support.v4.app.FragmentActivity.startActivityForResult(FragmentActivity.java:720)
at edmt.dev.androidcustomkeyboard.OrthKeyboard$SpeechInnerClass.startVoiceInput(OrthKeyboard.java:201)
at edmt.dev.androidcustomkeyboard.OrthKeyboard.onKey(OrthKeyboard.java:85)
at android.inputmethodservice.KeyboardView.detectAndSendKey(KeyboardView.java:847)
at android.inputmethodservice.KeyboardView.onModifiedTouchEvent(KeyboardView.java:1354)
at android.inputmethodservice.KeyboardView.onTouchEvent(KeyboardView.java:1217)
at android.view.View.dispatchTouchEvent(View.java:13417)
at android.view.ViewGroup.dispatchTransformedTouchEvent(ViewGroup.java:3060)
at android.view.ViewGroup.dispatchTouchEvent(ViewGroup.java:2755)
at android.view.ViewGroup.dispatchTransformedTouchEvent(ViewGroup.java:3060)
at android.view.ViewGroup.dispatchTouchEvent(ViewGroup.java:2755)
at android.view.ViewGroup.dispatchTransformedTouchEvent(ViewGroup.java:3060)
at android.view.ViewGroup.dispatchTouchEvent(ViewGroup.java:2755)
at android.view.ViewGroup.dispatchTransformedTouchEvent(ViewGroup.java:3060)
at android.view.ViewGroup.dispatchTouchEvent(ViewGroup.java:2755)
at android.view.ViewGroup.dispatchTransformedTouchEvent(ViewGroup.java:3060)
at android.view.ViewGroup.dispatchTouchEvent(ViewGroup.java:2755)
at com.android.internal.policy.DecorView.superDispatchTouchEvent(DecorView.java:460)
at com.android.internal.policy.PhoneWindow.superDispatchTouchEvent(PhoneWindow.java:1849)
at android.app.Dialog.dispatchTouchEvent(Dialog.java:861)
at android.inputmethodservice.SoftInputWindow.dispatchTouchEvent(SoftInputWindow.java:152)
at com.android.internal.policy.DecorView.dispatchTouchEvent(DecorView.java:418)
at android.view.View.dispatchPointerEvent(View.java:13676)
at android.view.ViewRootImpl$ViewPostImeInputStage.processPointerEvent(ViewRootImpl.java:5479)
at android.view.ViewRootImpl$ViewPostImeInputStage.onProcess(ViewRootImpl.java:5282)
at android.view.ViewRootImpl$InputStage.deliver(ViewRootImpl.java:4785)
at android.view.ViewRootImpl$InputStage.onDeliverToNext(ViewRootImpl.java:4838)
at android.view.ViewRootImpl$InputStage.forward(ViewRootImpl.java:4804)
at android.view.ViewRootImpl$AsyncInputStage.forward(ViewRootImpl.java:4944)
at android.view.ViewRootImpl$InputStage.apply(ViewRootImpl.java:4812)
at android.view.ViewRootImpl$AsyncInputStage.apply(ViewRootImpl.java:5001)
at android.view.ViewRootImpl$InputStage.deliver(ViewRootImpl.java:4785)
at android.view.ViewRootImpl$InputStage.onDeliverToNext(ViewRootImpl.java:4838)
at android.view.ViewRootImpl$InputStage.forward(ViewRootImpl.java:4804)
at android.view.ViewRootImpl$InputStage.apply(ViewRootImpl.java:4812)
at android.view.ViewRootImpl$InputStage.deliver(ViewRootImpl.java:4785)
at android.view.ViewRootImpl.deliverInputEvent(ViewRootImpl.java:7502)
at android.view.ViewRootImpl.doProcessInputEvents(ViewRootImpl.java:7471)
at android.view.ViewRootImpl.enqueueInputEvent(ViewRootImpl.java:7432)
at android.view.ViewRootImpl$WindowInputEventReceiver.onInputEvent(ViewRootImpl.java:7627)
at android.view.InputEventReceiver.dispatchInputEvent(InputEventReceiver.java:188)
at android.os.MessageQueue.nativePollOnce(Native Method)
at android.os.MessageQueue.next(MessageQueue.java:336)
at android.os.Looper.loop(Looper.java:174)
at android.app.ActivityThread.main(ActivityThread.java:7319)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(Runti
2019-07-14 13:39:34.489 12121-12121/edmt.dev.androidcustomkeyboard D/AndroidRuntime: Shutting down VM
2019-07-14 13:39:34.499 12121-12121/edmt.dev.androidcustomkeyboard E/AndroidRuntime: FATAL EXCEPTION: main
Process: edmt.dev.androidcustomkeyboard, PID: 12121
java.lang.NullPointerException: Attempt to invoke virtual method 'android.app.ActivityThread$ApplicationThread android.app.ActivityThread.getApplicationThread()' on a null object reference
at android.app.Activity.startActivityForResult(Activity.java:5174)
at android.support.v4.app.BaseFragmentActivityApi16.startActivityForResult(BaseFragmentActivityApi16.java:54)
at android.support.v4.app.FragmentActivity.startActivityForResult(FragmentActivity.java:67)
at android.app.Activity.startActivityForResult(Activity.java:5131)
at android.support.v4.app.FragmentActivity.startActivityForResult(FragmentActivity.java:720)
at edmt.dev.androidcustomkeyboard.OrthKeyboard$SpeechInnerClass.startVoiceInput(OrthKeyboard.java:201)
at edmt.dev.androidcustomkeyboard.OrthKeyboard.onKey(OrthKeyboard.java:85)
at android.inputmethodservice.KeyboardView.detectAndSendKey(KeyboardView.java:847)
at android.inputmethodservice.KeyboardView.onModifiedTouchEvent(KeyboardView.java:1354)
at android.inputmethodservice.KeyboardView.onTouchEvent(KeyboardView.java:1217)
at android.view.View.dispatchTouchEvent(View.java:13417)
at android.view.ViewGroup.dispatchTransformedTouchEvent(ViewGroup.java:3060)
at android.view.ViewGroup.dispatchTouchEvent(ViewGroup.java:2755)
at android.view.ViewGroup.dispatchTransformedTouchEvent(ViewGroup.java:3060)
at android.view.ViewGroup.dispatchTouchEvent(ViewGroup.java:2755)
at android.view.ViewGroup.dispatchTransformedTouchEvent(ViewGroup.java:3060)
at android.view.ViewGroup.dispatchTouchEvent(ViewGroup.java:2755)
at android.view.ViewGroup.dispatchTransformedTouchEvent(ViewGroup.java:3060)
at android.view.ViewGroup.dispatchTouchEvent(ViewGroup.java:2755)
at android.view.ViewGroup.dispatchTransformedTouchEvent(ViewGroup.java:3060)
at android.view.ViewGroup.dispatchTouchEvent(ViewGroup.java:2755)
at com.android.internal.policy.DecorView.superDispatchTouchEvent(DecorView.java:460)
at com.android.internal.policy.PhoneWindow.superDispatchTouchEvent(PhoneWindow.java:1849)
at android.app.Dialog.dispatchTouchEvent(Dialog.java:861)
at android.inputmethodservice.SoftInputWindow.dispatchTouchEvent(SoftInputWindow.java:152)
at com.android.internal.policy.DecorView.dispatchTouchEvent(DecorView.java:418)
at android.view.View.dispatchPointerEvent(View.java:13676)
at android.view.ViewRootImpl$ViewPostImeInputStage.processPointerEvent(ViewRootImpl.java:5479)
at android.view.ViewRootImpl$ViewPostImeInputStage.onProcess(ViewRootImpl.java:5282)
at android.view.ViewRootImpl$InputStage.deliver(ViewRootImpl.java:4785)
at android.view.ViewRootImpl$InputStage.onDeliverToNext(ViewRootImpl.java:4838)
at android.view.ViewRootImpl$InputStage.forward(ViewRootImpl.java:4804)
at android.view.ViewRootImpl$AsyncInputStage.forward(ViewRootImpl.java:4944)
at android.view.ViewRootImpl$InputStage.apply(ViewRootImpl.java:4812)
at android.view.ViewRootImpl$AsyncInputStage.apply(ViewRootImpl.java:5001)
at android.view.ViewRootImpl$InputStage.deliver(ViewRootImpl.java:4785)
at android.view.ViewRootImpl$InputStage.onDeliverToNext(ViewRootImpl.java:4838)
at android.view.ViewRootImpl$InputStage.forward(ViewRootImpl.java:4804)
at android.view.ViewRootImpl$InputStage.apply(ViewRootImpl.java:4812)
at android.view.ViewRootImpl$InputStage.deliver(ViewRootImpl.java:4785)
at android.view.ViewRootImpl.deliverInputEvent(ViewRootImpl.java:7502)
at android.view.ViewRootImpl.doProcessInputEvents(ViewRootImpl.java:7471)
at android.view.ViewRootImpl.enqueueInputEvent(ViewRootImpl.java:7432)
at android.view.ViewRootImpl$WindowInputEventReceiver.onInputEvent(ViewRootImpl.java:7627)
at android.view.InputEventReceiver.dispatchInputEvent(InputEventReceiver.java:188)
at android.os.MessageQueue.nativePollOnce(Native Method)
at android.os.MessageQueue.next(MessageQueue.java:336)
at android.os.Looper.loop(Looper.java:174)
at android.app.ActivityThread.main(ActivityThread.java:7319)
2019-07-14 13:39:34.500 12121-12121/edmt.dev.androidcustomkeyboard E/AndroidRuntime: at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:492)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:934)
try it
runOnUiThread(new Runnable() {
#Override
public void run() {
//Code
}
});
I'm creating a screen lock app, and faced notification able to drag down in the lock screen.
I've research it and found this solution to block the notification bar by using addView code below, but I cannot remove the view after user unlocked my app. Please advice how to remove the view.
I've try to use manager.removeView(view); in public void onDestroy() { but it crashed after run this code.
This is the error message
FATAL EXCEPTION: main
Process: com.mehuljoisar.lockscreen, PID: 10256
java.lang.IllegalArgumentException: View=android.view.View{42348cc0 V.ED.... ........ 0,0-0,0} not attached to window manager
at android.view.WindowManagerGlobal.findViewLocked(WindowManagerGlobal.java:373)
at android.view.WindowManagerGlobal.removeView(WindowManagerGlobal.java:302)
at android.view.WindowManagerImpl.removeView(WindowManagerImpl.java:79)
at com.mehuljoisar.lockscreen.LockScreenActivity.disablePullNotificationTouch(LockScreenActivity.java:261)
at com.mehuljoisar.lockscreen.LockScreenActivity.access$100(LockScreenActivity.java:24)
at com.mehuljoisar.lockscreen.LockScreenActivity$2.onClick(LockScreenActivity.java:113)
at android.view.View.performClick(View.java:4469)
at android.view.View$PerformClick.run(View.java:18788)
at android.os.Handler.handleCallback(Handler.java:808)
at android.os.Handler.dispatchMessage(Handler.java:103)
at android.os.Looper.loop(Looper.java:193)
at android.app.ActivityThread.main(ActivityThread.java:5347)
at java.lang.reflect.Method.invokeNative(Native Method)
at java.lang.reflect.Method.invoke(Method.java:515)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:835)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:651)
at dalvik.system.NativeStart.main(Native Method)
Where should I put the removeView code?
private void disablePullNotificationTouch(String gg) {
WindowManager manager = ((WindowManager) getApplicationContext().getSystemService(Context.WINDOW_SERVICE));
WindowManager.LayoutParams localLayoutParams = new WindowManager.LayoutParams();
localLayoutParams.type = WindowManager.LayoutParams.TYPE_SYSTEM_ERROR;
localLayoutParams.gravity = Gravity.TOP; //make the line top
localLayoutParams.flags = WindowManager.LayoutParams.FLAG_NOT_FOCUSABLE |
// this is to enable the notification to recieve touch events
WindowManager.LayoutParams.FLAG_NOT_TOUCH_MODAL |
// Draws over status bar
WindowManager.LayoutParams.FLAG_LAYOUT_IN_SCREEN;
localLayoutParams.width = WindowManager.LayoutParams.MATCH_PARENT;
localLayoutParams.height = (int) (25 * getResources().getDisplayMetrics().scaledDensity);
localLayoutParams.format = PixelFormat.RGBX_8888;
View view = new View(this);
if(gg == "on") {
manager.addView(view, localLayoutParams);
}else {
manager.removeView(view);
}
}
#Override
public void onCreate(Bundle savedInstanceState) {
disablePullNotificationTouch("on");
}
#Override
public void onDestroy() {
super.onDestroy();
disablePullNotificationTouch("off");
}
You use
WindowManager manager = ((WindowManager) this.getSystemService(Context.WINDOW_SERVICE));
Not use
WindowManager manager = ((WindowManager) getApplicationContext().getSystemService(Context.WINDOW_SERVICE));
Try it!
I'm trying to send an ArrayList to my Android Wear device from the mobile device.
Unfortunately I'm not getting past the mGoogleApiClient.connect() as per my sop statements.
What I've done is set up a DataLayer item and used the onDataChanged() to monitor the code and the DataItem being sent with it, but unfortunately it seems like nothing is getting across.
Console output is at the bottom of the post, if that helps pinpoint anything.
MAIN ACTIVITY - MOBILE
public class MainActivity extends AppCompatActivity implements GoogleApiClient.ConnectionCallbacks, GoogleApiClient.OnConnectionFailedListener {
Set<String> tasksSet;
ArrayList<String> actsList;
ArrayAdapter adapter;
ListView list;
GoogleApiClient mGoogleApiClient;
#Override
protected void onCreate(Bundle savedInstanceState) {
mGoogleApiClient = new GoogleApiClient.Builder(this)
.addConnectionCallbacks(this)
.addOnConnectionFailedListener(this)
.addApi(Wearable.API)
.build();
mGoogleApiClient.connect();
if(!PreferenceManager.getDefaultSharedPreferences(this)
.getStringSet("wristaroo", new HashSet<String>()).isEmpty()) {
tasksSet = PreferenceManager.getDefaultSharedPreferences(this)
.getStringSet("wristaroo", new HashSet<String>());
actsList = new ArrayList<String>(tasksSet);
}
else {
actsList = new ArrayList<>();
Set<String> tasksSet = new HashSet<>(actsList);
PreferenceManager.getDefaultSharedPreferences(this)
.edit()
.putStringSet("wristaroo", tasksSet)
.commit();
}
xxxxxxx
other populating code
xxxxxxx
Button btnSend = (Button) findViewById(R.id.sendButton);
btnSend.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
sendCustomSchedule(actsList);
System.out.println("Button Pressed: Send");
}
});
}
private void populateListView() {
list = (ListView) findViewById(R.id.listViewAdd);
list.setAdapter(adapter);
}
public MainActivity getActivity() {
return this;
}
#Override
public void onConnected(#Nullable Bundle bundle) {
}
#Override
public void onConnectionSuspended(int i) {
}
#Override
public void onConnectionFailed(#NonNull ConnectionResult connectionResult) {
}
public void sendCustomSchedule(ArrayList<String> customSchedule) {
PutDataMapRequest putDataMapRequest = PutDataMapRequest.create("/customSched");
putDataMapRequest.getDataMap().putStringArrayList("customSched", customSchedule);
PutDataRequest request = putDataMapRequest.asPutDataRequest().setUrgent();
Wearable.DataApi.putDataItem(mGoogleApiClient, request)
.setResultCallback(new ResultCallback<DataApi.DataItemResult>() {
#Override
public void onResult(#NonNull DataApi.DataItemResult dataItemResult) {
if(!dataItemResult.getStatus().isSuccess()) {
System.out.println("Apparent Failure!");
} else {
System.out.println("Apparent Success!");
}
}
});
System.out.println("When in doubt...");
}
}
MAIN ACTIVITY - WEAR
public class byTimeActivity extends Activity implements DataApi.DataListener,GoogleApiClient.ConnectionCallbacks, GoogleApiClient.OnConnectionFailedListener {
ArrayList<String> choicesList;
ArrayAdapter adapter;
ListView list;
ArrayList<String> data;
String dayExtra;
String howExtra;
String schedExtra;
GoogleApiClient mGoogleApiClient;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
mGoogleApiClient = new GoogleApiClient.Builder(this)
.addConnectionCallbacks(this)
.addOnConnectionFailedListener(this)
.addApi(Wearable.API)
.build();
mGoogleApiClient.connect();
setContentView(R.layout.activity_main);
final WatchViewStub stub = (WatchViewStub) findViewById(R.id.watch_view_stub);
dayExtra = getIntent().getExtras().getString("dayExtra");
schedExtra = getIntent().getExtras().getString("schedExtra");
howExtra = getIntent().getExtras().getString("howExtra");
System.out.println("dayExtra: " + dayExtra);
System.out.println("schedExtra: " + schedExtra);
System.out.println("howExtra: " + howExtra);
switch(dayExtra) {
case "Thursday":
if(schedExtra.equals("Full Schedule")) {
setStage(thTime);
}
if(schedExtra.equals("Custom Schedule")) {
adapter = new ArrayAdapter<>(this, R.layout.da_item, data);
}
break;
case "Friday":
setStage(frTime);
break;
case "Saturday":
setStage(saTime);
break;
case "Sunday":
setStage(suTime);
break;
}
stub.setOnLayoutInflatedListener(new WatchViewStub.OnLayoutInflatedListener() {
#Override
public void onLayoutInflated(WatchViewStub stub) {
list = (ListView) findViewById(R.id.mainChoiceList);
list.setAdapter(adapter);
}
});
}
private void setStage(String[] dayStage) {
choicesList = new ArrayList<>(Arrays.asList(dayStage));
adapter = new ArrayAdapter<>(this, R.layout.da_item, choicesList);
adapter.notifyDataSetChanged();
}
#Override
protected void onResume() {
super.onResume();
mGoogleApiClient.connect();
}
#Override
public void onConnected(#Nullable Bundle bundle) {
Wearable.DataApi.addListener(mGoogleApiClient, this);
}
#Override
protected void onPause() {
super.onPause();
Wearable.DataApi.removeListener(mGoogleApiClient, this);
mGoogleApiClient.disconnect();
}
#Override
public void onConnectionSuspended(int i) {
}
#Override
public void onDataChanged(DataEventBuffer dataEvents) {
for (DataEvent event : dataEvents) {
if (event.getType() == DataEvent.TYPE_CHANGED) {
DataItem item = event.getDataItem();
if (item.getUri().getPath().compareTo("/customSched") == 0) {
DataMap dataMap = DataMapItem.fromDataItem(item).getDataMap();
data = dataMap.getStringArrayList("customSched");
System.out.println("Data: " + data);
}
} else if (event.getType() == DataEvent.TYPE_DELETED) {
//dataItem Deleted
}
}
}
#Override
public void onConnectionFailed(#NonNull ConnectionResult connectionResult) {
}
}
CONSOLE OUTPUT - MOBILE
W/System: ClassLoader referenced unknown path: /data/app/com.michaeldvinci.conedmiro.schedaroo-2/lib/arm
I/GMPM: App measurement is starting up, version: 8487
I/GMPM: To enable debug logging run: adb shell setprop log.tag.GMPM VERBOSE
E/GMPM: GoogleService failed to initialize, status: 10, Missing an expected resource: 'R.string.google_app_id' for initializing Google services. Possible causes are missing google-services.json or com.google.gms.google-services gradle plugin.
E/GMPM: Scheduler not set. Not logging error/warn.
E/GMPM: Uploading is not possible. App measurement disabled
D/OpenGLRenderer: Use EGL_SWAP_BEHAVIOR_PRESERVED: true
I/Adreno200-EGL: <qeglDrvAPI_eglInitialize:265>: EGL 1.4 QUALCOMM build: AU_LINUX_ANDROID_JB_2.5.5.04.02.02.092.059_msm8960_JB_2.5.5_CL3896081_release_AU (CL3896081)
Build Date: 06/25/13 Tue
Local Branch:
Remote Branch: quic/jb_2.5.5
Local Patches: NONE
Reconstruct Branch: AU_LINUX_ANDROID_JB_2.5.5.04.02.02.092.059 + NOTHING
I/OpenGLRenderer: Initialized EGL, version 1.4
W/art: Before Android 4.1, method int android.support.v7.widget.ListViewCompat.lookForSelectablePosition(int, boolean) would have incorrectly overridden the package-private method in android.widget.ListView
I/System.out: When in doubt...
I/System.out: Button Pressed: Send
I/System.out: Apparent Success!
CONSOLE OUTPUT - WEAR
W/art: Suspending all threads took: 17.121ms
I/art: Background sticky concurrent mark sweep GC freed 1601(90KB) AllocSpace objects, 0(0B) LOS objects, 23% free, 508KB/663KB, paused 20.603ms total 53.990ms
W/art: Suspending all threads took: 5.855ms
I/art: Background partial concurrent mark sweep GC freed 168(48KB) AllocSpace objects, 0(0B) LOS objects, 45% free, 611KB/1123KB, paused 8.179ms total 61.166ms
I/System.out: mGoogleApiClient connected!
W/GooglePlayServicesUtil: Google Play services out of date. Requires 8487000 but found 8299574
D/OpenGLRenderer: Use EGL_SWAP_BEHAVIOR_PRESERVED: true
[ 04-03 23:16:13.428 15148:15148 D/ ]
HostConnection::get() New Host Connection established 0xb3edca60, tid 15148
D/Atlas: Validating map...
I/OpenGLRenderer: Initialized EGL, version 1.4
D/OpenGLRenderer: Enabling debug mode 0
W/EGL_emulation: eglSurfaceAttrib not implemented
W/OpenGLRenderer: Failed to set EGL_SWAP_BEHAVIOR on surface 0xb3f625e0, error=EGL_SUCCESS
I/System.out: mGoogleApiClient disconnected! //dis/connecting in MainActivity, before switching activities
W/EGL_emulation: eglSurfaceAttrib not implemented
W/OpenGLRenderer: Failed to set EGL_SWAP_BEHAVIOR on surface 0xb3f628a0, error=EGL_SUCCESS
W/EGL_emulation: eglSurfaceAttrib not implemented
W/OpenGLRenderer: Failed to set EGL_SWAP_BEHAVIOR on surface 0xb3f62700, error=EGL_SUCCESS
I/System.out: schedExtra: Custom Schedule
I/System.out: dayExtra: Thursday
I/System.out: howExtra: By Time
I/System.out: dayExtra: Thursday
I/System.out: schedExtra: Custom Schedule
I/System.out: howExtra: By Time
I/System.out: mGoogleApiClient connected!
D/AndroidRuntime: Shutting down VM
--------- beginning of crash
E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.michaeldvinci.conedmiro.schedaroo, PID: 15148
java.lang.NullPointerException: Attempt to invoke interface method 'int java.util.List.size()' on a null object reference
W/GooglePlayServicesUtil: Google Play services out of date. Requires 8487000 but found 8299574
WearableListenerService is required REGARDLESS
only briefly mentioned in the documentation [which should definitely be updated]
My application has 3 options(Buttons) in my main activity and a media player that plays a song when the application is launched. The media player starts correctly when the application is launched, but If i press a button to start a new activity while the audio is still playing, the application crushes (unfortunately app has stopped).
If i press "OK" in the message it opens the new activity and media player stops.
My aim is to start the new activity and stop the media player (song).
Could anyone help me with these issues.?
TextView logoname;
Button autismlogo,visionlogo,hearinglogo;
private SensorManager mSensorManager;
private ShakeEventListener mSensorListener;
MediaPlayer player;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
logoname = (TextView)findViewById(R.id.logotext);
autismlogo = (Button)findViewById(R.id.autismbutton);
visionlogo = (Button)findViewById(R.id.visionbutton);
hearinglogo = (Button)findViewById(R.id.hearingbutton);
final MediaPlayer player = MediaPlayer.create(MainActivity.this, R.raw.welcome);
player.start();
// ---SENSORS--------
mSensorManager = (SensorManager) getSystemService(Context.SENSOR_SERVICE);
mSensorListener = new ShakeEventListener();
mSensorListener.setOnShakeListener(new ShakeEventListener.OnShakeListener() {
public void onShake() {
Intent vision = new Intent(getApplicationContext(),Vision_main.class);
startActivity(vision);
}
});
// ----ON CLICK EVENTS -----------
autismlogo.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
Intent autism = new Intent(getApplicationContext(),Autism_main.class);
startActivity(autism);
}
});
visionlogo.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
Intent vision = new Intent(getApplicationContext(),Vision_main.class);
startActivity(vision);
}
});
hearinglogo.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
Intent hearing = new Intent(getApplicationContext(),Hearing_main.class);
startActivity(hearing);
}
});
}
public void onResume() {
super.onResume();
mSensorManager.registerListener(mSensorListener,
mSensorManager.getDefaultSensor(Sensor.TYPE_ACCELEROMETER),
SensorManager.SENSOR_DELAY_UI);
}
public void onPause() {
super.onPause();
player.stop();
mSensorManager.unregisterListener(mSensorListener);
}
Log Cat error
E/AndroidRuntime(27610): FATAL EXCEPTION: main
E/AndroidRuntime(27610): Process: com.giorgospapadopoulos.move4all, PID: 27610
E/AndroidRuntime(27610): java.lang.RuntimeException: Unable to pause activity {com.giorgospapadopoulos.move4all/com.giorgospapadopoulos.move4all.MainActivity}: java.lang.NullPointerException: Attempt to invoke virtual method 'void android.media.MediaPlayer.stop()' on a null object reference
E/AndroidRuntime(27610): at android.app.ActivityThread.performPauseActivity(ActivityThread.java:3260)
E/AndroidRuntime(27610): at android.app.ActivityThread.performPauseActivity(ActivityThread.java:3219)
E/AndroidRuntime(27610): at android.app.ActivityThread.handlePauseActivity(ActivityThread.java:3194)
E/AndroidRuntime(27610): at android.app.ActivityThread.access$1000(ActivityThread.java:151)
E/AndroidRuntime(27610): at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1314)
E/AndroidRuntime(27610): at android.os.Handler.dispatchMessage(Handler.java:102)
E/AndroidRuntime(27610): at android.os.Looper.loop(Looper.java:135)
E/AndroidRuntime(27610): at android.app.ActivityThread.main(ActivityThread.java:5254)
E/AndroidRuntime(27610): at java.lang.reflect.Method.invoke(Native Method)
E/AndroidRuntime(27610): at java.lang.reflect.Method.invoke(Method.java:372)
E/AndroidRuntime(27610): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:903)
E/AndroidRuntime(27610): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:698)
E/AndroidRuntime(27610): Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'void android.media.MediaPlayer.stop()' on a null object reference
E/AndroidRuntime(27610): at com.giorgospapadopoulos.move4all.MainActivity.onPause(MainActivity.java:220)
E/AndroidRuntime(27610): at android.app.Activity.performPause(Activity.java:6101)
E/AndroidRuntime(27610): at android.app.Instrumentation.callActivityOnPause(Instrumentation.java:1310)
E/AndroidRuntime(27610): at android.app.ActivityThread.performPauseActivity(ActivityThread.java:3246)
E/AndroidRuntime(27610): ... 11 more
Your error is quite clear. You get a NullPointerException at line 120 in your onPause() method. That's because you haven't created the player object and you try to invoke one of it's methods.
You have declared it as a global variable but you haven't created it. You create a different player object inside your onCreate() method but that's just a local variable.
Firstly in line
final MediaPlayer player = MediaPlayer.create(MainActivity.this, R.raw.welcome);
not declare MediaPlayer player as local, it should be global.
Use this in onPause()
if(player!=null){
player.stop();
}
in onResume()
if(
player!=null){
player.start();
}
by above code player will play music when app in foreground, when app in background player stop playing music and when app again comes in foreground state player will play music.