效果
布局文件
<?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>
service子类书写
package com.startservicedemo;
import android.app.Service;
import android.content.Intent;
import android.media.MediaPlayer;
import android.os.IBinder;
/**
* Created by IntelliJ IDEA
* Project: com.startservicedemo
* Author: 安诺爱成长
* Email: [email protected]
* 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 int onStartCommand(Intent intent, int flags, int startId) {
int control = intent.getIntExtra("control", -1);
switch (control) {
case 0:
player.start();
break;
case 1:
player.stop();
break;
case 2:
player.pause();
break;
}
return super.onStartCommand(intent, flags, startId);
}
@Override
public IBinder onBind(Intent intent) {
return null;
}
@Override
public void onDestroy() {
player.stop();
player.release();
player = null;
super.onDestroy();
}
}
activity书写
package com.startservicedemo;
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
public class MainActivity extends Activity {
/**
* Called when the activity is first created.
*/
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
Button stopButton = (Button) findViewById(R.id.stop);
Button playButton = (Button) findViewById(R.id.play);
Button pauseButton = (Button) findViewById(R.id.pause);
//启动服务
Intent intent = new Intent(this, PlayService.class);
startService(intent);
}
@Override
protected void onStop() {
//停止startservice启动的服务
Intent intent = new Intent(this, PlayService.class);
stopService(intent);
super.onStop();
}
//停止播放监听方法
public void stopOnClick(View view) {
Intent intent = new Intent(this, PlayService.class);
intent.putExtra("control", 1);
startService(intent);
}
//暂停播放监听方法
public void pauseOnClick(View view) {
Intent intent = new Intent(this, PlayService.class);
intent.putExtra("control", 2);
startService(intent);
}
//停止播放监听方法
public void playOnClick(View view) {
Intent intent = new Intent(this, PlayService.class);
intent.putExtra("control", 0);
startService(intent);
}
}
时间: 2024-11-20 14:05:00