Android中Service(後台服務)詳解

來源:互聯網
上載者:User

Android中Service(後台服務)詳解

   這篇文章主要介紹了Android中Service(後台服務)詳解,本文講解了Service的概念、作用、生命週期、啟動方式和代碼執行個體等內容,需要的朋友可以參考下

  1.概念:

  (1).Service可以說是一個在後台啟動並執行Activity。它不是一個單獨的進程,它只需要應用告訴它要在後台做什麼就可以了。

  (2).它要是實現和使用者的互動的話需要通過通知欄或者是通過發送廣播,UI去接收顯示。

  (3).它的應用十分廣泛,尤其是在架構層,應用更多的是對系統服務的調用。

  2.作用:

  (1).它用於處理一些不干擾使用者使用的後台操作。如下載,網路擷取。播放音樂,他可以通過INTENT來開啟,同時也可以綁定到宿主對象(調用者例如ACTIVITY上)來使用。

  (2).如果說Activity是顯示前台頁面的資訊,那麼Service就是在後台進行操作的。如果Service和前台UI進行互動的話可以通過發送廣播或者通知欄的方式。

  3.生命週期:

  (1).service整體的生命時間是從onCreate()被調用開始,到onDestroy()方法返回為止。和activity一樣,service在onCreate()中進行它的初始化工作,在onDestroy()中釋放殘留的資源。

  (2).**startService()的方式:**onCreate()->onStartCommand()->onStart()->onDestroy()

  (3).**BindService()的方式:**onCreate()->onBinder()->onUnbind()->onDestroy()。onUnbind()方法返回後就結束了。

  4.啟動方式:

  (1).Service自己不能運行,需要通過某一個Activity或者其它Context對象來調用。

  (2).Service的啟動方式有兩種:

  Context.startService()和Context.bindService()兩種方式啟動Service。如果在service的onCreate()方法或者onStart()方法中有耗時的操作,要新開啟一個線程。 在需要service的地方通過以上兩種方式來啟動。

  注意:

  平常使用多的是startService方法,可以把一些耗時的任務放到後台去處理,當處理完成後,可以通過廣播或者通知欄來通知前台。

  5.以下通過代碼來深入理解:

  (1).MainActivity.java類:

  ?

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

25

26

27

28

29

30

31

32

33

34

35

36

37

38

39

40

41

42

43

44

45

46

47

48

49

50

51

52

53

54

55

56

57

58

59

60

61

62

63

64

65

66

67

68

69

70

71

72

73

74

75

76

77

78

79

package com.example.servicetest;

 

import com.example.servicetest.service.MyService;

 

import android.app.Activity;

import android.content.ComponentName;

import android.content.Intent;

import android.content.ServiceConnection;

import android.os.Bundle;

import android.os.IBinder;

import android.util.Log;

import android.view.View;

import android.view.View.OnClickListener;

import android.widget.Button;

 

public class MainActivity extends Activity implements OnClickListener {

/** 標誌位 */

private static String TAG = "com.example.servicetest.MainActivity";

/** 啟動服務 */

private Button mBtnStart;

/** 綁定服務 */

private Button mBtnBind;

 

@Override

protected void onCreate(Bundle savedInstanceState) {

super.onCreate(savedInstanceState);

setContentView(R.layout.activity_main);

initView();

}

 

/**

* init the View

*/

private void initView() {

mBtnStart = (Button) findViewById(R.id.startservice);

mBtnBind = (Button) findViewById(R.id.bindservice);

mBtnStart.setOnClickListener(this);

mBtnBind.setOnClickListener(this);

 

}

 

@Override

public void onClick(View view) {

switch (view.getId()) {

// 啟動服務的方式

case R.id.startservice:

startService(new Intent(MyService.ACTION));

break;

// 綁定服務的方式

case R.id.bindservice:

bindService(new Intent(MyService.ACTION), conn, BIND_AUTO_CREATE);

 

break;

 

default:

 

break;

}

 

}

 

ServiceConnection conn = new ServiceConnection() {

public void onServiceConnected(ComponentName name, IBinder service) {

Log.v(TAG, "onServiceConnected");

}

 

public void onServiceDisconnected(ComponentName name) {

Log.v(TAG, "onServiceDisconnected");

}

};

 

@Override

protected void onDestroy() {

super.onDestroy();

System.out.println("-------onDestroy()--");

stopService(new Intent(MyService.ACTION));

unbindService(conn);

}

}

  (2).MyService.java類:

  ?

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

25

26

27

28

29

30

31

32

33

34

35

36

37

38

39

40

41

42

43

44

45

46

47

48

49

50

51

52

53

54

55

56

57

58

59

60

package com.example.servicetest.service;

 

import android.app.Service;

import android.content.Intent;

import android.os.Binder;

import android.os.IBinder;

import android.util.Log;

 

public class MyService extends Service {

/** 標誌位 */

private static String TAG = "com.example.servicetest.service.MyService";

/** 行為 */

public static final String ACTION = "com.example.servicetest.service.MyService";

 

@Override

public void onCreate() {

super.onCreate();

 

System.out.println("----- onCreate() ---");

 

}

 

@Override

public void onStart(Intent intent, int startId) {

super.onStart(intent, startId);

System.out.println("----- onStart() ---");

}

 

@Override

public int onStartCommand(Intent intent, int flags, int startId) {

System.out.println("----- onStartCommand() ---");

return super.onStartCommand(intent, flags, startId);

}

 

@Override

public IBinder onBind(Intent arg0) {

System.out.println("----- onBind() ---");

return null;

}

 

 

@Override

public void onRebind(Intent intent) {

System.out.println("----- onRebind() ---");

super.onRebind(intent);

}

 

@Override

public boolean onUnbind(Intent intent) {

System.out.println("----- onUnbind() ---");

return super.onUnbind(intent);

}

 

@Override

public void onDestroy() {

System.out.println("----- onDestroy() ---");

super.onDestroy();

}

 

}

  (3).AndroidManifest.xml

  ?

1

2

3

4

5

6

7

8

9

10

<!-- 註冊 -->

<service android:name="com.example.servicetest.service.MyService" >

<intent-filter>

 

<!-- 用來啟動服務的Intent -->

<action android:name="com.example.servicetest.service.MyService" />

 

<category android:name="android.intent.category.default" />

</intent-filter>

</service>

  StartService方法:

  (1).當按startService按鈕的時候:如下:

  (2).再繼續按startService按鈕的時候:如下:

  BindService方法:

  (1).當按bindService按鈕的時候:如下:

  (2).再繼續按bindService按鈕的時候:如下:

  (3).先按startService按鈕再按bindService按鈕:如下:

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.