在Service中播放,可以在后台进行播放
package cn.edu.design;
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import cn.design.service.PlayService;
public class BroadCastActivity extends Activity {
private Button button=null;
/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
button=(Button)findViewById(R.id.play);
button.setOnClickListener(new OnClickListener(){
@Override
public void onClick(View v) {
// TODO Auto-generated method stub
Intent intent=new Intent();
intent.setClass(BroadCastActivity.this, PlayService.class);
startService(intent);
}
});
}
}
继承Service,播放Mp3文件
package cn.design.service;
import android.app.Service;
import android.content.Intent;
import android.media.MediaPlayer;
import android.net.Uri;
import android.os.Environment;
import android.os.IBinder;
public class PlayService extends Service{
@Override
public IBinder onBind(Intent intent) {
// TODO Auto-generated method stub
return null;
}
@Override
public int onStartCommand(Intent intent, int flags, int startId) {
// TODO Auto-generated method stub
MediaPlayer medPlay=MediaPlayer.create(this,Uri.parse("/sdcard/music/6.mp3"));
medPlay.start();
return super.onStartCommand(intent, flags, startId);
}
}
在AndroidManifest.xml中添加如下信息
<service android:name="cn.design.service.PlayService">
</service>