I have two fragments (left and right) and getting in the left fragment a list of Radiostreams. By clicking on one of these streams, the right fragment should change the Name of the Stream and start playing the stream with the given uri.
2 Problems:
Some of the radio streams aren't up to date, so a lot of them aren't working anymore. The problem is, this causes my app to do a forceclose! I did error handling, but after calling such a stream I get:
03-20 14:23:28.192: A/libc(1021): Fatal signal 11 (SIGSEGV) at
0x00000000 (code=1)
03-20 14:23:28.192: W/AudioSystem(1021): AudioFlinger server died!
03-20 14:23:28.192: W/IMediaDeathNotifier(1021): media server died
03-20 14:23:28.192: E/MediaPlayer(1021): error (100, 0)
03-20 14:23:28.192: I/ServiceManager(1021): Waiting for service
media.audio_flinger...
03-20 14:23:28.752: I/dalvikvm(1021): threadid=3: reacting to signal 3
03-20 14:23:28.782: I/dalvikvm(1021): Wrote stack traces to
'/data/anr/traces.txt'
03-20 14:23:29.192: I/ServiceManager(1021): Waiting for service
media.audio_flinger...
I don't know why. Is there any other way to do error handling? Or is there a way to check all the streams before calling mediaPlayer.setDataSource(uri) to avoid preparing defekt uris? (see my code at the end)
I'm controlling the left ListFragment with a remote control. When I try to switch very fast from one channel to the other everything is very laggy. It seems that the reinstanciation of the Mediaplayer take very long. When I don't reinstanciate I get an runtimeerror when I call mediaPlayer.setDataSource(..) again. Is there a way to call .setDataSource two times on one MediaPlayer Object?
Here is my code:
My MediaPlayer Wrapper class:
package net.smart4life.tvplay.model;
import java.io.IOException;
import java.lang.reflect.Method;
import java.util.AbstractCollection;
import java.util.ArrayList;
import java.util.EnumSet;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
import android.media.AudioManager;
import android.media.MediaPlayer;
import android.media.MediaPlayer.OnBufferingUpdateListener;
import android.media.MediaPlayer.OnCompletionListener;
import android.media.MediaPlayer.OnErrorListener;
import android.media.MediaPlayer.OnInfoListener;
import android.media.MediaPlayer.OnPreparedListener;
import android.util.Log;
/**
* A wrapper class for {#link android.media.MediaPlayer}.
* <p>
* Encapsulates an instance of MediaPlayer, and makes a record of its internal
* state accessible via a {#link MediaPlayerWrapper#getState()} accessor.
*/
public class MediaPlayerStateWrapper {
private static String tag = "MediaPlayerWrapper";
private MediaPlayer mPlayer;
private State currentState;
private MediaPlayerStateWrapper mWrapper;
public MediaPlayerStateWrapper() {
mWrapper = this;
mPlayer = new MediaPlayer();
currentState = State.IDLE;
mPlayer.setOnPreparedListener(mOnPreparedListener);
mPlayer.setOnCompletionListener(mOnCompletionListener);
mPlayer.setOnBufferingUpdateListener(mOnBufferingUpdateListener);
mPlayer.setOnErrorListener(mOnErrorListener);
mPlayer.setOnInfoListener(mOnInfoListener);
}
/* METHOD WRAPPING FOR STATE CHANGES */
public static enum State {
IDLE, ERROR, INITIALIZED, PREPARING, PREPARED, STARTED, STOPPED, PLAYBACK_COMPLETE, PAUSED;
}
public void setDataSource(String path) {
if (currentState == State.IDLE) {
try {
mPlayer.setDataSource(path);
currentState = State.INITIALIZED;
} catch (IllegalArgumentException e) {
e.printStackTrace();
} catch (IllegalStateException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
} else
throw new RuntimeException();
}
public void prepareAsync() {
Log.d(tag, "prepareAsync()");
if (EnumSet.of(State.INITIALIZED, State.STOPPED).contains(currentState)) {
mPlayer.prepareAsync();
currentState = State.PREPARING;
} else
throw new RuntimeException();
}
public boolean isPlaying() {
Log.d(tag, "isPlaying()");
if (currentState != State.ERROR) {
return mPlayer.isPlaying();
} else
throw new RuntimeException();
}
public void seekTo(int msec) {
Log.d(tag, "seekTo()");
if (EnumSet.of(State.PREPARED, State.STARTED, State.PAUSED,
State.PLAYBACK_COMPLETE).contains(currentState)) {
mPlayer.seekTo(msec);
} else
throw new RuntimeException();
}
public void pause() {
Log.d(tag, "pause()");
if (EnumSet.of(State.STARTED, State.PAUSED).contains(currentState)) {
mPlayer.pause();
currentState = State.PAUSED;
} else
throw new RuntimeException();
}
public void start() {
Log.d(tag, "start()");
if (EnumSet.of(State.PREPARED, State.STARTED, State.PAUSED,
State.PLAYBACK_COMPLETE).contains(currentState)) {
mPlayer.start();
currentState = State.STARTED;
} else
throw new RuntimeException();
}
public void stop() {
Log.d(tag, "stop()");
if (EnumSet.of(State.PREPARED, State.STARTED, State.STOPPED,
State.PAUSED, State.PLAYBACK_COMPLETE).contains(currentState)) {
mPlayer.stop();
currentState = State.STOPPED;
} else
throw new RuntimeException();
}
public void reset() {
Log.d(tag, "reset()");
mPlayer.reset();
currentState = State.IDLE;
}
/**
* #return The current state of the mediaplayer state machine.
*/
public State getState() {
Log.d(tag, "getState()");
return currentState;
}
public void release() {
Log.d(tag, "release()");
mPlayer.release();
}
/* INTERNAL LISTENERS */
private OnPreparedListener mOnPreparedListener = new OnPreparedListener() {
#Override
public void onPrepared(MediaPlayer mp) {
Log.d(tag, "on prepared");
currentState = State.PREPARED;
mWrapper.onPrepared(mp);
mPlayer.start();
currentState = State.STARTED;
}
};
private OnCompletionListener mOnCompletionListener = new OnCompletionListener() {
#Override
public void onCompletion(MediaPlayer mp) {
Log.d(tag, "on completion");
currentState = State.PLAYBACK_COMPLETE;
mWrapper.onCompletion(mp);
}
};
private OnBufferingUpdateListener mOnBufferingUpdateListener = new OnBufferingUpdateListener() {
#Override
public void onBufferingUpdate(MediaPlayer mp, int percent) {
Log.d(tag, "on buffering update");
mWrapper.onBufferingUpdate(mp, percent);
}
};
private OnErrorListener mOnErrorListener = new OnErrorListener() {
#Override
public boolean onError(MediaPlayer mp, int what, int extra) {
Log.d(tag, "on error");
currentState = State.ERROR;
mWrapper.onError(mp, what, extra);
return false;
}
};
private OnInfoListener mOnInfoListener = new OnInfoListener() {
#Override
public boolean onInfo(MediaPlayer mp, int what, int extra) {
Log.d(tag, "on info");
mWrapper.onInfo(mp, what, extra);
return false;
}
};
/* EXTERNAL STUBS TO OVERRIDE */
public void onPrepared(MediaPlayer mp) {
}
public void onCompletion(MediaPlayer mp) {
}
public void onBufferingUpdate(MediaPlayer mp, int percent) {
}
boolean onError(MediaPlayer mp, int what, int extra) {
// Error Handling of type: "MEdiaPlayer error(100,0)
mp.stop();
mp.release();
return false;
}
public boolean onInfo(MediaPlayer mp, int what, int extra) {
return false;
}
/* OTHER STUFF */
public int getCurrentPosition() {
if (currentState != State.ERROR) {
return mPlayer.getCurrentPosition();
} else {
return 0;
}
}
public int getDuration() {
// Prepared, Started, Paused, Stopped, PlaybackCompleted
if (EnumSet.of(State.PREPARED, State.STARTED, State.PAUSED,
State.STOPPED, State.PLAYBACK_COMPLETE).contains(currentState)) {
return mPlayer.getDuration();
} else {
return 100;
}
}
}
Here is my TestFragment (right Fragment). Note: the left Fragment is calling the method "newChannel(radioChannel)" from TestFragment, everytime a listitem was clicked.
package net.smart4life.tvplay.fragment;
import java.io.IOException;
import net.smart4life.tvplay.R;
import net.smart4life.tvplay.model.MediaPlayerStateWrapper;
import net.smart4life.tvplay.model.RadioChannel;
import android.app.Fragment;
import android.media.AudioManager;
import android.media.MediaPlayer;
import android.media.MediaPlayer.OnErrorListener;
import android.media.MediaPlayer.OnPreparedListener;
import android.os.Bundle;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;
import android.widget.Toast;
public class TestFragment extends Fragment {
private RadioChannel radioCh;
private TextView tv_RadioCh;
private MediaPlayerStateWrapper mediaWrapper;
private View view;
// firstcall
public TestFragment(RadioChannel radioChannel) {
this.radioCh = radioChannel;
}
#Override
public void onActivityCreated(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onActivityCreated(savedInstanceState);
setRetainInstance(true);
tv_RadioCh = (TextView) view.findViewById(R.id.radioText);
mediaWrapper = new MediaPlayerStateWrapper();
newChannel(radioCh);
}
public void newChannel (RadioChannel radioChannel) {
this.radioCh = radioChannel;
Log.e("RadioChannel", radioCh.getName());
tv_RadioCh.setText(radioCh.getName());
if(mediaWrapper.isPlaying()) {
mediaWrapper.stop();
mediaWrapper.reset();
} else if(mediaWrapper.getState() == MediaPlayerStateWrapper.State.PREPARING) {
mediaWrapper.release();
mediaWrapper = new MediaPlayerStateWrapper();
}
mediaWrapper.setDataSource(radioCh.getUrl().toString());
mediaWrapper.prepareAsync();
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
view = inflater.inflate(R.layout.fragment_radio_player, container,
false);
return view;
}
#Override
public void onDetach() {
super.onDetach();
mediaWrapper.release();
}
}
Pros, could you please help me with one or both questions?
If a stream can't load you're often stucked in the prepare state, you can try this here, when mediaWrapper.getState() == MediaPlayerStateWrapper.State.ERROR:
mediaWrapper.reset();
mediaWrapper.release();
System.gc();
mediaWrapper = new MediaPlayerStateWrapper();
mediaWrapper.setDataSource(radioCh.getUrl().toString());
mediaWrapper.prepareAsync();
Best to put it in an AsyncTask, to avoid Not responding error. Or when you get an Error you have to create a new MediaPlayer, because Media Server died:
if(mediaWrapper.getState() == MediaPlayerStateWrapper.State.ERROR){
mediaWrapper = new MediaPlayerStateWrapper();
mediaWrapper.setDataSource(radioCh.getUrl().toString());
mediaWrapper.prepareAsync();
}
If the MediaPlayer is playing a stream you have to stop and reset it first :
mediaWrapper.stop();
mediaWrapper.reset();
mediaWrapper.setDataSource(radioCh.getUrl().toString());
mediaWrapper.prepareAsync();
It's working for me but i think it isn't the best way. Hope someone can find a better solution for what to do, when you're stucked in the prepare state.
Regarding the audioflinger service error, as you have noticed, it is marked by "what == 100" or error(100,0).
What you can do to avoid audioflinger error from my humble experience:
Avoid fast calls to the service (I do add like 500 millis delay after creating the player)
Limit the number of concurrent Mediaplayers active at the same time.
What you can do to handle audioflinger error:
Detect the audioflinger error 100, set a flag it occurred and disable GUI (releasing the player only is recommended, as stopping it when it already is in error state is not safe and will throw IllegalStateException & error(38,0)
Start another thread that keeps testing the service is back (could be by creating a new mediaplayer with no exceptions) with a timeout of let's say 5-10 seconds
When the Service is back reset the flag and re-enable GUI
So referring to your code:
boolean onError(MediaPlayer mp, int what, int extra) {
// Error Handling of type: "MEdiaPlayer error(100,0)
mp.release();
// here you add logic communicating the wrapper or main UI thread
// to disable GUI and set a flag
return false;
}
Then you add a method to handle this at the wrapper.
I would be really grateful when you work this out and post a solution. I too am facing a very similar problem.
Related
Here my scenario in which i am starting a service from an Activity which play music in background. When i press back button on this activity, activity get destroyed. but service is still running in background. I want to show a notification to user when this activity get destroyed so that they can play/pause/stop audio from notification. but i dont want notification to be displayed when the service get started.
below is my activity code :
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.ServiceConnection;
import android.os.Bundle;
import android.os.Handler;
import android.os.IBinder;
import android.os.Message;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.widget.Button;
import android.widget.ProgressBar;
import android.widget.TextView;
import android.widget.Toast;
public class PlayBackgroundAudioActivity extends AppCompatActivity {
private AudioServiceBinder audioServiceBinder = null;
private Handler audioProgressUpdateHandler = null;
// Show played audio progress.
private ProgressBar backgroundAudioProgress;
private TextView audioFileUrlTextView;
// This service connection object is the bridge between activity and background service.
private ServiceConnection serviceConnection = new ServiceConnection() {
#Override
public void onServiceConnected(ComponentName componentName, IBinder iBinder) {
// Cast and assign background service's onBind method returned iBander object.
audioServiceBinder = (AudioServiceBinder) iBinder;
}
#Override
public void onServiceDisconnected(ComponentName componentName) {
}
};
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_play_background_audio);
setTitle("dev2qa.com - Play Audio Use Background Service");
// Bind background audio service when activity is created.
bindAudioService();
final String audioFileUrl = "http://www.dev2qa.com/demo/media/test.mp3";
backgroundAudioProgress = (ProgressBar)findViewById(R.id.play_audio_in_background_service_progressbar);
// Get audio file url textview.
audioFileUrlTextView = (TextView)findViewById(R.id.audio_file_url_text_view);
if(audioFileUrlTextView != null)
{
// Show web audio file url in the text view.
audioFileUrlTextView.setText("Audio File Url. \r\n" + audioFileUrl);
}
// Click this button to start play audio in a background service.
Button startBackgroundAudio = (Button)findViewById(R.id.start_audio_in_background);
startBackgroundAudio.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
// Set web audio file url
audioServiceBinder.setAudioFileUrl(audioFileUrl);
// Web audio is a stream audio.
audioServiceBinder.setStreamAudio(true);
// Set application context.
audioServiceBinder.setContext(getApplicationContext());
// Initialize audio progress bar updater Handler object.
createAudioProgressbarUpdater();
audioServiceBinder.setAudioProgressUpdateHandler(audioProgressUpdateHandler);
// Start audio in background service.
audioServiceBinder.startAudio();
backgroundAudioProgress.setVisibility(ProgressBar.VISIBLE);
Toast.makeText(getApplicationContext(), "Start play web audio file.", Toast.LENGTH_LONG).show();
}
});
// Click this button to pause the audio played in background service.
Button pauseBackgroundAudio = (Button)findViewById(R.id.pause_audio_in_background);
pauseBackgroundAudio.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
audioServiceBinder.pauseAudio();
Toast.makeText(getApplicationContext(), "Play web audio file is paused.", Toast.LENGTH_LONG).show();
}
});
// Click this button to stop the media player in background service.
Button stopBackgroundAudio = (Button)findViewById(R.id.stop_audio_in_background);
stopBackgroundAudio.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
audioServiceBinder.stopAudio();
backgroundAudioProgress.setVisibility(ProgressBar.INVISIBLE);
Toast.makeText(getApplicationContext(), "Stop play web audio file.", Toast.LENGTH_LONG).show();
}
});
}
// Bind background service with caller activity. Then this activity can use
// background service's AudioServiceBinder instance to invoke related methods.
private void bindAudioService()
{
if(audioServiceBinder == null) {
Intent intent = new Intent(PlayBackgroundAudioActivity.this, AudioService.class);
// Below code will invoke serviceConnection's onServiceConnected method.
bindService(intent, serviceConnection, Context.BIND_AUTO_CREATE);
}
}
// Unbound background audio service with caller activity.
private void unBoundAudioService()
{
if(audioServiceBinder != null) {
unbindService(serviceConnection);
}
}
#Override
protected void onDestroy() {
// Unbound background audio service when activity is destroyed.
unBoundAudioService();
super.onDestroy();
}
// Create audio player progressbar updater.
// This updater is used to update progressbar to reflect audio play process.
private void createAudioProgressbarUpdater()
{
/* Initialize audio progress handler. */
if(audioProgressUpdateHandler==null) {
audioProgressUpdateHandler = new Handler() {
#Override
public void handleMessage(Message msg) {
// The update process message is sent from AudioServiceBinder class's thread object.
if (msg.what == audioServiceBinder.UPDATE_AUDIO_PROGRESS_BAR) {
if( audioServiceBinder != null) {
// Calculate the percentage.
int currProgress =audioServiceBinder.getAudioProgress();
// Update progressbar. Make the value 10 times to show more clear UI change.
backgroundAudioProgress.setProgress(currProgress*10);
}
}
}
};
}
}
#Override
public void onBackPressed() {
startActivity(new Intent(PlayBackgroundAudioActivity.this,ForeGroundService.class));
finish();
}
}
below is my service code:
import android.app.Service;
import android.content.Intent;
import android.os.IBinder;
public class AudioService extends Service {
private AudioServiceBinder audioServiceBinder = new AudioServiceBinder();
public AudioService() {
}
#Override
public IBinder onBind(Intent intent) {
return audioServiceBinder;
}
}
below is myaudio binder class:
import android.content.Context;
import android.media.AudioManager;
import android.media.MediaPlayer;
import android.net.Uri;
import android.os.Binder;
import android.os.Handler;
import android.os.Message;
import android.text.TextUtils;
import java.io.IOException;
/**
* Created by Jerry on 2/15/2018.
*/
public class AudioServiceBinder extends Binder {
// Save local audio file uri ( local storage file. ).
private Uri audioFileUri = null;
// Save web audio file url.
private String audioFileUrl = "";
// Check if stream audio.
private boolean streamAudio = false;
// Media player that play audio.
private MediaPlayer audioPlayer = null;
// Caller activity context, used when play local audio file.
private Context context = null;
// This Handler object is a reference to the caller activity's Handler.
// In the caller activity's handler, it will update the audio play progress.
private Handler audioProgressUpdateHandler;
// This is the message signal that inform audio progress updater to update audio progress.
public final int UPDATE_AUDIO_PROGRESS_BAR = 1;
public Context getContext() {
return context;
}
public void setContext(Context context) {
this.context = context;
}
public String getAudioFileUrl() {
return audioFileUrl;
}
public void setAudioFileUrl(String audioFileUrl) {
this.audioFileUrl = audioFileUrl;
}
public boolean isStreamAudio() {
return streamAudio;
}
public void setStreamAudio(boolean streamAudio) {
this.streamAudio = streamAudio;
}
public Uri getAudioFileUri() {
return audioFileUri;
}
public void setAudioFileUri(Uri audioFileUri) {
this.audioFileUri = audioFileUri;
}
public Handler getAudioProgressUpdateHandler() {
return audioProgressUpdateHandler;
}
public void setAudioProgressUpdateHandler(Handler audioProgressUpdateHandler) {
this.audioProgressUpdateHandler = audioProgressUpdateHandler;
}
// Start play audio.
public void startAudio()
{
initAudioPlayer();
if(audioPlayer!=null) {
audioPlayer.start();
}
}
// Pause playing audio.
public void pauseAudio()
{
if(audioPlayer!=null) {
audioPlayer.pause();
}
}
// Stop play audio.
public void stopAudio()
{
if(audioPlayer!=null) {
audioPlayer.stop();
destroyAudioPlayer();
}
}
// Initialise audio player.
private void initAudioPlayer()
{
try {
if (audioPlayer == null) {
audioPlayer = new MediaPlayer();
if (!TextUtils.isEmpty(getAudioFileUrl())) {
if (isStreamAudio()) {
audioPlayer.setAudioStreamType(AudioManager.STREAM_MUSIC);
}
audioPlayer.setDataSource(getAudioFileUrl());
} else {
audioPlayer.setDataSource(getContext(), getAudioFileUri());
}
audioPlayer.prepare();
// This thread object will send update audio progress message to caller activity every 1 second.
Thread updateAudioProgressThread = new Thread()
{
#Override
public void run() {
while(true)
{
// Create update audio progress message.
Message updateAudioProgressMsg = new Message();
updateAudioProgressMsg.what = UPDATE_AUDIO_PROGRESS_BAR;
// Send the message to caller activity's update audio prgressbar Handler object.
audioProgressUpdateHandler.sendMessage(updateAudioProgressMsg);
// Sleep one second.
try {
Thread.sleep(1000);
}catch(InterruptedException ex)
{
ex.printStackTrace();
}
}
}
};
// Run above thread object.
updateAudioProgressThread.start();
}
}catch(IOException ex)
{
ex.printStackTrace();
}
}
// Destroy audio player.
private void destroyAudioPlayer()
{
if(audioPlayer!=null)
{
if(audioPlayer.isPlaying())
{
audioPlayer.stop();
}
audioPlayer.release();
audioPlayer = null;
}
}
// Return current audio play position.
public int getCurrentAudioPosition()
{
int ret = 0;
if(audioPlayer != null)
{
ret = audioPlayer.getCurrentPosition();
}
return ret;
}
// Return total audio file duration.
public int getTotalAudioDuration()
{
int ret = 0;
if(audioPlayer != null)
{
ret = audioPlayer.getDuration();
}
return ret;
}
// Return current audio player progress value.
public int getAudioProgress()
{
int ret = 0;
int currAudioPosition = getCurrentAudioPosition();
int totalAudioDuration = getTotalAudioDuration();
if(totalAudioDuration > 0) {
ret = (currAudioPosition * 100) / totalAudioDuration;
}
return ret;
}
}
Basically you should reconsider the time when your notification is shown. Since the onDestroy method of an activity may not be always called, I would prefer to use another point when to display your notification. You should be also aware of the new restrictions regarding background services since android 8 (API 26), if you do not explicitly mark them as a foreground service, then they might be killed by the OS while the app is in the background.
So, for your purpose it might be an option to use the method startForeground with a notification id and call it when your activity is going to the background (e.g. at onStop), then it will display the notification (which is the requirement for keeping the service in the foreground). If you decide to go back to your activity after some time, you may call stopForeground to stop the foreground mode and dismiss your notification.
I implemented everything I've found here, but my service is not starting yet.
What I need to do is to start playing a radio station when the user clicks on a button, and only stop it when he clicks it again. I don't want the radio to be stopped if the application get closed.
When I test the code I'm sending, nothing happens.
Manifest:
<service
android:name=".RadioService"
android:icon="#drawable/ic_launcher"
android:label="#string/app_name"
android:exported="false"
>
</service>
Service Code:
package com.po.portelaonline.service;
import android.app.Service;
import android.content.Intent;
import android.os.IBinder;
public class RadioService extends Service {
Player player;
#Override
public int onStartCommand(Intent intent, int flags, int startId) {
player.start();
return Service.START_NOT_STICKY;
}
#Override
public void onCreate(){
player = new Player();
}
#Override
public IBinder onBind(Intent arg0) {
// TODO Auto-generated method stub
return null;
}
#Override
public void onDestroy(){
player.stopThread();
}
}
Player class code:
package com.po.portelaonline.service;
import android.media.MediaPlayer;
import android.media.MediaPlayer.OnPreparedListener;
import com.po.portelaonline.classes.Util;
class Player extends Thread {
volatile boolean running = true;
#Override
public void run() {
MediaPlayer player = new MediaPlayer();
try {
player.setDataSource(Util.getRadioUrl());
player.setOnPreparedListener(oplPlayer);
player.prepareAsync();
while (running) {
Player.sleep(500);
}
player.release();
player = null;
} catch (Exception e) {
e.printStackTrace();
}
}
public void stopThread() {
running = false;
}
OnPreparedListener oplPlayer = new OnPreparedListener() {
#Override
public void onPrepared(MediaPlayer mp) {
mp.start();
}
};
}
And I'm calling this way:
Intent i = new Intent(getApplicationContext(), RadioService.class);
if(getApplicationContext().startService(i) == null){
findViewById(R.id.btnPlayStop).setBackgroundDrawable(getApplicationContext().getResources().getDrawable(R.drawable.stop));
}else{
getApplicationContext().stopService(i);
findViewById(R.id.btnPlayStop).setBackgroundDrawable(getApplicationContext().getResources().getDrawable(R.drawable.play));
}
Try this code for service class.
You don't need to create MediaPlayer object in separate thread. player.prepareAsync(); is already asynchronous.
EDIT:
The path to the RadioService class into the AndroidManifest.xml should be absolute: android:name="com.po.portelaonline.service.RadioService"
public class RadioService extends Service implements OnPreparedListener, OnErrorListener{
MediaPlayer mPlayer;
#Override
public int onStartCommand(Intent intent, int flags, int startId) {
startPlayer();
return Service.START_NOT_STICKY;
}
#Override
public void onCreate(){
initMediaPlayer();
}
private void initMediaPlayer () {
mPlayer = new MediaPlayer();
mPlayer.setOnPreparedListener(this);
mPlayer.setOnErrorListener(this);
mPlayer.setAudioStreamType(AudioManager.STREAM_MUSIC);
mPlayer.setWakeMode(getApplicationContext(),
PowerManager.PARTIAL_WAKE_LOCK);
}
private void startPlayer(){
player.setDataSource(Util.getRadioUrl());
player.prepareAsync();
}
#Override
public IBinder onBind(Intent arg0) {
// TODO Auto-generated method stub
return null;
}
#Override
public void onDestroy(){
mPlayer.release();
}
#Override
public void onPrepared (MediaPlayer mp) {
mp.start();
}
#Override
public boolean onError (MediaPlayer mp, int what, int extra) {
Log.e("RadioService OnError", "what="+what+" extra="+extra);
return false;
}
}
i guess it should be
if(getApplicationContext().startService(i) != null)
instead of if(getApplicationContext().startService(i) == null)
You are immediately stopping the service after you start it.
I've developed an app which takes an advantage of the native Android's MediaPlayer. The source code of my class making use of Media Player is below.
The problem is that only on some devices after some miliseconds of playback (I hear only voice, the screen remains black) I keep getting error(100,0) which according to the documentation says
public static final int MEDIA_ERROR_SERVER_DIED
Media server died. In this case, the application must release the MediaPlayer object and instantiate a new one.
On forums I've found out that I need to reset the player every time I get it... but I get it after just a short moment and then it dies forever. I cannot reset the player every second since playback is useless. I cannot get why some devices have this problem and others not. The one that I know has Android OS > 4.0.
Of course, first init() and then showVideo() are getting called. The last onError with code 100 is then called. What's a potential solution to make the streams run continuously and not break?
public class NativePlayer extends Player implements OnBufferingUpdateListener,
OnCompletionListener, OnErrorListener, OnInfoListener {
private VideoView videoview;
private PlayerListener listener;
private MainActivity context;
private final Logger logger = LoggerFactory.getLogger(NativePlayer.class);
#Override
public void init(MainActivity activity) {
this.videoview = (VideoView) activity.findViewById(R.id.video);
context = activity;
}
#Override
public void showVideo(final String url, final PlayerListener _listener) {
listener = _listener;
videoview.setVisibility(View.VISIBLE);
try {
Uri video = Uri.parse(url);
videoview.setVideoURI(video);
} catch (Exception e) {
logger.error("Error playing video", e);
listener.onVideoError();
return;
}
videoview.setOnCompletionListener(this);
videoview.setOnErrorListener(this);
videoview.requestFocus();
videoview.setOnPreparedListener(new OnPreparedListener() {
public void onPrepared(MediaPlayer mp) {
videoview.start();
if (listener != null) {
listener.onVideoStarted();
}
}
});
}
#Override
public void onStop() {
stop();
}
private void stop() {
if (videoview == null) {
return;
}
if (videoview.isPlaying()) {
videoview.stopPlayback();
}
}
#Override
public void onDestroy() {
}
#Override
public void onCompletion(MediaPlayer mp) {
stop();
}
#Override
public boolean onError(MediaPlayer mp, int what, int extra) {
if (listener != null) {
listener.onVideoError();
}
return false;
}
#Override
public boolean onInfo(MediaPlayer mp, int what, int extra) {
if (listener != null) {
listener.onInfo(what, extra);
}
return false;
}
#Override
public void onBufferingUpdate(MediaPlayer mp, int percent) {
if (listener != null) {
listener.onBufferingUpdate(percent);
}
}
}
I had same problem (error 100, mediaplayer died, etc.).
I resolve it by using .stopPlayback(), and starting stream again.
Below is my part of code:
private void startWatchVideo(final string video_link) {
videoViewVA.setMediaController(new MediaController(this));
videoViewVA.setVideoURI(Uri.parse(video_link));
videoViewVA.requestFocus();
videoViewVA.setOnPreparedListener(new OnPreparedListener() {
public void onPrepared(MediaPlayer media) {
media.start();
}
});
videoViewVA.setOnErrorListener(new OnErrorListener() {
#Override
public boolean onError(MediaPlayer media, int what, int extra) {
if (what == 100)
{
videoViewVA.stopPlayback();
startWatchVideo(video_link);
}
return true;
}
});
}
On practice it looks like video is just slows down
This is an application that measures the sound intensity and in accordance with that measured value it sets the seek bar and in turn it adjusts the ringer volume in accordance with the seek bar automatically.
I want to run this application in foreground as well as in background
when user destroys it. Because the user will definately be needing
the app even after he quits it. I have read the documentation of
creating a service but the problem is i want full code same as
activity to be run in the background after the app destroyal..So any
help would be greatly appreciated.
package com.example.soundmeter;
import android.app.Activity;
import android.content.Intent;
import android.media.MediaRecorder;
import android.os.Bundle;
import android.os.Handler;
import android.util.Log;
import android.widget.TextView;
import android.content.Context;
import android.media.AudioManager;
import android.view.KeyEvent;
import android.widget.SeekBar;
import android.widget.SeekBar.OnSeekBarChangeListener;
import com.example.soundmeter.R;
public class MainActivity extends Activity {
//public static boolean isService = false;
TextView mStatusView;
MediaRecorder mRecorder;
Thread runner;
private static double mEMA = 0.0;
static final private double EMA_FILTER = 0.6;
//a variable to store the seek bar from the XML file
public SeekBar volumeBar;
//an AudioManager object, to change the volume settings
private AudioManager amanager;
final Runnable updater = new Runnable(){
public void run(){
updateTv();
};
};
final Handler mHandler = new Handler();
public void onCreate(Bundle savedInstanceState) {
setContentView(R.layout.main);
super.onCreate(savedInstanceState);
mStatusView = (TextView) findViewById(R.id.status);
//startService(new Intent(MainActivity.this,BackGroundService.class));
if (runner == null)
{
runner = new Thread(){
public void run()
{
while (runner != null)
{
volumeChanger();
try
{
Thread.sleep(5000);
Log.i("Noise", "Tock");
} catch (InterruptedException e) { };
mHandler.post(updater);
}
}
};
runner.start();
Log.d("Noise", "start runner()");
}
}
public void onResume()
{
super.onResume();
startRecorder();
}
public void onPause()
{
super.onResume();
startRecorder();
//super.onPause();
//super.stopRecorder();
}
/*#Override
public void onBackPressed()
{
super.onResume();
startRecorder();
}*/
public void startRecorder(){
if (mRecorder == null)
{
mRecorder = new MediaRecorder();
mRecorder.setAudioSource(MediaRecorder.AudioSource.MIC);
mRecorder.setOutputFormat(MediaRecorder.OutputFormat.THREE_GPP);
mRecorder.setAudioEncoder(MediaRecorder.AudioEncoder.AMR_NB);
mRecorder.setOutputFile("/dev/null");
try
{
mRecorder.prepare();
}catch (java.io.IOException ioe) {
android.util.Log.e("[Monkey]", "IOException: " +
android.util.Log.getStackTraceString(ioe));
}catch (java.lang.SecurityException e) {
android.util.Log.e("[Monkey]", "SecurityException: " +
android.util.Log.getStackTraceString(e));
}
try
{
mRecorder.start();
}catch (java.lang.SecurityException e) {
android.util.Log.e("[Monkey]", "SecurityException: " +
android.util.Log.getStackTraceString(e));
}
//mEMA = 0.0;
}
}
/*public void stopRecorder() {
if (mRecorder != null) {
mRecorder.stop();
mRecorder.release();
mRecorder = null;
}
}*/
public void updateTv(){
double amp=getAmplitudeEMA();
mStatusView.setText(Double.toString((amp)) + " dB");
}
public double soundDb(double ampl){
double intensity=20 * Math.log10(getAmplitudeEMA() / ampl);
return intensity;
}
public double getAmplitude() {
if (mRecorder != null)
return (mRecorder.getMaxAmplitude());
else
return 0;
}
public double getAmplitudeEMA() {
double amp = getAmplitude();
mEMA = EMA_FILTER * amp + (1.0 - EMA_FILTER) * mEMA;
return mEMA;
}
public void volumeChanger()
{
volumeBar = (SeekBar) findViewById(R.id.sb_volumebar);
//get the audio manager
amanager = (AudioManager) this.getSystemService(Context.AUDIO_SERVICE);
//seek bar settings//
//sets the range between 0 and the max volume
volumeBar.setMax(amanager.getStreamMaxVolume(AudioManager.STREAM_RING));
//set the seek bar progress to 1
//volumeBar.setKeyProgressIncrement(1);
//sets the progress of the seek bar based on the system's volume
// volumeBar.setProgress(500);
if(mEMA<(double)800.00)
{
volumeBar.setProgress((int)amanager.getStreamMaxVolume(AudioManager.STREAM_RING)/5);
}
else if(mEMA<(double)15000.00)
{
volumeBar.setProgress((int)amanager.getStreamMaxVolume(AudioManager.STREAM_RING)*2/5);
}
else if(mEMA<25000.00)
{
volumeBar.setProgress((int)amanager.getStreamMaxVolume(AudioManager.STREAM_RING)*3/5);
}
else if(mEMA<50000.00)
{
volumeBar.setProgress((int)amanager.getStreamMaxVolume(AudioManager.STREAM_RING)*4/5);
}
else
{
volumeBar.setProgress((int)amanager.getStreamMaxVolume(AudioManager.STREAM_RING));
}
//register OnSeekBarChangeListener, so that the seek bar can change the volume
volumeBar.setOnSeekBarChangeListener(new OnSeekBarChangeListener()
{
#Override
public void onStopTrackingTouch(SeekBar seekBar)
{
}
#Override
public void onStartTrackingTouch(SeekBar seekBar)
{
}
#Override
public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser)
{
int index=volumeBar.getProgress();
//change the volume, displaying a toast message containing the current volume and playing a feedback sound
amanager.setStreamVolume(AudioManager.STREAM_RING, index, AudioManager.FLAG_SHOW_UI);
}
});
}
#Override
public boolean onKeyDown(int keyCode, KeyEvent event)
{
//if one of the volume keys were pressed
if(keyCode == KeyEvent.KEYCODE_VOLUME_DOWN || keyCode == KeyEvent.KEYCODE_VOLUME_UP)
{
//change the seek bar progress indicator position
volumeBar.setProgress(amanager.getStreamVolume(AudioManager.STREAM_RING));
}
if (keyCode == KeyEvent.KEYCODE_BACK) {
moveTaskToBack(true);
return true;
}
//propagate the key event
return super.onKeyDown(keyCode, event);
}
}
Have the measurement code always listen on the service and let it update shared preferences.
Then all the activity needs to do is listen to changes on shared preferences and update the UI accordingly.
You can obviously use any number of mechanisms to allow the activity respond to the services changes, but I think listening for shared preference changes is probably easiest to start with.
listener = new SharedPreferences.OnSharedPreferenceChangeListener() {
public void onSharedPreferenceChanged(SharedPreferences prefs, String key) {
//update ui if your key was updated
}
};
prefs.registerOnSharedPreferenceChangeListener(listener);
I have figured out another way of doing it.
A broadcast Receiver can be used in the main activity in syncronization with a broadcast service.
I know this question has been asked many times before and might seem to be a conglomeration of several questions, but I feel that it is relevant and important to many developers; I need to create a background music Service that can run across multiple activities for my Android game that ends when the application is terminated and pauses in all of the following circumstances:
A certain Activity that has its own music is started. (Resume when this Activity finishes. This happens to be an AndEngine activity.)
The home screen is pressed and the app is backgrounded, or the application is terminated. Resumes when the app returns to the foreground. Requires use of onUserLeaveHint(). Another helpful link.
The phone receives a call and interrupts the app. Resumes when the call has been dealt with. Requires use of TelephonyManager similar to this.
The screen is locked. (Resumes after screen has been unlocked.) Requires use of ACTION_USER_PRESENT, which seems to be very problematic.
Basically the music pauses whenever the app is not being shown or when the special activity from #1 is being shown to the user.
Above is all of what I need and the information I have pieced together. My current code basically resembles this.
I find it curious that AndEngine manages to have none of these issues with their music, so maybe looking in the source code would help someone looking for an answer. I'm using the last functional GLES1 version from Google Code.
I have taken a look at the following links as well on creating a good music Service:
Stopping Background Service Music
http://www.codeproject.com/Articles/258176/Adding-Background-Music-to-Android-App
Android background music service
Playing BG Music Across Activities in Android
http://www.rbgrn.net/content/307-light-racer-20-days-61-64-completion
I would like the solution Service to:
Minimize the use of BroadcastReceivers and Android Manifest additions/permissions if possible
Self contained and error checking
Other Notes
Currently all the activities that require the background music all extend a common special class.
The music needs to loop but only runs a single track.
Thanks to everyone ahead of time! Best of luck!
Edit - Here are code snippets, feel free to improve or ignore:
Media Player Wrapper
import android.content.SharedPreferences;
import android.media.MediaPlayer;
import android.preference.PreferenceManager;
import android.util.Log;
public class CarefulMediaPlayer {
final SharedPreferences sp;
final MediaPlayer mp;
private boolean isPlaying = false;
public CarefulMediaPlayer(final MediaPlayer mp, final MusicService ms) {
sp = PreferenceManager.getDefaultSharedPreferences(ms.getApplicationContext());
this.mp = mp;
}
public void start() {
if (sp.getBoolean("com.embed.candy.music", true) && !isPlaying) {
mp.start();
isPlaying = true;
}
}
public void pause() {
if (isPlaying) {
mp.pause();
isPlaying = false;
}
}
public void stop() {
isPlaying = false;
try {
mp.stop();
mp.release();
} catch (final Exception e) {}
}
}
Music Service
import android.app.Service;
import android.content.Intent;
import android.media.MediaPlayer;
import android.os.IBinder;
public class MusicService extends Service {
static CarefulMediaPlayer mPlayer = null;
#Override
public IBinder onBind(final Intent arg0) {
return null;
}
#Override
public void onCreate() {
super.onCreate();
final MediaPlayer mp = MediaPlayer.create(this, R.raw.title_music);
mp.setLooping(true);
mPlayer = new CarefulMediaPlayer(mp,this);
}
#Override
public int onStartCommand(final Intent intent, final int flags, final int startId) {
mPlayer.start();
return 1;
}
#Override
public void onStart(final Intent intent, final int startId) {
}
public IBinder onUnBind(final Intent arg0) {
return null;
}
public static void onStop() {
mPlayer.stop();
}
public static void onPause() {
if (mPlayer!=null) {
mPlayer.pause();
}
}
public static void onResume() {
if (mPlayer!=null) {
mPlayer.start();
}
}
#Override
public void onDestroy() {
mPlayer.stop();
mPlayer = null;
}
#Override
public void onLowMemory() {
}
}
Improved Base Activity Class
import android.app.Activity;
import android.content.Intent;
import android.os.PowerManager;
import android.telephony.TelephonyManager;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.ViewGroup.LayoutParams;
import android.widget.ImageView;
public abstract class BetterActivity extends Activity {
private boolean isHome = true;
#Override
protected void onResume() {
System.gc();
super.onResume();
MusicService.onResume();
isHome = true;
}
#Override
protected void onPause() {
if (((TelephonyManager)getSystemService(TELEPHONY_SERVICE)).getCallState()==TelephonyManager.CALL_STATE_RINGING
|| !((PowerManager)getSystemService(POWER_SERVICE)).isScreenOn()) {
MusicService.onPause();
}
super.onPause();
System.gc();
}
#Override
public boolean onKeyDown (final int keyCode, final KeyEvent ke) {
switch (keyCode) {
case KeyEvent.KEYCODE_BACK:
isHome = false;
default:
return super.onKeyDown(keyCode, ke);
}
}
#Override
public void startActivity(final Intent i) {
isHome = false;
super.startActivity(i);
}
#Override
protected void onUserLeaveHint() {
if (isHome) {
MusicService.onPause();
}
super.onUserLeaveHint();
}
}
First here is some code. Below I'll give you an explanation.
public class MusicService extends Service {
// service binder
private final IBinder mBinder = new LocalBinder();
// music player controling game music
private static CarefulMediaPlayer mPlayer = null;
#Override
public void onCreate() {
// load music file and create player
MediaPlayer mediaPlayer = MediaPlayer.create(this, R.raw.title_music);
mediaPlayer.setLooping(true);
mPlayer = new CarefulMediaPlayer(mediaPlayer, this);
}
#Override
public void onDestroy() {
super.onDestroy();
}
// =========================
// Player methods
// =========================
public void musicStart() {
mPlayer.start();
}
public void musicStop() {
mPlayer.stop();
}
public void musicPause() {
mPlayer.pause();
}
/**
* Class for clients to access. Because we know this service always runs in
* the same process as its clients, we don't need to deal with IPC.
*/
public class LocalBinder extends Binder {
MusicService getService() {
return MusicService.this;
}
}
#Override
public IBinder onBind(Intent arg0) {
return mBinder;
}
}
Activity:
public class StartupActivity extends Activity {
// bounded service
private static MusicService mBoundService;
// whetere service is bounded or not
private boolean mIsBound;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_startup);
doBindService();
// HOW TO WORK WITH THE SERVICE:
// call the following methods whenever
// you want to interact with you
// music player
// ===================================
// call this e.g. in onPause() of your Activities
StartupActivity.getService().musicPause();
// call this e.g. in onStop() of your Activities
StartupActivity.getService().musicStop();
// call this e.g. in onResume() of your Activities
StartupActivity.getService().musicStart();
}
#Override
public void onDestroy() {
super.onDestroy();
doUnbindService();
}
private final ServiceConnection mServiceConnection = new ServiceConnection() {
#Override
public void onServiceConnected(ComponentName className, IBinder service) {
setService(((MusicService.LocalBinder) service).getService());
}
#Override
public void onServiceDisconnected(ComponentName className) {
setService(null);
}
};
private void doBindService() {
Intent service = new Intent(getBaseContext(), MusicService.class);
// start service and bound it
startService(service);
bindService(new Intent(this, MusicService.class), mServiceConnection, Context.BIND_AUTO_CREATE);
mIsBound = true;
}
private void doUnbindService() {
if (mIsBound) {
// Detach existing connection.
unbindService(mServiceConnection);
mIsBound = false;
}
}
public static MusicService getService() {
return mBoundService;
}
private static void setService(MusicService mBoundService) {
StartupActivity.mBoundService = mBoundService;
}
}
First of all you got a Service which runs in background. This service creates the mediaPlayer object as you did. With the localBinder you can bind the Service in your Activity(ies) and access it like a normal Java-Object.
The Activity I've posted bindes the Service. In it's onCreate() method you can find a way how to interact with your mediaPlayer.
You can bind any Activity to your Service.
Another Solution:
public class CarefulMediaPlayer {
final SharedPreferences sp;
final MediaPlayer mp;
private boolean isPlaying = false;
private static CarefulMediaPlayer instance;
public CarefulMediaPlayer(final MediaPlayer mp, final MusicService ms) {
sp = PreferenceManager.getDefaultSharedPreferences(ms.getApplicationContext());
this.mp = mp;
instance = this;
}
public static CarefulMediaPlayer getInstance() {
return instance;
}
public void start() {
if (sp.getBoolean("com.embed.candy.music", true) && !isPlaying) {
mp.start();
isPlaying = true;
}
}
public void pause() {
if (isPlaying) {
mp.pause();
isPlaying = false;
}
}
public void stop() {
isPlaying = false;
try {
mp.stop();
mp.release();
} catch (final Exception e) {}
}
}
Then you can pause, play and stop the music by calling CarefulMediaPlayer.getInstance().play();
I did it this way and I'm pleased with the result:
1st create the service:
public class LocalService extends Service
{
// This is the object that receives interactions from clients. See RemoteService for a more complete example.
private final IBinder mBinder = new LocalBinder();
private MediaPlayer player;
/**
* Class for clients to access. Because we know this service always runs in
* the same process as its clients, we don't need to deal with IPC.
*/
public class LocalBinder extends Binder
{
LocalService getService()
{
return LocalService.this;
}
}
#Override
public void onCreate()
{
}
#Override
public int onStartCommand(Intent intent, int flags, int startId)
{
// We want this service to continue running until it is explicitly stopped, so return sticky.
return START_STICKY;
}
#Override
public void onDestroy()
{
destroy();
}
#Override
public IBinder onBind(Intent intent)
{
return mBinder;
}
public void play(int res)
{
try
{
player = MediaPlayer.create(this, res);
player.setLooping(true);
player.setVolume(0.1f, 0.1f);
player.start();
}
catch(Exception e)
{
e.printStackTrace();
}
}
public void pause()
{
if(null != player && player.isPlaying())
{
player.pause();
player.seekTo(0);
}
}
public void resume()
{
try
{
if(null != player && !player.isPlaying())
{
player.start();
}
}
catch(Exception e)
{
e.printStackTrace();
}
}
public void destroy()
{
if(null != player)
{
if(player.isPlaying())
{
player.stop();
}
player.release();
player = null;
}
}
}
2nd, create a base activity and extend all your activities in witch you wish to play the background music from it:
public class ActivityBase extends Activity
{
private Context context = ActivityBase.this;
private final int [] background_sound = { R.raw.azilum_2, R.raw.bg_sound_5 };
private LocalService mBoundService;
private boolean mIsBound = false;
#Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
doBindService();
}
#Override
protected void onStart()
{
super.onStart();
try
{
if(null != mBoundService)
{
Random rand = new Random();
int what = background_sound[rand.nextInt(background_sound.length)];
mBoundService.play(what);
}
}
catch(Exception e)
{
e.printStackTrace();
}
}
#Override
protected void onStop()
{
super.onStop();
basePause();
}
protected void baseResume()
{
try
{
if(null != mBoundService)
{
mBoundService.resume();
}
}
catch(Exception e)
{
e.printStackTrace();
}
}
protected void basePause()
{
try
{
if(null != mBoundService)
{
mBoundService.pause();
}
}
catch(Exception e)
{
e.printStackTrace();
}
}
private ServiceConnection mConnection = new ServiceConnection()
{
public void onServiceConnected(ComponentName className, IBinder service)
{
// This is called when the connection with the service has been
// established, giving us the service object we can use to
// interact with the service. Because we have bound to a explicit
// service that we know is running in our own process, we can
// cast its IBinder to a concrete class and directly access it.
mBoundService = ((LocalService.LocalBinder) service).getService();
if(null != mBoundService)
{
Random rand = new Random();
int what = background_sound[rand.nextInt(background_sound.length)];
mBoundService.play(what);
}
}
public void onServiceDisconnected(ComponentName className)
{
// This is called when the connection with the service has been
// unexpectedly disconnected -- that is, its process crashed.
// Because it is running in our same process, we should never
// see this happen.
mBoundService = null;
if(null != mBoundService)
{
mBoundService.destroy();
}
}
};
private void doBindService()
{
// Establish a connection with the service. We use an explicit
// class name because we want a specific service implementation that
// we know will be running in our own process (and thus won't be
// supporting component replacement by other applications).
Intent i = new Intent(getApplicationContext(), LocalService.class);
bindService(i, mConnection, Context.BIND_AUTO_CREATE);
mIsBound = true;
}
private void doUnbindService()
{
if (mIsBound)
{
// Detach our existing connection.
unbindService(mConnection);
mIsBound = false;
}
}
#Override
protected void onDestroy()
{
super.onDestroy();
doUnbindService();
}
}
And that's it, now you have background sound in all the activities that are extended from ActivityBase.
You can even control the pause / resume functionality by calling basePause() / baseResume().
Don't forget to declare the service in manifest:
<service android:name="com.gga.screaming.speech.LocalService" />
In the startup activity we are binding and Starting Service seperately. This is wrong since service will keep running after activity exits as we haven't called stopService() anywhere. So The part ' startService(service) ' should be removed as bind service is already "Auto-Creating" the service too.
Please correct me if anyone got opposite results
startService(service);// remove this part
bindService(new Intent(this, MusicService.class), mServiceConnection, Context.BIND_AUTO_CREATE);