标签:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="horizontal"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:gravity="center_horizontal"
>
<Button
android:id="@+id/stop"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="停止"
android:onClick="stopOnClick"
/>
<Button
android:id="@+id/play"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="播放"
android:onClick="playOnClick"
/>
<Button
android:id="@+id/pause"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="暂停"
android:onClick="pauseOnClick"
/>
</LinearLayout>
package com.ht.bindservicedemo;
import android.app.Service;
import android.content.Intent;
import android.media.MediaPlayer;
import android.os.Binder;
import android.os.IBinder;
/**
* Created by IntelliJ IDEA
* Project: com.ht.bindservicedemo
* Author: 安诺爱成长
* Email: 1399487511@qq.com
* Date: 2015/5/13
*/
public class PlayService extends Service {
private MediaPlayer player;
@Override
public void onCreate() {
super.onCreate();
player = MediaPlayer.create(this, R.raw.ai);
}
@Override
public IBinder onBind(Intent intent) {
return new MyControl();
}
/**
* 用于交给当前服绑定的组件
*/
class MyControl extends Binder{
public void play() {
if (player != null) {
player.start();
}
}
public void stop() {
if (player != null) {
player.stop();
}
}
public void pause() {
if (player != null) {
player.pause();
}
}
}
@Override
public void onDestroy() {
super.onDestroy();
player.stop();
player.release();
player = null;
}
}
package com.ht.bindservicedemo;
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.View;
public class MainActivity extends Activity implements ServiceConnection {
private PlayService.MyControl myControl;
/**
* Called when the activity is first created.
*/
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
//绑定服务
Intent intent = new Intent(this, PlayService.class);
bindService(intent, this, BIND_AUTO_CREATE);
}
//绑定服务使用的方法
@Override
public void onServiceConnected(ComponentName name, IBinder service) {
myControl = (PlayService.MyControl) service;
}
@Override
public void onServiceDisconnected(ComponentName name) {
myControl = null;
}
//取消绑定
@Override
protected void onStop() {
super.onStop();
unbindService(this);
}
//三个按钮的监听器
public void stopOnClick(View view) {
if (myControl != null) {
myControl.stop();
}
}
public void playOnClick(View view) {
if (myControl != null) {
myControl.play();
}
}
public void pauseOnClick(View view) {
if (myControl != null) {
myControl.pause();
}
}
}
标签:
原文地址:http://blog.csdn.net/a910626/article/details/45697627