Service destroyed, Activity still does service's work - android

This is a pretty strange problem. I have a book that I have been going through (The Android Developer's Cookbook)
I am making a pretty basic app (at least, I think it is basic)
The problem I am having is this. When the service I create is stopped, the activity does the service's work.
I want to monitor the Z Axis reading on my phone (in the background, always)
Here is my project structure:
TiltMonitorActivity
TiltMonitorService
From TiltMonitorActivity:
#Override
public void onClick(View v) {
boolean error = false;
if (tbService.isChecked()) {
try {
startService(backgroundService);
}
catch (Exception e) {
error = true;
}
finally {
if (error)
{
errorToast();
}
}
}
else if (!tbService.isChecked()) {
try {
stopService(backgroundService);
}
catch (Exception e){
error = true;
}
finally {
if (error)
{
errorToast();
}
}
}
}
});
I also put this in onBackPressed(), onPause, onDestroy
finish();
The intent I create when starting/stopping service
final Intent backgroundService = new Intent(this, TiltMonitorService.class);
From TiltMonitorService:
import android.app.Service;
import android.content.Context;
import android.content.Intent;
import android.hardware.Sensor;
import android.hardware.SensorEvent;
import android.hardware.SensorEventListener;
import android.hardware.SensorManager;
import android.os.IBinder;
import android.os.Vibrator;
import android.widget.Toast;
public class TiltMonitorService extends Service {
private SensorManager sensorManager = null;
private Vibrator vibrator = null;
private float[] accData = new float[3];
// These are for manual config
private float FORWARD_THRESHOLD = 5f;
private float BACKWARD_THRESHOLD = -5f;
// These are for auto config
// The phone will face forward, so a positive Z Axis means user is leaning backwards
// and that a negative Z Axis the user is leaning forward
private float AUTO_FORWARD_THRESHOLD = -1.5f;
private float AUTO_BACKWARD_THRESHOLD = 3.5f;
public static TiltMonitorActivity MAIN_ACTIVITY = null;
public static void setMainActivity(TiltMonitorActivity activity)
{
MAIN_ACTIVITY = activity;
}
#Override
public IBinder onBind(Intent arg0) {
// TODO Auto-generated method stub
return null;
}
#Override
public void onCreate() {
super.onCreate();
sensorManager = (SensorManager)getSystemService(Context.SENSOR_SERVICE);
vibrator = (Vibrator)getSystemService(Context.VIBRATOR_SERVICE);
sensorManager.registerListener( tiltListener,
sensorManager.getDefaultSensor(Sensor.TYPE_ACCELEROMETER),
SensorManager.SENSOR_DELAY_NORMAL);
Toast.makeText(this, "Service created", Toast.LENGTH_LONG).show();
}
#Override
public void onDestroy() {
super.onDestroy();
Toast.makeText(this, "Service destroyed", Toast.LENGTH_LONG).show();
}
private SensorEventListener tiltListener = new SensorEventListener() {
#Override
public void onAccuracyChanged(Sensor sensor, int accuracy) {
// TODO Auto-generated method stub
}
#Override
public void onSensorChanged(SensorEvent event) {
accData[0] = event.values[0];
accData[1] = event.values[1];
accData[2] = event.values[2];
checkData(accData);
}
};
private void checkData(float[] accData)
{
if ((accData[2] < AUTO_FORWARD_THRESHOLD) || (accData[2] > AUTO_BACKWARD_THRESHOLD))
{
vibrator.vibrate(100);
}
}
#Override
public void onStart(Intent intent, int startId) {
super.onStart(intent, startId);
}
}
Again, I get the Toast that the service has been started and stopped when hitting the ToggleButton in the activity.
But the task still happens. (Vibrates when below or above set thresholds)
When I open up a task killer, the service isn't running. Only the activity is (and killing it kills the vibration)
I'm not sure what words to search for, I couldn't find any one else with the same problem. I tried to post only relevant code in the Activity to avoid clutter. The service is posted in its entirety. If more is needed, I will put it up promptly.
Thanks you guys for any insight given

