代码改变世界

Android Service 简介

2013-11-19 14:42  Andy Ge  阅读(498)  评论(0编辑  收藏  举报

Service是Android系统中的一种组件,它跟Activity的级别差不多,但是它不能自己运行,只能后台运行,并且可以和其他组件进行交互。Service是没有界面的长生命周期的代码。Service是一种程序,它可以运行很长时间,但是它却没有用户界面。这么说有点枯燥,来看个例子,打开一个音乐播放器的程序,这个时候若想上网了,那么,我们打开Android浏览器,这个时候虽然我们已经进入了浏览器程序,但是,歌曲播放并没有停止,而是在后台继续一首接着一首地播放。其实这个播放就是由播放音乐的Service进行控制的。
当然这个播放音乐的Service也可以停止,例如,当播放列表里边的歌曲都结束,或者用户按下了停止音乐播放的快捷键等。Service可以在很多场合的应用中使用,比如播放多媒体的时候用户启动了其他Activity,这个时候程序要在后台继续播放,比如检测SD卡上文件的变化,再或者在后台记录用户地理信息位置的改变等等。总之服务嘛,总是藏在后头的。

PlayMusicService.java

package com.supermario.playmusic;
import android.app.Service;
import android.content.Intent;
import android.media.MediaPlayer;
import android.os.IBinder;
public class PlayMusicService extends Service{
    //定义音乐播放器
    private MediaPlayer mMediaPlayer;
    @Override
    public IBinder onBind(Intent arg0) {
        // TODO Auto-generated method stub
        return null;
    }    
    @Override
    public void onStart(Intent intent,int startId)
    {
        super.onStart(intent, startId);
        //装载音乐
        mMediaPlayer=MediaPlayer.create(this, R.raw.demo);
        //开始播放音乐
        mMediaPlayer.start();
    }
    @Override
    public void onDestroy()
    {
        super.onDestroy();
        //停止播放音乐
        mMediaPlayer.stop();
    }
}

PlayMusicActivity.java

package com.supermario.playmusic;
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 PlayMusicActivity extends Activity {
    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
        //开始按钮
        Button start=(Button)findViewById(R.id.button1);
        //停止按钮
        Button stop=(Button)findViewById(R.id.button2);
        //用于启动和停止Service的intent
        final Intent it=new Intent("android.guo.service.playmusic");
        //为“开始”按钮绑定监听器
        start.setOnClickListener(new OnClickListener(){
            @Override
            public void onClick(View v) {
                // TODO Auto-generated method stub
                //启动服务
                startService(it);
            }          
        });
        //为“停止”按钮绑定监听器
        stop.setOnClickListener(new OnClickListener(){
            @Override
            public void onClick(View v) {
                // TODO Auto-generated method stub
                //停止服务
                stopService(it);
            }          
        });
    }
}

main.xml

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:orientation="vertical" >
    <TextView
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:text="音乐播放器--回到拉萨" />
    <!-- 播放音乐 -->
    <Button
        android:id="@+id/button1"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="播放" />
    <!-- 停止音乐 -->
    <Button
        android:id="@+id/button2"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="停止" />
</LinearLayout>

AndroidManifest.xml

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.supermario.playmusic"
    android:versionCode="1"
    android:versionName="1.0" >
    <uses-sdk android:minSdkVersion="10" />
    <application
        android:icon="@drawable/ic_launcher"
        android:label="@string/app_name" >
        <activity
            android:name=".PlayMusicActivity"
            android:label="@string/app_name" >
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />

                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
        <service android:name=".PlayMusicService">
            <intent-filter>
                <action android:name="android.guo.service.playmusic"/>
            </intent-filter>
        </service>
    </application>
</manifest>