Service and background music codes -updated- - android

i am making a quiz game that has a background music.i saw a very helpful source code using service and background music here http://marakana.com/forums/android/examples/60.html but my problem is i want to add another sound on my EasyOne.class in my correct answer button. what will i add or edit to make it work. my point is. everytime i click the a button of my easyone.class it will play a sound and if i want to turn off all my music even the corrrect button and the background music it will turn off if ill go to my settings.class and click the OFF button. hope you can help me.really appriciate it.
here is my code for my service
public class MusicService extends Service {
private static final String TAG = "";
MediaPlayer player;
#Override
public IBinder onBind(Intent intent) {
return null;
}
#Override
public void onCreate() {
Toast.makeText(this, "ON", Toast.LENGTH_LONG).show();
Log.d(TAG, "onCreate");
player = MediaPlayer.create(this, R.raw.bsound);
player.setLooping(false);
}
#Override
public void onDestroy() {
Toast.makeText(this, "OFF", Toast.LENGTH_LONG).show();
Log.d(TAG, "onDestroy");
player.stop();
}
#Override
public void onStart(Intent intent, int startid) {
Toast.makeText(this, "ON", Toast.LENGTH_LONG).show();
Log.d(TAG, "onStart");
player.start();
}
}
and here is my for my settings
public class Settings extends Activity implements OnClickListener {
private static final String TAG = "";
Button on, off, back;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.settings);
back = (Button) findViewById(R.id.btn_backk);
on = (Button) findViewById(R.id.btn_on);
off = (Button) findViewById(R.id.btn_off);
back.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Toast.makeText(getApplicationContext(),"Back",
Toast.LENGTH_SHORT).show();
Intent intent = new Intent(getApplicationContext(),MainMenu.class);
startActivity(intent);
}
});
on.setOnClickListener(this);
off.setOnClickListener(this);
}
public void onClick(View src) {
switch (src.getId()) {
case R.id.btn_on:
Log.d(TAG, "onClick: starting srvice");
startService(new Intent(this, MusicService.class));
break;
case R.id.btn_off:
Log.d(TAG, "onClick: stopping srvice");
stopService(new Intent(this, MusicService.class));
break;
}
}
}
my EasyOne.class - (class of my level 1 easy mode)
public class EasyOne extends Activity {
ImageButton a, b, c;
Intent intent ;
CountDownTimer cdt;
TextView timer;
MediaPlayer clap;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.easyone);
a = (ImageButton) findViewById(R.id.ib_a);
b = (ImageButton) findViewById(R.id.ib_b);
c = (ImageButton) findViewById(R.id.ib_c);
timer = (TextView) findViewById(R.id.tv_timer);
cdt = new CountDownTimer(5000,1000) {
#Override
public void onTick(long millisUntilFinished) {
timer.setText("seconds remaining: " + millisUntilFinished / 1000);
}
#Override
public void onFinish() {
timer.setText("TIMES UP!");
intent = new Intent(getApplicationContext(),TimesUp.class);
startActivity(intent);
}
};
intent = new Intent(getApplicationContext(),ChoiceTwo.class);
a.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
startActivity(intent);
//i want to add a sound here that will play if they click this button and can turn it OFF on the setting.class OFF button
cdt.cancel();
Intent intent = new Intent(getApplicationContext(),ChoiceTwo.class);
startActivity(intent);
}
});
cdt.start();
}
}

In the main activity of your code (where the game actually starts), put:
startService(new Intent(MusicService.class))
This will start your music playing as soon as the game starts

Related

When resuming music player then music resumes but not the play and pause button states

