放置我们的媒体文件(jack.mp3)
编写我们的媒体Service类
?
package org.snailteam;import android.app.Service;import android.content.Intent;import android.media.MediaPlayer;import android.os.IBinder;import android.util.Log;import android.widget.Toast;public class MediaPlayerService extends Service { private static final String TAG = "音乐播放器服务"; MediaPlayer player; public IBinder onBind(Intent intent) { return null; } public void onCreate() {//服务初始化, Toast.makeText(this, "MediaPlayerService created", Toast.LENGTH_LONG).show(); Log.i(TAG, "onCreate"); player = MediaPlayer.create(this,R.raw.jack);//此处引用到我们的mp3文件,raw文件夹的。 player.setLooping(false); } public void onStart(Intent intent, int startId) { Toast.makeText(this, " MediaPlayerService Start", Toast.LENGTH_LONG).show(); Log.i(TAG, "onStart"); player.start(); } public void onDestroy() { Toast.makeText(this, " MediaPlayerService Stoped", Toast.LENGTH_LONG).show(); Log.i(TAG, "onDestroy"); player.stop(); }}
?输入代码R.raw.jack音乐文件没有提示时,需要修复一下
?
注册我们的Service组件到程序中
? 配置文件会多一行,注意.MediaPlayerService前面的.
<service android:name=".MediaPlayerService"></service>
?
我们的界面图设计如下,主要是两个按钮
主程序添加代码
?
package org.snailteam;import android.app.Activity;import android.content.Intent;import android.os.Bundle;import android.util.Log;import android.view.View;import android.view.View.OnClickListener;import android.widget.Button;public class application extends Activity implements OnClickListener{//我的主程序类是application private static final String TAG = "主程序"; Button buttonStart, buttonStop; public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.main); buttonStart = (Button)findViewById(R.id.buttonStart); buttonStop = (Button)findViewById(R.id.buttonStop); buttonStart.setOnClickListener(this); buttonStop.setOnClickListener(this); } public void onClick(View view) { switch (view.getId()) {//判断哪个按钮 case R.id.buttonStart: Log.i(TAG, "onClick: starting service"); startService(new Intent(this, MediaPlayerService.class));//引用我们自己写的媒体服务组件 break; case R.id.buttonStop: Log.i(TAG, "onClick: stopping service"); stopService(new Intent(this, MediaPlayerService.class)); break; } }}
?
之后大家可以运行试试效果。