at a guess, because you register the listener in onCreate without unregistering it in onDestroy
in the service, that is.

Related

How to display a notification from service when activity gets destroyed

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.

Update Android Service TextView from Activity/ Static Method

Background:
I've created a custom service as:
public class FloatingViewService extends Service {
public static FloatingViewService self;
onCreate() {
self = this;
addView(....)
}
...
...
public void updateText ( String newText) { this.textView.setText(newText) };
}
OnCreate event of this service, it sets a view using WindowManager.addView(...) and also set an instance pointer in self variable for future use.
Now this view is just a textview, that stays on the top of activities, regardless.
What I want to achieve:
I want to send some data from a static method that runs using ExecutorService instance, which should update textview text.
How I use this service:
Inside of an activity, I make a call to a static method that logs some values:
public class MyActivity: Activity
{
public void log() {
LogUtil.log(new Runnable() {
#Override
public void run() {
//log api call
FloatingViewService.self.updateText("New Text");
}
}) ;
}
}
Now you can see that I am making a call to an updateText method present in service, from different thread.
Here is how the LogUtil is:
public class LogUtil {
private static ExecutorService taskExecutorService = ThreadUtils.createTimedExecutorService(TASK_POOL_SIZE, TASK_POOL_IDLE_ALIVE_SECONDS,
TimeUnit.SECONDS, new LowPriorityThreadFactory());
public static log(Runnable runnable) {
taskExecutorService.submit(new Runnable() {
#Override
public void run() {
try {
runnable.run();
} catch (Exception ex) {
../
}
}
});
Now the problem is, it cannot update textview text. I can understand it is due to thread. But I have no clue on how to achieve it - is there any UIthread for service ?
Here is my code for example .. you shuold be able to pick the necesary parts from it. as Selvin said you have to create an Incoming handler on both sides to send information from one thread to the other...
Here is my service code
import java.util.ArrayList;
import java.util.Timer;
import java.util.TimerTask;
import com.pekam.myandroidtheme.*;
import android.app.Notification;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.app.Service;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.IBinder;
import android.os.Message;
import android.os.Messenger;
import android.os.RemoteException;
import android.util.Log;
public class MyService extends Service {
private NotificationManager nm;
private Timer timer = new Timer();
private int counter = 0, incrementby = 1;
private static boolean isRunning = false;
ArrayList<Messenger> mClients = new ArrayList<Messenger>(); // Keeps track of all current registered clients.
int mValue = 0; // Holds last value set by a client.
static final int MSG_REGISTER_CLIENT = 1;
static final int MSG_UNREGISTER_CLIENT = 2;
static final int MSG_SET_INT_VALUE = 3;
static final int MSG_SET_STRING_VALUE = 4;
final Messenger mMessenger = new Messenger(new IncomingHandler()); // Target we publish for clients to send messages to IncomingHandler.
#Override
public IBinder onBind(Intent intent) {
return mMessenger.getBinder();
}
class IncomingHandler extends Handler { // Handler of incoming messages from clients.
#Override
public void handleMessage(Message msg) {
switch (msg.what) {
case MSG_REGISTER_CLIENT:
mClients.add(msg.replyTo);
break;
case MSG_UNREGISTER_CLIENT:
mClients.remove(msg.replyTo);
break;
case MSG_SET_INT_VALUE:
incrementby = msg.arg1;
break;
default:
super.handleMessage(msg);
}
}
}
private void sendMessageToUI(int intvaluetosend) {
for (int i=mClients.size()-1; i>=0; i--) {
try {
// Send data as an Integer
mClients.get(i).send(Message.obtain(null, MSG_SET_INT_VALUE, intvaluetosend, 0));
//Send data as a String
Bundle b = new Bundle();
b.putString("str1", "ab" + intvaluetosend + "cd");
Message msg = Message.obtain(null, MSG_SET_STRING_VALUE);
msg.setData(b);
mClients.get(i).send(msg);
} catch (RemoteException e) {
// The client is dead. Remove it from the list; we are going through the list from back to front so this is safe to do inside the loop.
mClients.remove(i);
}
}
}
#Override
public void onCreate() {
super.onCreate();
Log.i("MyService", "Service Started.");
showNotification();
timer.scheduleAtFixedRate(new TimerTask(){ public void run() {onTimerTick();}}, 0, 100L);
isRunning = true;
}
private void showNotification() {
nm = (NotificationManager)getSystemService(NOTIFICATION_SERVICE);
// In this sample, we'll use the same text for the ticker and the expanded notification
CharSequence text = getText(R.string.service_started);
// Set the icon, scrolling text and timestamp
Notification notification = new Notification(R.drawable.ic_launcher, text, System.currentTimeMillis());
// The PendingIntent to launch our activity if the user selects this notification
PendingIntent contentIntent = PendingIntent.getActivity(this, 0, new Intent(this, TabBarActivity.class), 0);
// Set the info for the views that show in the notification panel.
notification.setLatestEventInfo(this, getText(R.string.service_label), text, contentIntent);
// Send the notification.
// We use a layout id because it is a unique number. We use it later to cancel.
nm.notify(R.string.service_started, notification);
}
#Override
public int onStartCommand(Intent intent, int flags, int startId) {
Log.i("MyService", "Received start id " + startId + ": " + intent);
return START_STICKY; // run until explicitly stopped.
}
public static boolean isRunning()
{
return isRunning;
}
private void onTimerTick() {
Log.i("TimerTick", "Timer doing work." + counter);
try {
counter += incrementby;
sendMessageToUI(counter);
} catch (Throwable t) { //you should always ultimately catch all exceptions in timer tasks.
Log.e("TimerTick", "Timer Tick Failed.", t);
}
}
#Override
public void onDestroy() {
super.onDestroy();
if (timer != null) {timer.cancel();}
counter=0;
nm.cancel(R.string.service_started); // Cancel the persistent notification.
Log.i("MyService", "Service Stopped.");
isRunning = false;
}
}
here is my android form app code
import android.app.Activity;
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.os.Messenger;
import android.os.RemoteException;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.TextView;
import com.pekam.myandroidtheme.*;
public class MyServiceControllerActivity extends Activity {
Button btnStart, btnStop, btnBind, btnUnbind, btnUpby1, btnUpby10;
TextView textStatus, textIntValue, textStrValue;
Messenger mService = null;
boolean mIsBound;
final Messenger mMessenger = new Messenger(new IncomingHandler());
class IncomingHandler extends Handler {
#Override
public void handleMessage(Message msg) {
switch (msg.what) {
case MyService.MSG_SET_INT_VALUE:
textIntValue.setText("Int Message: " + msg.arg1);
break;
case MyService.MSG_SET_STRING_VALUE:
String str1 = msg.getData().getString("str1");
textStrValue.setText("Str Message: " + str1);
break;
default:
super.handleMessage(msg);
}
}
}
private ServiceConnection mConnection = new ServiceConnection() {
public void onServiceConnected(ComponentName className, IBinder service) {
mService = new Messenger(service);
textStatus.setText("Attached.");
try {
Message msg = Message.obtain(null, MyService.MSG_REGISTER_CLIENT);
msg.replyTo = mMessenger;
mService.send(msg);
} catch (RemoteException e) {
// In this case the service has crashed before we could even do anything with it
}
}
public void onServiceDisconnected(ComponentName className) {
// This is called when the connection with the service has been unexpectedly disconnected - process crashed.
mService = null;
textStatus.setText("Disconnected.");
}
};
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.exampleservice);
btnStart = (Button)findViewById(R.id.btnStart);
btnStop = (Button)findViewById(R.id.btnStop);
btnBind = (Button)findViewById(R.id.btnBind);
btnUnbind = (Button)findViewById(R.id.btnUnbind);
textStatus = (TextView)findViewById(R.id.textStatus);
textIntValue = (TextView)findViewById(R.id.textIntValue);
textStrValue = (TextView)findViewById(R.id.textStrValue);
btnUpby1 = (Button)findViewById(R.id.btnUpby1);
btnUpby10 = (Button)findViewById(R.id.btnUpby10);
btnStart.setOnClickListener(btnStartListener);
btnStop.setOnClickListener(btnStopListener);
btnBind.setOnClickListener(btnBindListener);
btnUnbind.setOnClickListener(btnUnbindListener);
btnUpby1.setOnClickListener(btnUpby1Listener);
btnUpby10.setOnClickListener(btnUpby10Listener);
restoreMe(savedInstanceState);
CheckIfServiceIsRunning();
}
#Override
protected void onSaveInstanceState(Bundle outState) {
super.onSaveInstanceState(outState);
outState.putString("textStatus", textStatus.getText().toString());
outState.putString("textIntValue", textIntValue.getText().toString());
outState.putString("textStrValue", textStrValue.getText().toString());
}
private void restoreMe(Bundle state) {
if (state!=null) {
textStatus.setText(state.getString("textStatus"));
textIntValue.setText(state.getString("textIntValue"));
textStrValue.setText(state.getString("textStrValue"));
}
}
private void CheckIfServiceIsRunning() {
//If the service is running when the activity starts, we want to automatically bind to it.
if (MyService.isRunning()) {
doBindService();
}
}
private OnClickListener btnStartListener = new OnClickListener() {
public void onClick(View v){
startService(new Intent(MyServiceControllerActivity.this, MyService.class));
}
};
private OnClickListener btnStopListener = new OnClickListener() {
public void onClick(View v){
doUnbindService();
stopService(new Intent(MyServiceControllerActivity.this, MyService.class));
}
};
private OnClickListener btnBindListener = new OnClickListener() {
public void onClick(View v){
doBindService();
}
};
private OnClickListener btnUnbindListener = new OnClickListener() {
public void onClick(View v){
doUnbindService();
}
};
private OnClickListener btnUpby1Listener = new OnClickListener() {
public void onClick(View v){
sendMessageToService(1);
}
};
private OnClickListener btnUpby10Listener = new OnClickListener() {
public void onClick(View v){
sendMessageToService(10);
}
};
private void sendMessageToService(int intvaluetosend) {
if (mIsBound) {
if (mService != null) {
try {
Message msg = Message.obtain(null, MyService.MSG_SET_INT_VALUE, intvaluetosend, 0);
msg.replyTo = mMessenger;
mService.send(msg);
} catch (RemoteException e) {
}
}
}
}
void doBindService() {
bindService(new Intent(this, MyService.class), mConnection, Context.BIND_AUTO_CREATE);
mIsBound = true;
textStatus.setText("Binding.");
}
void doUnbindService() {
if (mIsBound) {
// If we have received the service, and hence registered with it, then now is the time to unregister.
if (mService != null) {
try {
Message msg = Message.obtain(null, MyService.MSG_UNREGISTER_CLIENT);
msg.replyTo = mMessenger;
mService.send(msg);
} catch (RemoteException e) {
// There is nothing special we need to do if the service has crashed.
}
}
// Detach our existing connection.
unbindService(mConnection);
mIsBound = false;
textStatus.setText("Unbinding.");
}
}
#Override
protected void onDestroy() {
super.onDestroy();
try {
doUnbindService();
} catch (Throwable t) {
Log.e("TabBarActivity", "Failed to unbind from the service", t);
}
}
}
You need to stay on UIThread to update UI. A solution may be:
Create a static reference of activity. Remember to set it on resume method of activity and to unset it on pause method.
On the service side you can invoke a method of activiy to update UI.
Translating those operations in pseudocode. The activity will become :
public class MainActivity extends Activity {
public static MainActivity reference;
...
public onResume() {
reference=this;
}
public onPause() {
reference=null;
}
public void needToUpdateText(final String text)
{
runOnUiThread(new Runnable() {
public void run() {
Log.d("UI thread", "I am the UI thread with text "+text);
});
}
}
}
And the service class:
public class FloatingViewService extends Service {
...
public void updateText ( String newText)
{
if (MainActivity.reference!=null)
{
MainActivity.reference.needUpdateText(newText);
}
};
}