Below is the code which I use.By this code the background music plays on all activities.But when I come back to this activity using home button then music plays normally but the drawables will not resumed. That Mean if music is played and I went back to that activity via home button then play button is shown rather than the pause button but I want that if music played on resume then button is pause and if not then show play button.
Can you tell what to do with play and pause buttons on resuming activties?
public class RadioActivity extends ActionBarActivity implements RadioListener{
private final String[] RADIO_URL = {"url "};
private ActionMenuView amvMenu;
ImageButton mButtonControlStart;
TextView mTextViewControl;
RadioManager mRadioManager = RadioManager.with(this);
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_radio);
mButtonControlStart = (ImageButton) findViewById(R.id.buttonControlStart);
mRadioManager.registerListener(this);
mRadioManager.setLogging(true);
initializeUI();
mButtonControlStart.setBackgroundResource(R.drawable.play);
Toolbar toolbarBottom = (Toolbar) findViewById(R.id.toolbar);
toolbarBottom.setTitle("Radio");
amvMenu = (ActionMenuView) toolbarBottom.findViewById(R.id.amvMenu);
amvMenu.setOnMenuItemClickListener(new ActionMenuView.OnMenuItemClickListener() {
// toolbarBottom.setOnMenuItemClickListener(new Toolbar.OnMenuItemClickListener() {
public boolean onMenuItemClick(MenuItem item) {
switch(item.getItemId()){
case R.id.activity_aboutus:
// TODO
Intent intent=new Intent(RadioActivity.this,Contact_us.class);
startActivity(intent);
break;
// TODO: Other cases
case R.id.menu_refresh:
// TODO
Intent intent1=new Intent(RadioActivity.this,Web.class);
startActivity(intent1);
break;
case R.id.menu_about:
Intent intent2=new Intent(RadioActivity.this,Song_rqst.class);
startActivity(intent2);
break;
case R.id.menu_item_share:
Intent intent3=new Intent(RadioActivity.this,Ratee.class);
startActivity(intent3);
break;
}
return true;
}
});
}
public void initializeUI() {
mButtonControlStart = (ImageButton) findViewById(R.id.buttonControlStart);
mTextViewControl = (TextView) findViewById(R.id.textviewControl);
mButtonControlStart.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if (!mRadioManager.isPlaying()) {
mRadioManager.startRadio(RADIO_URL[0]);
mButtonControlStart.setBackgroundResource(R.drawable.end);
}
else {
mRadioManager.stopRadio();
mButtonControlStart.setBackgroundResource(R.drawable.play);
}
}
});
}
#Override
protected void onResume() {
super.onResume();
mRadioManager.connect();
}
#Override
protected void onDestroy() {
super.onDestroy();
mRadioManager.disconnect();
}
#Override
public void onRadioLoading() {
runOnUiThread(new Runnable() {
#Override
public void run() {
//TODO Do UI works here.
mTextViewControl.setText("RADIO STATE : LOADING...");
}
});
}
#Override
public void onRadioConnected() {
}
#Override
public void onRadioStarted() {
runOnUiThread(new Runnable() {
#Override
public void run() {
//TODO Do UI works here.
mTextViewControl.setText("RADIO STATE : PLAYING...");
}
});
}
#Override
public void onRadioStopped() {
runOnUiThread(new Runnable() {
#Override
public void run() {
//TODO Do UI works here
mTextViewControl.setText("RADIO STATE : STOPPED.");
}
});
}
#Override
public void onMetaDataReceived(String s, String s1) {
//TODO Check metadata values. Singer name, song name or whatever you have.
}
#Override
public void onError() {
}
Whenever you come back to your Music Play Activity Oncreate() is not called so your drawable resource load on Onpause() or Onstart(), Everytime Oncreate() is not calling.

How to stop a service in block method in Android?

