背景音乐

来源:互联网 发布:nba球员体测数据排行 编辑:程序博客网 时间:2024/04/18 19:12

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

public class AudioService extends Service implements
  MediaPlayer.OnCompletionListener {
 // 实例化MediaPlayer对象
 MediaPlayer player;
 private final IBinder binder = new AudioBinder();

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

 public void onCreate() {
  super.onCreate();
  // 从raw文件夹中获取一个应用自带的mp3文件
  player = MediaPlayer.create(this, R.raw.qq);
  player.setOnCompletionListener(this);
  player.setLooping(true);
 }

 @Override
 public int onStartCommand(Intent intent, int flags, int startId) {
  super.onStartCommand(intent, flags, startId);
  if (!player.isPlaying()) {
   new MusicPlayThread().start();
  }
  else player.isPlaying();
  return START_STICKY;
 }

 
 /**
  * 当Audio播放完的时候触发该动作
  */
 public void onCompletion(MediaPlayer mp) {
  stopSelf();// 结束了,则结束Service

 }

 public void onDestroy() {
  super.onDestroy();
  if (player.isPlaying()) {
   player.stop();
  }
  player.release();
 }

 // 为了和Activity交互,我们需要定义一个Binder对象
 public class AudioBinder extends Binder {
  // 返回Service对象
  public AudioService getService() {
   return AudioService.this;
  }
 }

 private class MusicPlayThread extends Thread {
  public void run() {
   if (!player.isPlaying()) {
    player.start();
   }
  }
 }
  
}

MainActivity:

import android.os.Bundle;
import android.app.Activity;
import android.content.ComponentName;
import android.content.Intent;
import android.view.Menu;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;

public class MainActivity extends Activity {
 private Button btnPlay;
 private Button btnPause;
    private ComponentName com;//用于启动服务
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        //得到布局中的控件
        btnPlay=(Button) findViewById(R.id.btnPlay);
        btnPause=(Button) findViewById(R.id.btnPause);
       
        //绑定控件事件
       setListener();     
      
    }

    private void setListener() {
     btnPlay.setOnClickListener((OnClickListener) this);
     btnPause.setOnClickListener((OnClickListener) this);
  
 }
    //按钮单击事件响应
    public void onClick (View v){
     if(v==btnPlay){
      startService(new Intent(this,AudioService.class));
     }
    }

 @Override
    protected void onResume() {
     super.onResume();
     startService(new Intent(this,AudioService.class));
    }
    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        // Inflate the menu; this adds items to the action bar if it is present.
        getMenuInflater().inflate(R.menu.main, menu);
        return true;
    }
   
}

 

0 0
原创粉丝点击