Service2--PlayService
1.新建工程PlayService
2.设置main.xml
- <?xml version="1.0" encoding="utf-8"?>
- <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
- android:orientation="vertical"
- android:layout_width="fill_parent"
- android:layout_height="fill_parent"
- >
- <Button
- android:id="@+id/start"
- android:layout_width="fill_parent"
- android:layout_height="wrap_content"
- android:text="Start Play"
- />
- <Button
- android:id="@+id/stop"
- android:layout_width="fill_parent"
- android:layout_height="wrap_content"
- android:text="Stop Play"
- />
- </LinearLayout>
3.新建Music.java
- package com.iceskysl.PlayService;
- import android.app.Service;
- import android.content.Intent;
- import android.media.MediaPlayer;
- import android.os.IBinder;
- public class Music extends Service {
- private MediaPlayer player;
- @Override
- public IBinder onBind(Intent intent) {
- // TODO Auto-generated method stub
- return null;
- }
- public void onStart(Intent intent, int startId) {
- super.onStart(intent, startId);
- player = MediaPlayer.create(this, R.raw.gequ);
- player.start();
- }
- public void onDestroy() {
- super.onDestroy();
- player.stop();
- }
- }
4.修改PlayService.java
- package com.iceskysl.PlayService;
- import android.app.Activity;
- import android.content.Intent;
- import android.os.Bundle;
- import android.view.View;
- import android.view.View.OnClickListener;
- import android.widget.Button;
- public class PlayService extends Activity {
- /** Called when the activity is first created. */
- @Override
- public void onCreate(Bundle savedInstanceState) {
- super.onCreate(savedInstanceState);
- setContentView(R.layout.main);
- Button button1 = (Button)findViewById(R.id.start);
- button1.setOnClickListener(startIt);
- Button button2 = (Button)findViewById(R.id.stop);
- button2.setOnClickListener(stopIt);
- }
- private OnClickListener startIt = new OnClickListener()
- {
- public void onClick(View v)
- {
- startService(new Intent("com.iceskysl.PlayService.START_AUDIO_SERVICE"));
- }
- };
- private OnClickListener stopIt = new OnClickListener()
- {
- public void onClick(View v)
- {
- stopService(new Intent("com.iceskysl.PlayService.START_AUDIO_SERVICE"));
- finish();
- }
- };
- }
5.注册service
<service android:name=".Music">
<intent-filter>
<action android:name="com.iceskysl.PlayService.START_AUDIO_SERVICE" />
<category android:name="android.intent.category.default" />
</intent-filter>
</service>
6.加入资源/res/raw/gequ.mp3
当单击按钮启动播放Service后,在后台播放音乐,当执行其他操作时也不会打断音乐播放。