Tag Archives: # android

Android: How to Add Background Music for Activity with Service

Create a new Service and name it MyFirstBgmServic

package com.example.cyberwoodenfish;

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

public  class MyFirstBgmService extends Service {
     public MyFirstBgmService() {
    }
    
    MediaPlayer mp;

    @Override
    public  void onCreate() {                   // call 
        super .onCreate() when starting the service;
        mp = MediaPlayer.create( this ,R.raw.dabeizhou);
        mp.start();
    }

    @Override
    public  void onDestroy() {                 // Stop music playback when the service is destroyed 
        if (mp != null ){
            mp.stop();
            mp.release();
        }
        super.onDestroy ();
    }

    @Override
    public IBinder onBind(Intent intent) {
         // TODO: Return the communication channel to the service. 
        throw  new UnsupportedOperationException("Not yet implemented" );
    }
}

Then start package com.example.cyberwoodenfish in MainActivity ;

import androidx.appcompat.app.AppCompatActivity;

import android.annotation.SuppressLint;
 import android.app.Activity;
 import android.content.Intent;
 import android.media.AudioManager;
 import android.media.SoundPool;
 import android.os.Bundle;
 import android.view.View;
 import android.view.animation.Animation;
 import android.view.animation.AnimationUtils;
 import android.widget.ImageButton;
 import android.widget.ProgressBar;
 import android.widget.TextView;
 import android.widget.Toast;

public  class MainActivity extends Activity {
    
    @Override
    protected  void onCreate(Bundle savedInstanceState) {
         super .onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        Intent intentbgm;
        intentbgm = new Intent(MainActivity.this , MyFirstBgmService.class ) ;
        startService(intentbgm);       //. . . Code unrelated to bgm was eaten by me again

    }
}