I run the code and get the following result, but I hope that the App can run at the order "A" -> "Service OnDestroy" -> "B" -> "C", how can I do ?
In My Way 2 section, I try to place the code into the function new Handler().postDelayed(new Runnable() {}, it's OK , it ran at the order "A" -> "Service OnDestroy" ->"B" ->"C",
I don't konw why the way can success, I don't know if the way is good way!
Result
11-13 10:04:32.137 27947-27947/info.dodata.screenrecorder E/My﹕ A
11-13 10:04:32.147 27947-27947/info.dodata.screenrecorder E/My﹕ B
11-13 10:04:32.157 27947-27947/info.dodata.screenrecorder E/My﹕ C
11-13 10:04:32.157 27947-27947/info.dodata.screenrecorder E/My﹕ Service OnDestroy
UIAbou.cs
public class UIAbout extends Activity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.layout_about);
Intent intent1 = new Intent(UIAbout.this,bll.RecordService.class);
startService(intent1);
Button btnReturn = (Button) findViewById(R.id.btnReturn);
btnReturn.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
Log.e("My", "A");
Intent intent1 = new Intent(UIAbout.this,bll.RecordService.class);
stopService(intent1);
Log.e("My", "B");
Toast.makeText(getApplicationContext(), "OK", Toast.LENGTH_LONG).show();
Log.e("My", "C");
}
});
}
}
RecordService.cs
public class RecordService extends Service {
private Context mContext;
#Override
public IBinder onBind(Intent intent) {
// TODO Auto-generated method stub
return null;
}
#Override
public void onCreate(){
}
#Override
public void onDestroy(){
Log.e("My","Service OnDestroy");
super.onDestroy(); //It seems that the APP is OK if I remove this.
}
#Override
public int onStartCommand(Intent intent, int flags, int startId) {
return super.onStartCommand(intent,flags,startId);
}
}
=======================My Way 1 ======================================
I set a mark isServiceStoped to monitor if Stop Service is finished, but my app is hang up after disply the result "11-13 11:31:23.107 7599-7599/info.dodata.screenrecorder E/My﹕ A"
New UIAbout.cs
public class UIAbout extends Activity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.layout_about);
Intent intent1 = new Intent(UIAbout.this,bll.RecordService.class);
startService(intent1);
Button btnReturn = (Button) findViewById(R.id.btnReturn);
btnReturn.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
Log.e("My", "A");
Intent intent1 = new Intent(UIAbout.this, bll.RecordService.class);
stopService(intent1);
while (RecordService.isServiceStoped==false){
//It block
}
Log.e("My", "B");
Toast.makeText(getApplicationContext(), "OK", Toast.LENGTH_LONG).show();
Log.e("My", "C");
}
});
}
}
New RecordService.cs
public class RecordService extends Service {
public static boolean isServiceStoped=true;
#Override
public IBinder onBind(Intent intent) {
// TODO Auto-generated method stub
return null;
}
#Override
public void onCreate(){
}
#Override
public void onDestroy(){
Log.e("My", "Service OnDestroy");
isServiceStoped=true;
super.onDestroy(); //It seems that the APP is OK if I remove this.
}
#Override
public int onStartCommand(Intent intent, int flags, int startId) {
isServiceStoped=false;
return super.onStartCommand(intent,flags,startId);
}
}
=====================My Way 2==========================================
I try to place the code into the function new Handler().postDelayed(new Runnable() {}, it's OK , it ran at the order "A" -> "Service OnDestroy" ->"B" ->"C",
I don't konw why the way can success, I don't know if the way is good way
The last UIAbout.cs
public class UIAbout extends Activity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.layout_about);
Intent intent1 = new Intent(UIAbout.this,bll.RecordService.class);
startService(intent1);
Button btnReturn = (Button) findViewById(R.id.btnReturn);
btnReturn.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
Log.e("My", "A");
Intent intent1 = new Intent(UIAbout.this, bll.RecordService.class);
stopService(intent1);
new Handler().postDelayed(new Runnable() {
public void run() {
Log.e("My", "B");
Toast.makeText(getApplicationContext(), "OK", Toast.LENGTH_LONG).show();
Log.e("My", "C");
}
}, 1);
}
});
}
}
The last RecordService.cs
public class RecordService extends Service {
private Context mContext;
#Override
public IBinder onBind(Intent intent) {
// TODO Auto-generated method stub
return null;
}
#Override
public void onCreate(){
}
#Override
public void onDestroy(){
Log.e("My", "Service OnDestroy");
super.onDestroy(); //It seems that the APP is OK if I remove this.
}
#Override
public int onStartCommand(Intent intent, int flags, int startId) {
return super.onStartCommand(intent,flags,startId);
}
}
No, you can't stop a service synchronously. stopService() is request to stop the service. It will stop sometime later, as soon as it can.
No, you can't remove super.onDestroy() from your onDestroy() method and still have it work properly.
You can not control the timing to completely stop the running service. Use stopService() and the rest is out of your hands. You can use an handler to monitor is the service has stopped before moving to B although I am not sure why would you do it. Not a good practice.
Yeah you can remove super.onDestroy() in onDestroy but I would not advise you to do so. Your app may run but it will be leaving unwanted resources around.
Here how onDestroy() looks like in the android SDK:
#CallSuper
protected void onDestroy() {
if (DEBUG_LIFECYCLE) Slog.v(TAG, "onDestroy " + this);
mCalled = true;
// dismiss any dialogs we are managing.
if (mManagedDialogs != null) {
final int numDialogs = mManagedDialogs.size();
for (int i = 0; i < numDialogs; i++) {
final ManagedDialog md = mManagedDialogs.valueAt(i);
if (md.mDialog.isShowing()) {
md.mDialog.dismiss();
}
}
mManagedDialogs = null;
}
// close any cursors we are managing.
synchronized (mManagedCursors) {
int numCursors = mManagedCursors.size();
for (int i = 0; i < numCursors; i++) {
ManagedCursor c = mManagedCursors.get(i);
if (c != null) {
c.mCursor.close();
}
}
mManagedCursors.clear();
}
// Close any open search dialog
if (mSearchManager != null) {
mSearchManager.stopSearch();
}
getApplication().dispatchActivityDestroyed(this);
}
* Sample *
There could be some compile errors, but you will get the idea.
public class UIAbout extends Activity {
private Handler mHandler = new Handler();
private Runnable checkServiceHandler;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.layout_about);
Intent intent1 = new Intent(UIAbout.this,bll.RecordService.class);
startService(intent1);
Button btnReturn = (Button) findViewById(R.id.btnReturn);
btnReturn.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
Log.e("My", "A");
Intent intent1 = new Intent(UIAbout.this, bll.RecordService.class);
stopService(intent1);
checkServiceHandler = new Runnable() {
public void run() {
if(RecordService.isServiceStoped){
mHandler.removeCallbacks(checkServiceHandler );
somemethod();
} else{
mHandler.postDelayed(checkServiceHandler, 500);
}
}
};
mHandler.postDelayed(checkServiceHandler, 500); }
});
}
private void somemethod(){
Log.e("My", "B");
Toast.makeText(getApplicationContext(), "OK", Toast.LENGTH_LONG).show();
Log.e("My", "C");
}
}
You should implement your code in a way that you don't care when exactly your service is destroyed.
Anyway. If you really need the exact moment, you can fire an intent from your service using Android's broadcast system.
In your service:
#Override
public void onDestroy()
{
super.onDestroy();
LocalBroadcastManager.getInstance(this).sendBroadcast(new Intent(CONST_SERVICE_DESTROYED));
}
In your activity:
private BroadcastReceiver receiver = new BroadcastReceiver()
{
#Override
public void onReceive(Context context, Intent intent)
{
// your B here
// your C here
}
};
And you need to register and unregister your receiver like this:
#Override
protected void onResume()
{
super.onResume();
LocalBroadcastManager.getInstance(this).registerReceiver(receiver, new IntentFilter(CONST_SERVICE_DESTROYED));
}
#Override
protected void onPause()
{
super.onPause();
LocalBroadcastManager.getInstance(this).unregisterReceiver(receiver);
}
A good explanation and examples of Android's broadcast system can be found here

