简体   繁体   中英

game background music

Hello im making a android game application and i want to make a background music for my game. i have found some code here in stackoverflow but its not work properly because when i press the back button or home button the music is still playing, even i remove it from task its still running it mean onPause or onDestroy is not working. can someone help me, thank you!.

here's the link where i found the codes Android background music service

我认为您将音乐作为服务播放,并且必须在活动的onPause和onDestroy中销毁此服务。

1) First put your music.mp3 into raw folder

2) Declaring a service in the manifest as child of the <application> element

<service android:name=".SoundService"  android:enabled="true"/>

3) Add MusicService.java class:

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

public class SoundService extends Service {

MediaPlayer mPlayer;

    @Override
    public void onCreate() {
        mPlayer = MediaPlayer.create(this, R.raw.music); 
        mPlayer.setLooping(true); 
    }

    @Override
    public IBinder onBind(Intent intent) {
        return null;
    }

    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {
        mPlayer.start();
        return Service.START_NOT_STICKY;
    }

    @Override
    public void onDestroy() {
        mPlayer.stop();
        mPlayer.release();
        super.onDestroy();
    }

}

4) Run\\Stop services in the activity:

import android.content.Intent;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;

public class MainActivity extends AppCompatActivity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {

        startService(new Intent(MainActivity.this, SoundService.class));

        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
    }

    @Override
    public void onBackPressed() {
        stopService(new Intent(MainActivity.this, SoundService.class));
        super.onBackPressed();    
    }

    @Override
    protected void onPause() {
        // When the app is going to the background
        stopService(new Intent(MainActivity.this, SoundService.class)); 
        super.onPause();
    }

    @Override
    protected void onDestroy() {
        // when system temporarily destroying activity 
        stopService(new Intent(MainActivity.this, SoundService.class));
        super.onDestroy();
    }

}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM