Android允许我们使用Service组件来完成后台任务,这些任务的允许不会影响到用户其他的交互。
1、Activity类
-
package demo.camera;
-
import android.app.Activity;
-
import android.content.ComponentName;
-
import android.content.Context;
-
import android.content.Intent;
-
import android.content.ServiceConnection;
-
import android.os.Bundle;
-
import android.os.IBinder;
-
import android.view.View;
-
-
-
-
-
-
-
public class BackgroundAudioDemo extends Activity {
-
-
private AudioService audioService;
-
-
-
private ServiceConnection conn = new ServiceConnection() {
-
-
@Override
-
public void onServiceDisconnected(ComponentName name) {
-
-
audioService = null;
-
}
-
-
@Override
-
public void onServiceConnected(ComponentName name, IBinder binder) {
-
-
audioService = ((AudioService.AudioBinder)binder).getService();
-
-
}
-
};
-
-
public void onCreate(Bundle savedInstanceState){
-
super.onCreate(savedInstanceState);
-
setContentView(R.layout.back_audio);
-
}
-
-
-
public void onClick(View v){
-
int id = v.getId();
-
Intent intent = new Intent();
-
intent.setClass(this, AudioService.class);
-
if(id == R.id.btn_start){
-
-
startService(intent);
-
bindService(intent, conn, Context.BIND_AUTO_CREATE);
-
finish();
-
}else if(id == R.id.btn_end){
-
-
unbindService(conn);
-
stopService(intent);
-
finish();
-
}else if(id == R.id.btn_fun){
-
audioService.haveFun();
-
}
-
}
-
}
2、Service类
-
package demo.camera;
-
import android.app.Service;
-
import android.content.Intent;
-
import android.media.MediaPlayer;
-
import android.os.Binder;
-
import android.os.IBinder;
-
import android.widget.MediaController.MediaPlayerControl;
-
-
-
-
-
-
-
public class AudioService extends Service implements MediaPlayer.OnCompletionListener{
-
-
MediaPlayer player;
-
-
private final IBinder binder = new AudioBinder();
-
@Override
-
public IBinder onBind(Intent arg0) {
-
-
return binder;
-
}
-
-
-
-
@Override
-
public void onCompletion(MediaPlayer player) {
-
-
stopSelf();
-
}
-
-
-
public void onCreate(){
-
super.onCreate();
-
-
player = MediaPlayer.create(this, R.raw.tt);
-
player.setOnCompletionListener(this);
-
}
-
-
-
-
-
public int onStartCommand(Intent intent, int flags, int startId){
-
if(!player.isPlaying()){
-
player.start();
-
}
-
return START_STICKY;
-
}
-
-
public void onDestroy(){
-
-
if(player.isPlaying()){
-
player.stop();
-
}
-
player.release();
-
}
-
-
-
class AudioBinder extends Binder{
-
-
-
AudioService getService(){
-
return AudioService.this;
-
}
-
}
-
-
-
public void haveFun(){
-
if(player.isPlaying() && player.getCurrentPosition()>2500){
-
player.seekTo(player.getCurrentPosition()-2500);
-
}
-
}
-
}
3、在清单文件AndroidManifest.xml中配置Service
<service
android:name=".AudioService" />
Android多媒体学习六:利用Service实现背景音乐的播放
原文:http://blog.csdn.net/u011730649/article/details/44304929