Several ways to add background bgm music in Android studio

Playing background audio in the app needs to call the Service component

The Service component needs to be registered with a tag in the manifest file (usually it will be automatically registered in the file)

Service is an abstract base class for writing service components

onCreate() and onDestroy() are two important life cycle methods of Service, and code needs to be written in them

When starting a service in a non-binding manner, there is no need to write code in the lifecycle method onBind()

Play bgm by clicking the button

service:

package com.example.example5_1;

import android.app.Service;
import android.content.Intent;
import android.media.MediaPlayer;
import android.os.IBinder;

public class MyAudioService extends Service {
    MediaPlayer mp;

    @Override
    public void onCreate() {                  //开始服务时调用
        super.onCreate();
        mp = MediaPlayer.create(this,R.raw.white);
        mp.start();
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        mp.stop();
        if (mp != null) mp=null;
    }

    @Override
    public IBinder onBind(Intent intent) {           //不可省略的生命周期方法
        // TODO: Return the communication channel to the service.
        throw new UnsupportedOperationException("Not yet implemented");
    }
}

MainActivity:

package com.example.example5_1;

import androidx.appcompat.app.AppCompatActivity;

import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.Toast;

public class MainActivity extends AppCompatActivity implements View.OnClickListener{

    Intent intent;
    Button btn_play,btn_stop;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        btn_play = findViewById(R.id.btn_play);
        btn_stop = findViewById(R.id.btn_stop);
        btn_play.setOnClickListener(this);
        btn_stop.setOnClickListener(this);
    }

    @Override
    public void onClick(View v){
        intent = new Intent(this,MyAudioService.class);    //用intent来实现服务的运行和停止

        int id = v.getId();
        switch (id){
            case R.id.btn_play:
                startService(intent);
                Toast.makeText(this, "音乐服务进行中...", Toast.LENGTH_SHORT).show();
                btn_stop.setEnabled(true);
                btn_play.setEnabled(false);
                break;
            case R.id.btn_stop:
                stopService(intent);
                btn_stop.setEnabled(false);
                btn_play.setEnabled(true);
        }
    }

    @Override
    protected void onDestroy() {           //考虑播放时返回
        super.onDestroy();
        if (intent != null) stopService(intent);   //停止服务
        finish();                                 //关闭
    }
}

Enter the app and play bgm directly in the background

Service:

package com.example.example5_2;

import android.app.Service;
import android.content.Intent;
import android.media.MediaPlayer;
import android.os.Binder;
import android.os.IBinder;

public class MyAudioService extends Service {
    private MediaPlayer mp;

    public class PlayBinder extends Binder{        //用作代理的内部类
        public  void MyMethod(){                   //服务方法
            mp = MediaPlayer.create(getApplicationContext(),R.raw.white);
            mp.start();
        }
    }

    @Override
    public IBinder onBind(Intent intent) {
        // TODO: Return the communication channel to the service.
       // throw new UnsupportedOperationException("Not yet implemented");
        return new PlayBinder();                    //返回服务代理类
    }

    @Override
    public void onDestroy() {                //服务销毁时停止音乐播放
        if (mp != null){
            mp.stop();
            mp.release();
        }
        super.onDestroy();
    }
}

MainActivity:

Need to create an interface ServiceConnection object to realize the content when establishing a service connection

package com.example.example5_2;

import androidx.appcompat.app.AppCompatActivity;

import android.content.ComponentName;
import android.content.Intent;
import android.content.ServiceConnection;
import android.os.Bundle;
import android.os.IBinder;

public class MainActivity extends AppCompatActivity {
//以绑定方式启动服务(活动和服务绑定),需要建立代理人
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        final ServiceConnection connection = new ServiceConnection() {
            @Override
            public void onServiceConnected(ComponentName componentName, IBinder iBinder) {

                MyAudioService.PlayBinder playBinder = (MyAudioService.PlayBinder) iBinder;
                //获取代理人对象
                playBinder.MyMethod();  //调用代理方法
            }

            @Override
            public void onServiceDisconnected(ComponentName componentName) {
                                            //断开服务连接
            }
        };
        Intent intent = new Intent(getApplicationContext(),MyAudioService.class);
        bindService(intent,connection,BIND_AUTO_CREATE);   //绑定服务
    }
}

agent

The so-called agent is equivalent to a role that can help users and programs interact better, such as

Cash machine in "Payer - ATM - Bank Server"

There is also a method of remote service calling audio playback, which is less used

Guess you like

Origin blog.csdn.net/Ice1774/article/details/124791414