您的位置:首页 > 其它

demo_音乐播放器_Service

2016-05-23 16:45 323 查看
下面是布局文件

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical">

<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:onClick="play"
android:text="播放" />

<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:onClick="pause"
android:text="暂停" />

</LinearLayout>

下面是Activity

package com.demo.music;

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.view.Menu;
import android.view.MenuItem;
import android.view.View;

public class MainActivity extends Activity {

ControllerInterface cl;
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);

//在创建的时候就绑定服务 一绑定就调用Service中的onBind方法
Intent intent = new Intent(this,MusicService.class);
//混合启动 这样不会随着Activity关闭服务而挂掉--先启动,再绑定
//把进程变成服务进程
startService(intent);
//绑定服务获取中间人对象 (如果不用解绑就可以使用匿名内部类)
bindService(intent, new ServiceConnection() {

@Override
//连接因为异常而终止才会调用
public void onServiceDisconnected(ComponentName name) {
}

@Override
//到服务的连接被建立了,此方法调用 service对象就是 onBind返回的中间人
//onBind有返回值时,此方法才调用
public void onServiceConnected(ComponentName name, IBinder service) {
cl = (ControllerInterface) service;

}
}, BIND_AUTO_CREATE);

}

public void play(View v){
cl.play();
}

public void pause(View v){
cl.pause();
}
}


下面是MusicService   代码

package com.demo.music;

import android.app.Service;
import android.content.Intent;
import android.os.Binder;
import android.os.IBinder;

public class MusicService extends Service {

@Override
public IBinder onBind(Intent arg0) {
//把中间人对象返回出去
return new MusciController();
}

//创建一个中间人对象继承IBinder的实现类Binder 来做为中间人,调用
class MusciController extends Binder implements ControllerInterface{

@Override
public void play() {
MusicService.this.play();
}

@Override
public void pause() {
MusicService.this.pause();
}

}

public void play(){
System.out.println("开始播放音乐");
}

public void pause(){
4000
System.out.println("暂停音乐");
}

}


下面是接口ControllerInterface 代码

package com.demo.music;

/*
* 创建一个公共的方法
*/
public interface ControllerInterface {
public void play();
public void pause();
}


下面是xml文件

<service android:name="com.demo.music.MusicService"></service>
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: