歡迎來到Linux教程網
Linux教程網
Linux教程網
Linux教程網
Linux教程網 >> Linux編程 >> Linux編程 >> Android開發教程:Service簡析

Android開發教程:Service簡析

日期:2017/3/1 11:12:37   编辑:Linux編程

簡介

Service是Android 四大組件之一,它跟Activity的級別差不多,但是他不能自己運行,只能後台運行,並且可以和其他組件進行交互。

Service的啟動有兩種方式:context.startService()和context.bindService()。

1.使用context.startService()啟動Service

生命周期:
context.startService() ->onCreate()- >onStart()->Servicerunning->context.stopService()

onDestroy() ->Service stop

如果Service還沒有運行,則android先調用onCreate()然後調用onStart();如果Service已經運行,則只調用onStart(),所以一個Service的onStart方法可能會重復調用多次。

stopService的時候直接onDestroy,如果是調用者自己直接退出而沒有調用stopService的話,Service會一直在後台運行。該Service的調用者再啟動起來後可以通過stopService關閉Service。

所以調用startService的生命周期為:onCreate --> onStart(可多次調用) --> onDestroy

2.使用context.bindService()啟動Service

生命周期:

context.bindService()->onCreate()->onBind()->Service running

onUnbind() ->onDestroy() ->Servicestop

onBind將返回給客戶端一個IBind接口實例,IBind允許客戶端回調服務的方法,比如得到Service運行的狀態或其他操作。這個時候把調用者(Context,例如Activity)會和Service綁定在一起,Context退出了,Srevice就會調用onUnbind->onDestroy相應退出。

所以調用bindService的生命周期為:onCreate --> onBind(只一次,不可多次綁定) --> onUnbind -->onDestory。

在Service每一次的開啟關閉過程中,只有onStart可被多次調用(通過多次startService調用),其他onCreate,onBind,onUnbind,onDestory在一個生命周期中只能被調用一次。

service可以在和多場合的應用中使用,比如播放多媒體的時候用戶啟動了其他Activity這個時候程序要在後台繼續播放,比如檢測SD卡上文件的變化,再或者在後台記錄你地理信息位置的改變等等。

下面是一個實際的例子:

這個例子有四個類:



其中和Service有關的是PlayMusicActivit.java和MusicService.java

PlayMusicActivit是一個啟動界面上面有四個按鈕分別來啟動、暫停、停止和關閉Service

MusicService是一個實際的Service類

另外連個類是用來做通知的,將在通知裡面講解

  1. package com.my;
  2. import android.app.Activity;
  3. import android.app.NotificationManager;
  4. import android.content.Intent;
  5. import android.os.Bundle;
  6. import android.view.View;
  7. import android.widget.Button;
  8. public class PlayMusicActivity extends Activity {
  9. private static final int NOTIFICATION_ID = 10001;
  10. private Button playBtn;
  11. private Button stopBtn;
  12. private Button pauseBtn;
  13. private Button closeBtn;
  14. private Button exitBtn;
  15. @Override
  16. public void onCreate(Bundle savedInstanceState) {
  17. super.onCreate(savedInstanceState);
  18. setContentView(R.layout.main);
  19. playBtn = (Button) findViewById(R.id.play_btn);
  20. stopBtn = (Button) findViewById(R.id.stop_btn);
  21. pauseBtn = (Button) findViewById(R.id.pause_btn);
  22. closeBtn = (Button) findViewById(R.id.close_btn);
  23. exitBtn = (Button) findViewById(R.id.exit_btn);
  24. playBtn.setOnClickListener(new View.OnClickListener() {
  25. @Override
  26. public void onClick(View v) {
  27. Intent service = new Intent("com.my.musicService");
  28. Bundle value = new Bundle();
  29. value.putInt("opt", 1);
  30. service.putExtras(value);
  31. startService(service);
  32. }
  33. });
  34. stopBtn.setOnClickListener(new View.OnClickListener() {
  35. @Override
  36. public void onClick(View v) {
  37. Intent service = new Intent("com.my.musicService");
  38. Bundle value = new Bundle();
  39. value.putInt("opt", 2);
  40. service.putExtras(value);
  41. startService(service);
  42. }
  43. });
  44. pauseBtn.setOnClickListener(new View.OnClickListener() {
  45. @Override
  46. public void onClick(View v) {
  47. Intent service = new Intent("com.my.musicService");
  48. Bundle value = new Bundle();
  49. value.putInt("opt", 3);
  50. service.putExtras(value);
  51. startService(service);
  52. }
  53. });
  54. closeBtn.setOnClickListener(new View.OnClickListener() {
  55. @Override
  56. public void onClick(View v) {
  57. PlayMusicActivity.this.finish();
  58. }
  59. });
  60. exitBtn.setOnClickListener(new View.OnClickListener() {
  61. @Override
  62. public void onClick(View v) {
  63. Intent service = new Intent("com.my.musicService");
  64. stopService(service);
  65. final NotificationManager nm = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
  66. nm.cancel(NOTIFICATION_ID);
  67. PlayMusicActivity.this.finish();
  68. }
  69. });
  70. }
  71. }
  1. package com.my;
  2. import java.io.IOException;
  3. import android.app.Service;
  4. import android.content.Intent;
  5. import android.media.MediaPlayer;
  6. import android.os.Bundle;
  7. import android.os.IBinder;
  8. import android.util.Log;
  9. public class MusicService extends Service {
  10. private static final String TAG = "MusicService";
  11. private MediaPlayer mediaPlayer;
  12. @Override
  13. public IBinder onBind(Intent intent) {
  14. return null;
  15. }
  16. @Override
  17. public void onCreate() {
  18. Log.i(TAG, "create service");
  19. super.onCreate();
  20. if(mediaPlayer == null) {
  21. mediaPlayer = MediaPlayer.create(this, R.raw.he);
  22. mediaPlayer.setLooping(false);
  23. }
  24. }
  25. @Override
  26. public void onDestroy() {
  27. Log.i(TAG, "destroy service");
  28. super.onDestroy();
  29. if(mediaPlayer != null) {
  30. mediaPlayer.stop();
  31. mediaPlayer.release();
  32. }
  33. }
  34. @Override
  35. public void onStart(Intent intent, int startId) {
  36. Log.i(TAG, "start service");
  37. super.onStart(intent, startId);
  38. if(intent != null) {
  39. Bundle bundle = intent.getExtras();
  40. if(bundle != null) {
  41. int opt = bundle.getInt("opt");
  42. switch(opt) {
  43. case 1:
  44. play();break;
  45. case 2:
  46. stop();break;
  47. case 3:
  48. pause();break;
  49. }
  50. }
  51. }
  52. }
  53. private void play() {
  54. if(!mediaPlayer.isPlaying()) {
  55. mediaPlayer.start();
  56. }
  57. }
  58. private void pause() {
  59. if(mediaPlayer != null && mediaPlayer.isPlaying()) {
  60. mediaPlayer.pause();
  61. }
  62. }
  63. private void stop() {
  64. if(mediaPlayer != null) {
  65. mediaPlayer.stop();
  66. try {
  67. mediaPlayer.prepare();
  68. } catch (IllegalStateException e) {
  69. e.printStackTrace();
  70. } catch (IOException e) {
  71. e.printStackTrace();
  72. }
  73. }
  74. }
  75. }
Copyright © Linux教程網 All Rights Reserved