首页 » Android » android实现音乐播放功能

发表时间:2012-2-22 0:37:28 | 分类:Android | 阅读:317

在Android音乐播放器应用开发中,可以使用服务(Service)来实现音乐的后台的播放,也就是说就算关闭了Activity也可以继续播放音乐,附带完全代码下载。

1、创建一个简单的播放器界面。

在res/layout/main.xml中添加“播放”和“停止”两个按钮。

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
 android:orientation="vertical" android:layout_width="fill_parent"
 android:layout_height="fill_parent">
 <Button android:id="@+id/btnPlay" android:layout_width="100px"
  android:layout_height="wrap_content" android:layout_x="100px"
  android:layout_y="80px" android:text="播放">
 </Button>

 <Button android:id="@+id/btnStop" android:layout_width="100px"
  android:layout_height="wrap_content" android:layout_x="100px"
  android:layout_y="180px" android:text="停止">
 </Button>
</LinearLayout>

2、创建音乐服务类

在src/你的命名空间中添加一个MusicService类,该类继承Service类:

package cn.fetso;
import android.app.Service;
import android.content.Intent;
import android.media.MediaPlayer;
import android.os.IBinder;

public class MusicService extends Service {
 private MediaPlayer player;
 @Override
 public IBinder onBind(Intent arg0) {
  return null;
 }

 public void onStart(Intent intent, int startId) {
  super.onStart(intent, startId);
  // 加载音乐
  player = MediaPlayer.create(this, R.raw.music);
  // 开始播放
  player.start();
 }

 public void onDestory() {
  super.onDestroy();
  // 停止音乐 、service
  player.stop();
 }
}

3、在主Activity中调用服务播放音乐。

package cn.fetso;
import android.app.Service;
import android.content.Intent;
import android.media.MediaPlayer;
import android.os.IBinder;

public class MusicService extends Service {
 private MediaPlayer player;
 @Override
 public IBinder onBind(Intent arg0) {
  return null;
 }

 public void onStart(Intent intent, int startId) {
  super.onStart(intent, startId);
  // 加载音乐
  player = MediaPlayer.create(this, R.raw.music);
  // 开始播放
  player.start();
 }

 public void onDestory() {
  super.onDestroy();
  // 停止音乐 、service
  player.stop();
 }
}

4、在AndroidManifest.xml中配置Activity和Service

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
 package="cn.fetso" android:versionCode="1" android:versionName="1.0">
 <application android:icon="@drawable/icon" android:label="@string/app_name">
  <activity android:name=".MusicPlayer" android:label="@string/app_name">
   <intent-filter>
    <action android:name="android.intent.action.MAIN" />
    <category android:name="android.intent.category.LAUNCHER" />
   </intent-filter>
  </activity>
  <service android:name=".MusicService">
   <intent-filter>
    <action android:name="cn.fetso.Android.MUSIC" />
    <category android:name="android.intent.category.default" />
   </intent-filter>
  </service>
 </application>
 <uses-sdk android:minSdkVersion="7" />
</manifest>

5、测试播放效果。点击下载源代码

 

评论列表


#1 作者:susen 评论时间:2012-4-7 15:42:10
播放了之后没有关闭音乐的功能。。。

发表评论


昵称:
邮件:
链接: