使用service播放音乐

运行界面

项目目录

PlayMusicActivity.java

package gogler.myandroid;

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;

public class PlayMusicActivity extends Activity {
/** Called when the activity is first created. */


@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
//从main.xml布局中获得Button对象
Button button_start = (Button)findViewById(R.id.playbt);
Button button_stop = (Button)findViewById(R.id.stopbt);
//设置按钮(Button)监听
button_start.setOnClickListener(start);
button_stop.setOnClickListener(stop);
}

//开始按钮
private OnClickListener start = new OnClickListener()
{
public void onClick(View v)
{
//开启Service
startService(new Intent("android.intent.action.MUSIC"));
}
};
//停止按钮
private OnClickListener stop = new OnClickListener()
{
public void onClick(View v)
{
//停止Service
stopService(new Intent("android.intent.action.MUSIC"));

}
};
}

MusicPlayerService .java

package gogler.myandroid;

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

public class MusicPlayerService extends Service {

private MediaPlayer player;

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

@Override
public void onDestroy() {
// TODO Auto-generated method stub
super.onDestroy();
// 3、停止音乐
player.stop();
}

@Override
public void onStart(Intent intent, int startId) {
// TODO Auto-generated method stub
super.onStart(intent, startId);
// 1、加载音乐
// 2、播放音乐
player = MediaPlayer.create(this, R.raw.tommaimairubsaktee);
player.start();
}

}

AndroidManifest.xml

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="gogler.myandroid"
android:versionCode="1"
android:versionName="1.0" >

<uses-sdk android:minSdkVersion="1" />

<application
android:icon="@drawable/russia"
android:label="@string/app_name" >
<activity
android:icon="@drawable/russia"
android:label="@string/app_name"
android:name=".PlayMusicActivity" >
<intent-filter >
<action android:name="android.intent.action.MAIN" />

<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>

<service
android:name=".MusicPlayerService">
<intent-filter>
<action android:name="android.intent.action.MUSIC"/>
</intent-filter>
</service>
</application>

</manifest>

代码打包下载

http://download.csdn.net/download/gogler/3727632

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值