how do i stop background music when back button is pressed?

i have 2 activities. and 2 different background music plays on both. when i press a button on the first activity it will go to this activity and the changing of music goes smoothly but i want to stop background music when back button is pressed. i tried this but it force closes. is there any other way to do this?
public class Categories extends Activity{
MediaPlayer mp;
#Override
protected void onCreate(Bundle savedInstanceState){
super.onCreate(savedInstanceState);
setContentView(R.layout.categories);
mp = MediaPlayer.create(Categories.this, R.raw.looney);
mp.setLooping(true);
mp.start();
Button cartoonButton = (Button) findViewById(R.id.cartoon);
cartoonButton.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
Intent launchCartoon = new Intent(Categories.this, Cartoon.class);
startActivity(launchCartoon);
}
});
Button superButton = (Button) findViewById(R.id.hero);
superButton.setOnClickListener(new View.OnClickListener()
{
public void onClick(View v) {
Intent launchSuperheroes = new Intent(Categories.this, SuperHeroes.class);
startActivity(launchSuperheroes);
}
});
Button singerButton = (Button) findViewById(R.id.singer);
singerButton.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
Intent launchSinger = new Intent(Categories.this, Singer.class);
startActivity(launchSinger);
}
});
Button famousButton = (Button) findViewById(R.id.famous);
famousButton.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
Intent launchFamous = new Intent(Categories.this, Famous.class);
startActivity(launchFamous);
}
});
}
#Override
protected void onResume() {
super.onResume();
mp.start();
}
#Override
protected void onPause() {
super.onPause();
if (mp != null) {
mp.stop();
mp.release();
mp = null;
}
}
}
You can try this code:
#Override
public void onBackPressed() {
if (player.isPlaying()) {
player.stop();
}
player.release();
super.onBackPressed();
}
Hope this help you :)

how to add soundeffects when clicking a button

