Лучший способ воспроизводить разную фоновую музыку при разных занятияхAndroid

Форум для тех, кто программирует под Android
Ответить Пред. темаСлед. тема
Гость
 Лучший способ воспроизводить разную фоновую музыку при разных занятиях

Сообщение Гость »


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();
}
}
And In my activity I will assign it with a constant like this

Код: Выделить всё

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();
}
}
However, my code leads me to some problems:
  • 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
Реклама
Ответить Пред. темаСлед. тема

Быстрый ответ

Изменение регистра текста: 
Смайлики
:) :( :oops: :roll: :wink: :muza: :clever: :sorry: :angel: :read: *x)
Ещё смайлики…
   
К этому ответу прикреплено по крайней мере одно вложение.

Если вы не хотите добавлять вложения, оставьте поля пустыми.

Максимально разрешённый размер вложения: 15 МБ.

  • Похожие темы
    Ответы
    Просмотры
    Последнее сообщение
  • Изолируйте вокал, удалив фоновую музыку.
    Anonymous » » в форуме Python
    0 Ответы
    17 Просмотры
    Последнее сообщение Anonymous
  • Как добавить фоновую музыку на мой html-сайт с автозапуском [закрыто]
    Anonymous » » в форуме CSS
    0 Ответы
    22 Просмотры
    Последнее сообщение Anonymous
  • Как воспроизводить музыку дольше при уведомлении?
    Anonymous » » в форуме IOS
    0 Ответы
    28 Просмотры
    Последнее сообщение Anonymous
  • Установленная музыка на Android 8.1 не может воспроизводить музыку
    Anonymous » » в форуме Android
    0 Ответы
    28 Просмотры
    Последнее сообщение Anonymous
  • Как я могу воспроизводить музыку по разным каналам в Python?
    Anonymous » » в форуме Python
    0 Ответы
    25 Просмотры
    Последнее сообщение Anonymous

Вернуться в «Android»