运行界面
项目目录
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>