I'm having a bit of a trouble,, here's the gen. idea,, I have created an app a simple game-like application.. however the problem is when I try to click the button in the title screen it doesn't play the click sound.. can anyone please help me.. here's the code for my sound
public class Effects extends Activity implements MediaPlayer.OnCompletionListener {
Button mPlay;
MediaPlayer mPlayer;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
mPlay = (Button)findViewById(R.id.btnStart);
mPlay.setOnClickListener(playListener);
setContentView(R.layout.activity_main);
}
#Override
public void onDestroy() {
super.onDestroy();
if(mPlayer != null) {
mPlayer.release();
}
}
private View.OnClickListener playListener = new View.OnClickListener() {
#Override
public void onClick(View v) {
if(mPlayer == null) {
try {
mPlayer = MediaPlayer.create(Effects.this, R.raw.button11);
mPlayer.start();
} catch (Exception e) {
e.printStackTrace();
}
} else {
mPlayer.stop();
mPlayer.release();
mPlayer = null;
}
}
};
#Override
public void onCompletion(MediaPlayer arg0) {
// TODO Auto-generated method stub
}
}
and here's my code for the main java that I want the sound to be played when I clicked this button
public class Main extends Activity implements OnClickListener
{
Button about;
Button Quit;
Button start;
protected void onCreate(Bundle onSavedInstanceState) {
super.onCreate(onSavedInstanceState);
setContentView(R.layout.activity_main);
about = (Button)findViewById(R.id.btnAbout);
about.setOnClickListener(this);
Quit = (Button)findViewById(R.id.btnQuit);
Quit.setOnClickListener(this);
start = (Button)findViewById(R.id.btnStart);
start.setOnClickListener(this);
}
public void onClick(View argo)
{
if(argo.getId()==R.id.btnAbout)
{
Intent i = new Intent(this,About.class);
this.startActivity(i);
}
if(argo.getId()==R.id.btnQuit)
{
Intent intent = new Intent(Intent.ACTION_MAIN);
intent.addCategory(Intent.CATEGORY_HOME);
intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
startActivity(intent);
}
if(argo.getId()==R.id.btnStart)
{
Intent start = new Intent(this,Howto.class);
this.startActivity(start);
Intent svc=new Intent(this,Effects.class);
startService(svc);
}
}
}
Use SoundPool to play your sounds: http://developer.android.com/reference/android/media/SoundPool.html you should init sounds in your onCreate() and then play them back in onClick()
And instead of doing thousands of pointless if(argo.getId()==R.id.btnQuit) (you should at least use else) get familiar with switch/case syntax)

Saving music state

