今天写了个Service的例子,test.mp3放在资源文件夹下res->raw文件夹下。主要是三个文件:
1、配置文件 AndroidManifest.xml,主要设置音乐播放器Service
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.example"
android:versionCode="1"
android:versionName="1.0" >
<uses-sdk
android:minSdkVersion="8"
android:targetSdkVersion="8" />
<application
android:allowBackup="true"
android:icon="@drawable/ic_launcher"
android:label="@string/app_name"
android:theme="@style/AppTheme" >
<activity
android:name=".Controller"
android:label="@string/app_name" android:screenOrientation="nosensor">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<!-- 音乐播放 Server-->
<service android:name=".MusicService">
<intent-filter>
<action android:name="com.example.Android.MUSIC" />
<category android:name="android.intent.category.default" />
</intent-filter>
</service>
</application>
</manifest>
2、控制文件 Controller.java用于控制Service的启动和停止。
package com.example;
import com.example.R;
import android.os.Bundle;
import android.app.Activity;
import android.content.Intent;
import android.view.View;
import android.widget.Button;
public class Controller extends Activity {
private Button start = null;
private Button stop = null;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.controller);
initialView();
}
private void initialView() {
start = (Button)findViewById(R.id.start);
stop = (Button)findViewById(R.id.stop);
start.setOnClickListener(new Button.OnClickListener(){
@Override
public void onClick(View v) {
startService(new Intent("com.example.Android.MUSIC"));
}
});
stop.setOnClickListener(new Button.OnClickListener(){
@Override
public void onClick(View v) {
stopService(new Intent("com.example.Android.MUSIC"));
}
});
}
}
3、业务文件 MediaPlayer.java,音乐播放器的实现类
package com.example;
import com.example.R;
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;
}
@Override
public void onDestroy() {
super.onDestroy();
player.stop();
}
@Override
public void onStart(Intent intent, int startId) {
super.onStart(intent, startId);
player = MediaPlayer.create(this, R.raw.test);
player.start();
}
}