I'm new to Android Application development and there is so much that I have to learn.
I'm creating an app that has multiple activities. I want to find a way to create a service that can play different background music on a loop based on different activities.
I was trying to to create a background music service like this
Код: Выделить всё
public class BGMService extends Service {
private MediaPlayer player;
@Nullable
@Override
public IBinder onBind(Intent intent) {
return null;
}
@Override
public int onStartCommand(Intent intent, int flags, int startId) {
String currentActivity = intent.getStringExtra("activity_key");
// Release the previous MediaPlayer instance
if (player != null) {
player.stop();
player.release();
}
// Initialize a new MediaPlayer instance
player = new MediaPlayer();
try {
// Check the current activity and set the data source
if (MAIN_ACTIVITY_EXTRA_VALUES.equals(currentActivity)) {
player.setDataSource(getResources().openRawResourceFd(R.raw.background));
} else if (MAIN_PlAY_HOME_EXTRA_VALUES.equals(currentActivity)) {
player.setDataSource(getResources().openRawResourceFd(R.raw.hall));
}
// Set looping and volume
player.setLooping(true);
player.setVolume(0.5f, 0.5f); // Adjust volume as needed
// Set the prepared listener
player.setOnPreparedListener(mp -> {
// Start playback when prepared
mp.start();
});
// Prepare the MediaPlayer
player.prepareAsync();
} catch (IOException e) {
e.printStackTrace();
}
return START_STICKY;
}
@Override
public void onDestroy() {
if (player != null) {
player.stop();
player.release();
}
super.onDestroy();
}
}
Код: Выделить всё
public class MainActivity extends AppCompatActivity {
private ViewPager2 viewPager2;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
onBindingView();
//for view
ViewPagerAdapter adapter = new ViewPagerAdapter(this);
viewPager2.setAdapter(adapter);
viewPager2.setLayoutDirection(View.LAYOUT_DIRECTION_LTR);
//for background music
Intent servicebgIntent = new Intent(this, BGMService.class);
servicebgIntent.putExtra("activity_key", MAIN_ACTIVITY_EXTRA_VALUES);
startService(servicebgIntent);
}
private void onBindingView() {
viewPager2 = findViewById(R.id.vp2Intro);
}
@Override
protected void onDestroy() {
Intent service = new Intent(this, BGMService.class);
stopService(service);
super.onDestroy();
}
}
- When I press the home button the music still running
- when I change to another activity, the current background music is gone
Источник: https://stackoverflow.com/questions/781 ... activities