I am having an issue with the music playback of my app. I set up the media player within a Service class which plays music throughout the application fine. However, the issue I'm having is when changing screens from the Options page to the Home page again.
In the option class, I have a single ToggleButton which turns the music on and off when it's clicked, and I have used a boolean to determine whether the ToggleButton is auto on and off, depending on whether the music is playing.
However, when the user clicks the back button or the save button (which both send them back to the home page) the music starts playing again, even if it's checked as "off".
Does anyone have a suggestion for me?
Service Class:
public class MyMusicService extends Service {
MediaPlayer mp;
#Override
public int onStartCommand(Intent intent, int flags, int startId) {
mp = MediaPlayer.create(this, R.raw.song);
mp.start();
mp.setLooping(true);
return super.onStartCommand(intent, flags, startId);
}
#Override
public IBinder onBind(Intent intent) {
return null;
}
#Override
public void onDestroy() {
super.onDestroy();
if(mp!=null) {
mp.stop();
mp.release();
}
mp=null;
}
}
Options Class:
public class OptionsActivity extends Activity {
#Override
public boolean onKeyDown(int keyCode, KeyEvent event) {
if (keyCode == KeyEvent.KEYCODE_BACK ) {
Intent i = new Intent(OptionsActivity.this, MainActivity.class);
startActivity(i);
return true;
}
return super.onKeyDown(keyCode, event);
}
private boolean isMyServiceRunning(String serviceCanonicalClassName) {
ActivityManager manager = (ActivityManager) getSystemService(ACTIVITY_SERVICE);
for (RunningServiceInfo service : manager.getRunningServices(Integer.MAX_VALUE)) {
if (serviceCanonicalClassName.equals(service.service.getClassName())) {
return true;
}
}
return false;
}
Intent i; // Handles MyMusicService.java
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.options);
final TextView tSound = (TextView) findViewById(R.id.textView2);
final Button saveBtn = (Button) findViewById(R.id.optSaveBtn);
final Button tblBtn = (Button) findViewById(R.id.tableBtn);
i=new Intent(this, MyMusicService.class);
final ToggleButton soundOption = (ToggleButton) findViewById(R.id.soundPref);
boolean musicPlays = isMyServiceRunning(MyMusicService.class.getCanonicalName());
soundOption.setChecked(musicPlays);
if(musicPlays==true){
tSound.setText("On");
}
if(musicPlays==false) {
tSound.setText("Off");
}
soundOption.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
// Perform action on clicks to control sound being on and off.
if(soundOption.isChecked()) {
Toast.makeText(OptionsActivity.this, "Music on.", Toast.LENGTH_SHORT).show();
startService(i);
Intent i = new Intent(OptionsActivity.this, OptionsActivity.class);
startActivity(i);
}
else {
if(stopService(i)==true){
soundOption.setChecked(false);
stopService(i);
Toast.makeText(OptionsActivity.this, "Music off.", Toast.LENGTH_SHORT).show();
Intent i = new Intent(OptionsActivity.this, OptionsActivity.class);
startActivity(i);
}
}
}
});
tblBtn.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
Intent tblView = new Intent(OptionsActivity.this, SQLView.class);
startActivity(tblView);
}
});
saveBtn.setOnClickListener(new View.OnClickListener(){
public void onClick(View v) {
Intent homePage = new Intent(OptionsActivity.this, MainActivity.class);
switch (v.getId()){
case R.id.optSaveBtn: //Determine what will happen when the user presses the "Submit button".
boolean optionsWork = true;
try{
String sound = tSound.getText().toString();
optionsDB entry = new optionsDB(OptionsActivity.this); //Creating a new instance of MasterMind game
entry.open();
entry.createOptionEntry(sound); //Passing both strings
entry.close();
}catch (Exception e){ //Creating an error message if for some reason the app cannot transfer data to the Database.
Toast.makeText(OptionsActivity.this, "Error", Toast.LENGTH_SHORT).show();
}
finally { //Creating an AlertDialog box when the user presses the Submit button.
if (optionsWork){
Toast.makeText(OptionsActivity.this, "Settings Saved", Toast.LENGTH_SHORT).show();
}
}
break;
}
startActivity(homePage);
}
});
}
}
And finally, the home class:
public class MainActivity extends Activity {
Intent i;
private boolean isMyServiceRunning(String serviceCanonicalClassName) {
ActivityManager manager = (ActivityManager) getSystemService(ACTIVITY_SERVICE);
for (RunningServiceInfo service : manager.getRunningServices(Integer.MAX_VALUE)) {
if (serviceCanonicalClassName.equals(service.service.getClassName())) {
return true;
}
}
return false;
}
public void checkSound(){
boolean musicPlays = isMyServiceRunning(MyMusicService.class.getCanonicalName());
if(musicPlays==true){
//Do nothing
}
else {
stopService(i);
}
}
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
//setting the layout
//Start Networking
//Intent net = new Intent(this, Networking.class);
//startService(net);
//Auto starts playing music on app launch.
i = new Intent(this,MyMusicService.class);
startService(i);
checkSound();
final ImageView findGame = (ImageView) findViewById(R.id.btnFindGame);
final ImageView profile = (ImageView) findViewById(R.id.btnProfile);
final ImageView instructions = (ImageView) findViewById(R.id.btnInstructions);
final ImageView options = (ImageView) findViewById(R.id.btnOptions);
findGame.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent(MainActivity.this, DrawActivity.class);
startActivity(intent);
}
});
profile.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent(MainActivity.this, WaitingActivity.class);
startActivity(intent);
}
});
instructions.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent(MainActivity.this, InstructionsActivity.class);
startActivity(intent);
}
});
options.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent(MainActivity.this, OptionsActivity.class);
startActivity(intent);
}
});
}
//On app close, music stops playing.
#Override
protected void onDestroy() {
if (this.isFinishing()){
super.onDestroy();
stopService(i);
//finish();
}
}
}
When you're creating the home screen, you are also starting the service again. In your 'onStartCommand' of the service you are starting the media player. That means that every time you go to the homepage, the media player will start playing again.
I would recommend not putting mp.start(); in the 'onStartCommand' but instead in its own function. Then after you call startService(i); you can bind to the the service using bindService() then call a function such as play() on the service handle you have.
Of course if you are pausing the song instead of stopping you will need to save the position of the songs and then use seekTo() to move the song to the proper position when you restart the service.
I'd recommend reading through the Android service page here and here
i think u have to place some check on start service in your home class on create method,
check if(your service is running)
{
if(mp is playing)
{
//do nothing
}
}
else
{
startservice();
}

Categories

Resources