1. 程式人生 > >android開發 利用Service給遊戲新增背景音樂

android開發 利用Service給遊戲新增背景音樂

 1、增加一個類,這個類是繼承Service的,如下。 
Java程式碼

package com.zhw.game8;

/**
 * Created by 得已 on 2018/9/19.
 */
import android.app.Service;
import android.content.Intent;
import android.media.MediaPlayer;
import android.os.IBinder;

public class MusicServer extends Service {

    private MediaPlayer mediaPlayer;

    @Override
    public IBinder onBind(Intent intent) {
// TODO Auto-generated method stub
        return null;
    }

    @Override
    public void onStart(Intent intent,int startId){
        super.onStart(intent, startId);

        if(mediaPlayer==null){

// R.raw.abc是資原始檔,MP3格式的
            mediaPlayer = MediaPlayer.create(this, R.raw.abc);
            mediaPlayer.setLooping(true);
            mediaPlayer.start();

        }
    }

    @Override
    public void onDestroy() {
// TODO Auto-generated method stub
        super.onDestroy();
        mediaPlayer.stop();
    }
}

2在AndroidManifest.xml中新增如下程式碼。

  1. <service Android:name=".MusicServer">  
  2. <intent-filter>  
  3. <action Android:name="com.angel.Android.MUSIC"/>  
  4. <category Android:name="android.intent.category.default" />  
  5. </intent-filter>  
  6. </service>  

3.在activity中

package com.zhw.game8;

import android.app.Activity;
import android.content.Intent;
import android.os.Build;
import android.os.Bundle;
import android.view.View;

public class MainActivity extends Activity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {

        super.onCreate(savedInstanceState);

        setContentView(R.layout.layout);


    }

    public void startGame(View view) {
        Intent intent = new Intent(this,MusicServer.class);
        startService(intent);
        Intent intent1=new Intent(this,StartActivity.class);
        startActivity(intent1);
    }

    @Override
    protected void onResume() {
        super.onResume();
        Intent intent = new Intent(this,MusicServer.class);
        stopService(intent);
    }
}