I am building a simple android application and it has two Activities and a IntentService. My IntentService plays music over every activity(thats what I want) but if I leave the app the music still plays (example: if I press the home button it will take me to the desktop, putting my activity in the onpause state but the music from that app is still playing). Any help would be appreciated....
code below
Main Activity
public class MainActivity extends Activity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Intent serviceIntent= new Intent(this, BackgroundMusic.class);
startService(serviceIntent);
}
public void ShipPick(View view){
Intent activityIntent= new Intent(this, ShipChoiceActivity.class);
startActivity(activityIntent);
}
}
Background Music Service
public class BackgroundMusic extends IntentService {
MediaPlayer mp;
public BackgroundMusic() {
super("BackgroundMusic");
}
Handler HN = new Handler();
private class PlayMusic implements Runnable {
public void PLayMusic(){
}
public void run(){
mp = MediaPlayer.create(getApplicationContext(), R.raw.musicfile);
mp.start();
}
}
@Override
protected void onHandleIntent(Intent intent) {
HN.post(new PlayMusic());
}
public void onPause() {
mp.pause();
}
public void onResume() {
mp.start();
}
protected void onStop() {
mp.stop();
mp = null;
}
}
second activity
public class ShipChoiceActivity extends Activity {
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_ship_choice);
}
}
manifest
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.example.starwars"
android:versionCode="1"
android:versionName="1.0" >
<uses-sdk
android:minSdkVersion="8"
android:targetSdkVersion="18" />
<application
android:allowBackup="true"
android:debuggable="true"
android:icon="@drawable/ic_launcher"
android:label="@string/app_name"
android:theme="@style/AppTheme" >
<service android:name=".BackgroundMusic" />
<activity
android:name="com.example.ship.MainActivity"
android:label="@string/app_name" >
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<activity android:label="@string/app_name" android:name="ShipChoiceActivity"/>
</application>
</manifest>
For controlling
BackgroundMusic
Service from Activity you will need to use customBroadcastReceiver
to communicate with service when application is going in onpause state.Register BroadcastReceiver In BackgroundMusic :
Send BroadcastReceiver from Activity
onPause
: