背景音乐的实现

1.首先在Manifest的</application> </application>中写入以下内容:

2.然后将要播放的歌曲放入raw文件夹中:

在R中即可自动生产索引。

主要代码:

MainActivity:

package com.example.music;

import android.os.Bundle;
import android.app.Activity;
import android.content.Intent;
import android.view.Menu;

public class MainActivity extends Activity {
private Intent intent = new Intent("com.angel.Android.MUSIC");

@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
startService(intent);
}


@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;
}

}

Service:

package com.example.music;

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

public class ServiceMusic extends Service {

private MediaPlayer mediaPlayer;

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

@SuppressWarnings("deprecation")

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

if(mediaPlayer==null){

mediaPlayer = MediaPlayer.create(this, R.raw.biji);
mediaPlayer.setLooping(true);
mediaPlayer.start();

}
}

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

posted @ 2015-07-09 13:39  Z_devotion  阅读(134)  评论(0编辑  收藏  举报