[ZT]:http://www.eoeandroid.com/thread-13616-1-1.html
沈青海的视频教程Android Service初级应用讲解是用音乐播放器做为例子,同时也用到了BroadCastReceiver,这样就可以作为和Activity三者之间相互作用的最佳范例了。鄙人觉得视频看不清楚,贴出的代码又不全,所以加以补充,自己添加布局和按钮,编写Main.xml文件。这样工程就完整可用了,希望对您有所帮助。
感谢沈先生的视频和源码,非常值得仔细研究。
沈先生网站视频链接地址:http://www.3gqa.com/?p=1510
直接贴代码:
服务:MusicService.java
- package work.service;
- import java.io.IOException;
- import android.app.Service;
- import android.content.Intent;
- import android.media.MediaPlayer;
- import android.os.Binder;
- import android.os.Bundle;
- import android.os.IBinder;
- import android.util.Log;
- public class MusicService extends Service {
- // MediaPlayer实例
- private MediaPlayer player;
- // IBinder实例
- private final IBinder binder = new MyBinder();
- /**
- * 绑定
- */
- @Override
- public IBinder onBind(Intent intent) {
- playMusic();
- return binder;
- }
- /**
- * 声明Binder子类
- *
- * @author www.3gqa.com
- *
- */
- public class MyBinder extends Binder {
- MusicService getService() {
- return MusicService.this;
- }
- }
- /**
- * 创建服务
- */
- public void onCreate() {
- super.onCreate();
- Log.e("TAG", "onCreate");
- playMusic();
- }
- /**
- * 播放
- */
- public void playMusic() {
- if (player == null) {
- Log.e("TAG", "playMusic");
- player = MediaPlayer.create(this, R.raw.yuanlai);
- }
- if (!player.isPlaying()) {
- player.start();
- }
- }
- /**
- * 暂停播放
- */
- public void pauseMusic() {
- if (player != null)
- if (player.isPlaying()) {
- Log.e("TAG", "pauseMusic");
- player.pause();
- }
- }
- /**
- * 停止播放
- */
- public void stopMusic() {
- if (player != null) {
- Log.e("TAG", "stopMusic");
- player.stop();
- try {
- // 在调用stop后如果需要再次通过start进行播放,需要之前调用prepare函数
- player.prepare();
- } catch (IOException ex) {
- ex.printStackTrace();
- }
- }
- }
- /**
- * 开始播放
- */
- public void onStart(Intent intent, int startId) {
- super.onStart(intent, startId);
- Log.e("TAG", "onStart");
- if (intent != null) {
- Bundle bundle = intent.getExtras();
- if (bundle != null) {
- int op = bundle.getInt("op");
- switch (op) {
- case 1:
- playMusic();
- break;
- case 2:
- pauseMusic();
- break;
- case 3:
- stopMusic();
- break;
- }
- }
- }
- }
- /**
- * 销毁服务
- */
- public void onDestroy() {
- super.onDestroy();
- Log.e("TAG", "onDestroy");
- if (player != null) {
- player.stop();
- player.release();
- }
- }
- }
广播接收器:MusicReceiver.java
- package work.service;
- import android.content.BroadcastReceiver;
- import android.content.Context;
- import android.content.Intent;
- import android.os.Bundle;
- import android.util.Log;
- /**
- *
- * @author 3gqa.com
- *
- */
- public class MusicReceiver extends BroadcastReceiver {
- Context context;
- @Override
- public void onReceive(Context context, Intent intent) {
- Log.e("TAG", "onReceive");
- this.context = context;
- Intent it = new Intent("work.service.MUSIC_SERVICE_SERVICE");
- Bundle bundle = intent.getExtras();
- it.putExtras(bundle);
- if (bundle != null) {
- int op = bundle.getInt("op");
- Log.e("TAG", "Receive"+op+"...........");
- if (op == 4) {
- context.stopService(it);
- } else {
- context.startService(it);
- // context.bindService(it, mConnection,
- // Context.BIND_AUTO_CREATE);
- }
- }
- }
- }
界面Activity类:ExampleServiceRequest.java
- package work.service;
- import android.app.Activity;
- import android.content.ComponentName;
- import android.content.Intent;
- import android.content.ServiceConnection;
- import android.os.Bundle;
- import android.os.IBinder;
- import android.util.Log;
- import android.view.View;
- import android.view.View.OnClickListener;
- import android.widget.Button;
- import android.widget.LinearLayout;
- /**
- *
- * @author 3gqa.com
- *
- */
- public class ExampleServiceRequest extends Activity implements OnClickListener {
- Button btnStartservice;
- Button btnPlay;
- Button btnPause;
- Button btnStop;
- Button btnStopservice;
- Button btnExit;
- /** Called when the activity is first created. */
- @Override
- public void onCreate(Bundle savedInstanceState) {
- super.onCreate(savedInstanceState);
- // setContentView(R.layout.main);
- //
- LinearLayout l=new LinearLayout(this);
- l.setOrientation(LinearLayout.VERTICAL);//垂直布局
- LinearLayout.LayoutParams ll=new LinearLayout.LayoutParams(
- LinearLayout.LayoutParams.FILL_PARENT,
- LinearLayout.LayoutParams.WRAP_CONTENT
- );
- //
- Button btnStartservice = new Button(this);
- btnStartservice.setId(01);
- btnStartservice.setText("开始服务");
- btnStartservice.setOnClickListener(this);
- l.addView(btnStartservice, ll);
- //
- Button btnPlay = new Button(this);
- btnPlay.setId(02);
- btnPlay.setText("播放音乐");
- btnPlay.setOnClickListener(this);
- l.addView(btnPlay, ll);
- //
- Button btnPause = new Button(this);
- btnPause.setId(03);
- btnPause.setText("暂停");
- btnPause.setOnClickListener(this);
- l.addView(btnPause, ll);
- //
- Button btnStop =new Button(this);
- btnStop.setId(04);
- btnStop.setText("停止");
- btnStop.setOnClickListener(this);
- l.addView(btnStop, ll);
- //
- Button btnStopservice =new Button(this);
- btnStopservice.setId(05);
- btnStopservice.setText("停止服务");
- btnStopservice.setOnClickListener(this);
- l.addView(btnStopservice, ll);
- //
- Button btnExit =new Button(this);
- btnExit.setId(06);
- btnExit.setText("退出");
- btnExit.setOnClickListener(this);
- l.addView(btnExit, ll);
- this.setContentView(l);
- }
- /**
- * 点击处理
- */
- public void onClick(View v) {
- int op = -1;
- if (v==(findViewById(01))){
- op = 0; }
- else if (v.equals(findViewById(02)))
- op = 1;
- else if (v.equals(findViewById(03)))
- op = 2;
- else if (v.equals(findViewById(04)))
- op = 3;
- else if (v.equals(findViewById(05)))
- op = 4;
- else if (v.equals(findViewById(06))) {
- this.finish();
- return;
- }
- Log.e("TAG", "onClick..."+op+"...........");
- // 构造数据
- Bundle bundle = new Bundle();
- bundle.putInt("op", op);
- Intent intent = new Intent("work.service.MUSIC_SERVICE_BROADCAST");
- intent.putExtras(bundle);
- // 发送广播
- sendBroadcast(intent);
- Log.e("TAG", "Broadcast"+op+"...........");
- }
- /*
- *//**
- * 服务实例
- *//*
- private MusicService serviceBinder;
- *//**
- * 当服务和Activity连接时调用函数
- *
- *//*
- private ServiceConnection mConnection=new ServiceConnection(){
- public void onServiceConnected(ComponentName name, IBinder service) {
- serviceBinder=((MusicService.MyBinder)service).getService();//???
- if(serviceBinder!=null){
- serviceBinder.playMusic();
- }
- }
- *//**
- * 当服务和Activity断开时调用
- *//*
- public void onServiceDisconnected(ComponentName name) {
- serviceBinder=null;
- }
- };*/
- }
主配置文件:AndroidManifest.xml
- <?xml version="1.0" encoding="utf-8"?>
- <manifest xmlns:android="http://schemas.android.com/apk/res/android"
- package="work.service"
- android:versionCode="1"
- android:versionName="1.0">
- <application android:icon="@drawable/icon" android:label="@string/app_name">
- <activity android:name="ExampleServiceRequest">
- <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="work.service.MUSIC_SERVICE_SERVICE" />
- <category android:name="android.intent.category.defult" />
- </intent-filter>
- </service>
- <receiver android:name="MusicReceiver">
- <intent-filter>
- <action android:name="work.service.MUSIC_SERVICE_BROADCAST"/>
- </intent-filter>
- </receiver>
- </application>
- <uses-sdk android:minSdkVersion="7" />
- </manifest>
工程文件,如果不会贴的就倒吧,其实不必破费呵呵
操,我的p3文件太大了,传不上来,算了,想要的都贴自己工程里吧,练练手,我没用其他的xml,都是自己在代码里布局的