335 views

Android Service学习

很多情况下,我们一般让一些与用户很少产生交互的Android应用程序在后台运行就行了,而且在它们运行期间我们仍然能运行其他的应用。
为了处理这种后台程序Android引入了Service的概念。Service在Android中是一种长生命周期的组件,它不实现任何用户界面。

常见的例子:我们播放音乐的时候,想边听音乐边干一些其他事情,当我们退出播放音乐的应用,如果不用Service,歌曲就停了,这时候就得用到Service了,又比如当我们一个应用的数据是通过网络获取的,不同时间(一段时间)的数据是不同的这时候我们可以 用Service在后台定时更新,而不用每打开应用的时候在去获取。

Android Service的生命周期并不像Activity那么复杂,它只继承了onCreate(),onStart(),onDestroy()三个方法,当我们第一次启动Service时,先后调用了onCreate(),onStart()这两个方法,当停止Service时,则执行onDestroy()方法,这里需要注意的是,如果Service已经启动了,当我们再次启动Service时,不会在执行onCreate()方法,而是直接执行onStart()方法,可以看下面的实例,具体可以观察Log输出的信息了解Service运行机制。

public class TestService extends Service {

    private static final String TAG = "TestService";
    private NotificationManager _nm;

    public class LocalBinder extends Binder {
        TestService getService() {
            return TestService.this;
        }
    }
    @Override
    public IBinder onBind(Intent arg0) {
        Log.e(TAG, "………TestService…….onBind");
        return null;
    }
    @Override
    public void onCreate() {
        Log.e(TAG, "………TestService…….onCreate");
        _nm = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
        showNotification();
    }
    @Override
    public void onDestroy() {
        Log.e(TAG, "………TestService…….onDestroy");
        _nm.cancel(R.string.service_started);
    }

    @Override
    public void onRebind(Intent intent) {
        Log.e(TAG, "………TestService…….onRebind");
    }
    @Override
    public boolean onUnbind(Intent intent) {
        Log.e(TAG, "………TestService…….onUnbind");
        return false;
    }
    @Override
    public void onStart(Intent intent, int startId) {
        Log.e(TAG, "………TestService…….onStart");
    }
    private void showNotification() {
        Notification notification = new Notification(R.drawable.face_1,
                "Service started", System.currentTimeMillis());
        PendingIntent contentIntent = PendingIntent.getActivity(this, 0,
                new Intent(this, TestServiceHolder.class), 0);
        notification.setLatestEventInfo(this, "Test Service",
                "Service started", contentIntent);
        _nm.notify(R.string.service_started, notification);
    }
}

然后新建一个Activity类,用来调用,比如启动Service和停止Service,其他也类似:

private void startService() {
    Intent i = new Intent(this, TestService.class);
    this.startService(i);
}

private void stopService() {
    Intent i = new Intent(this, TestService.class);
    this.stopService(i);
}

下面来看一个Android运用Service的实例,就是最经典的用Service播放音乐。

首先新建2个按钮,用来播放和停止音乐。

<?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">
    <TextView android:layout_width="fill_parent"
        android:layout_height="wrap_content" android:text="@string/hello" />

    <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>

新建一个Activity类,用来调用Service。

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 {

    @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("START_AUDIO_SERVICE"));
        }
    };

    private OnClickListener stopIt = new OnClickListener() {
        public void onClick(View v) {
            stopService(new Intent("START_AUDIO_SERVICE"));
            finish();
        }
    };
}

下面是最关键的Service类。

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) {
        return null;
    }

    public void onStart(Intent intent, int startId) {
        super.onStart(intent, startId);
        player = MediaPlayer.create(this, R.raw.a1);
        player.start();
    }

    public void onDestroy() {
        super.onDestroy();
        player.stop();
    }
}

运行程序:

点击播放按钮,程序员开始播放MP3,如果此时退出程序,Service没有停止,音乐并不会停止;

点击停止按钮,音乐停止并退出程序。

无觅相关文章插件,快速提升流量

发表评论

电子邮件地址不会被公开。 必填项已用 * 标注

*

您可以使用这些 HTML 标签和属性: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>