Android background and music

foreword

Simply add background images and music to the app

1. Add a background image

  1. Prepare a suitable background image
  2. Create a new Empty Activity project and select the Java language
  3. Create a mipmap file in res, and paste the prepared picture into the file directory
    insert image description here
  4. Add code in activity_main.xml to insert the background image
android:background="@mipmap/picture_1"
  1. The effect is as follows
    insert image description here

2. Add background music

  1. Prepare the right music first
  2. Create a raw file in res
  3. Put the music into the raw file directory
  4. Create a Java file named MusicServer.java, add code
package com.example.myapplication;

import android.content.Context;
import android.media.MediaPlayer;

public class MusicServer{
    private static MediaPlayer mp =null;
    public static void play(Context context, int resource){
        stop(context);
        mp = MediaPlayer.create(context, resource);
        mp.setLooping(true);
        mp.start();
    }
    
    public static void stop(Context context) {
        if(mp!= null){
            mp.stop();
            mp.release();
            mp = null;
        }
    }

}

  1. Add code to MainActivity to make background music take effect

    @Override
    protected void onPause() {
        super.onPause();
        stop(this);
    }

    
    @Override
    protected void onResume() {
        super.onResume();
        play(this, R.raw.music_1);
    }
    

3123d36dae40ede36fb8572032b26b64


In addition to this method, StartService can also control the background music very well

Lin Huan
Original link: https://blog.csdn.net/qq_52972314/article/details/128177466?spm=1001.2014.3001.5501

Guess you like

Origin blog.csdn.net/fjnu_se/article/details/128179787