Making same android activity class as a service ondestroy

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.

Accelerometer not working

I am new to android. I want to play a audio file when my mobile get shaking. I know the acceleration code. But when I wrote mediaplayer code I didn't get any output from my device.
public void onSensorChanged(SensorEvent event) {
// TODO Auto-generated method stub
if (event.sensor.getType() == Sensor.TYPE_ACCELEROMETER) {
getAccelerometer(event);
MediaPlayer mPlayer1 = MediaPlayer.create(null, R.raw.hello);
try {
mPlayer1.prepare();
} catch (IllegalStateException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
mPlayer1.start();
}
}
You should provide a Context while creating a MediaPlayer. E.g.
MediaPlayer.create(getApplicationContext(), R.raw.hello);
Also, it would advisable to create a MediaPlayer beforehand.
Modify ur code like this. Hope this works.
MediaPlayer mPlayer1 = MediaPlayer.create(null, R.raw.hello);
into
MediaPlayer mPlayer1 = MediaPlayer.create(getApplicationContext(), R.raw.hello);
Use below class for shake listener,
import java.util.List;
import android.hardware.Sensor;
import android.hardware.SensorEvent;
import android.hardware.SensorEventListener;
import android.hardware.SensorManager;
public class ShakeListener implements SensorEventListener{
private MyShakeListener mOnShakeListener = null;
private SensorManager mSensorManager;
private double mTotalForcePrev;
private double mForceThreshHold = 1.5f;
private List<Sensor> mSensors;
private Sensor mAccelerationSensor;
public ShakeListener(SensorManager sm){
mSensorManager = sm;
mSensors = mSensorManager.getSensorList(Sensor.TYPE_ACCELEROMETER);
if(mSensors.size() > 0) {
mAccelerationSensor = mSensors.get(0);
mSensorManager.registerListener(this, mAccelerationSensor, SensorManager.SENSOR_DELAY_GAME);
}
}
public void setForceThreshHold(double threshhold){
mForceThreshHold = threshhold;
}
public double getForceThreshHold(){
return mForceThreshHold;
}
public void onAccuracyChanged(Sensor sensor, int accuracy) {}
public void onSensorChanged(SensorEvent event) {
double totalForce = 0.0f;
totalForce += Math.pow(event.values[0]/SensorManager.GRAVITY_EARTH, 2.0);
totalForce += Math.pow(event.values[1]/SensorManager.GRAVITY_EARTH, 2.0);
totalForce += Math.pow(event.values[2]/SensorManager.GRAVITY_EARTH, 2.0);
totalForce = Math.sqrt(totalForce);
if((totalForce < mForceThreshHold) && (mTotalForcePrev > mForceThreshHold)) {
OnShake();
}
mTotalForcePrev = totalForce;
}
public void setOnShakeListener(MyShakeListener listener)
{
mOnShakeListener = listener;
}
private void OnShake()
{
if(mOnShakeListener!=null)
{
mOnShakeListener.onShake();
}
}
}
public interface MyShakeListener {
public abstract void onShake();
}
and add the lisener class on your main class like this,
public class MainActivity extends Activity
{
MediaPlayer defaultPlayer;
#Override
public void onCreate(Bundle bundle)
{
super.onCreate(bundle);
setContentView(R.layout.playerscree);
ShakeListener myShake = new ShakeListener((SensorManager)getSystemService(Context.SENSOR_SERVICE));
myShake.setForceThreshHold(1.9);
myShake.setOnShakeListener(new MyShakeListener()
{
#Override
public void onShake()
{
// do ur work here...
defaultPlayer= MediaPlayer.create(getApplicationContext(), R.raw.music);
defaultPlayer.start();
}
});
}

Android comprehensive failproof music service across multiple activities

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);

Categories

Resources