Android Service生命周期及用法.docx

上传人:b****8 文档编号:30463435 上传时间:2023-08-15 格式:DOCX 页数:16 大小:231.78KB
下载 相关 举报
Android Service生命周期及用法.docx_第1页
第1页 / 共16页
Android Service生命周期及用法.docx_第2页
第2页 / 共16页
Android Service生命周期及用法.docx_第3页
第3页 / 共16页
Android Service生命周期及用法.docx_第4页
第4页 / 共16页
Android Service生命周期及用法.docx_第5页
第5页 / 共16页
点击查看更多>>
下载资源
资源描述

Android Service生命周期及用法.docx

《Android Service生命周期及用法.docx》由会员分享,可在线阅读,更多相关《Android Service生命周期及用法.docx(16页珍藏版)》请在冰豆网上搜索。

Android Service生命周期及用法.docx

AndroidService生命周期及用法

大家好,上一节我讲解了AndroidActivity的生命周期,这一节我将讲解一下Service,首先我们要知道Service具体是干什么的,什么时候用到?

以及它的生命周期等。

Service概念及用途:

Android中的服务,它与Activity不同,它是不能与用户交互的,不能自己启动的,运行在后台的程序,如果我们退出应用时,Service进程并没有结束,它仍然在后台运行,那我们什么时候会用到Service呢?

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

Service生命周期 :

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

Service与Activity通信:

Service后端的数据最终还是要呈现在前端Activity之上的,因为启动Service时,系统会重新开启一个新的进程,这就涉及到不同进程间通信的问题了(AIDL)这一节我不作过多描述,当我们想获取启动的Service实例时,我们可以用到bindService和onBindService方法,它们分别执行了Service中IBinder()和onUnbind()方法。

为了让大家更容易理解,我写了一个简单的Demo,大家可以模仿着我,一步一步的来。

 第一步:

新建一个Android工程,我这里命名为ServiceDemo.

第二步:

修改main.xml代码,我这里增加了四个按钮,代码如下:

viewplain

1.

xml version="1.0" encoding="utf-8"?

>  

2.

android="  

3.    android:

orientation="vertical"  

4.    android:

layout_width="fill_parent"  

5.    android:

layout_height="fill_parent"  

6.    >  

7.    

8.        android:

id="@+id/text"    

9.        android:

layout_width="fill_parent"   

10.        android:

layout_height="wrap_content"   

11.        android:

text="@string/hello"  

12.        />  

13.    

14.        android:

id="@+id/startservice"  

15.        android:

layout_width="fill_parent"  

16.        android:

layout_height="wrap_content"  

17.        android:

text="startService"  

18.    />  

19.    

20.        android:

id="@+id/stopservice"  

21.        android:

layout_width="fill_parent"  

22.        android:

layout_height="wrap_content"  

23.        android:

text="stopService"  

24.    />  

25.    

26.        android:

id="@+id/bindservice"  

27.        android:

layout_width="fill_parent"  

28.        android:

layout_height="wrap_content"  

29.        android:

text="bindService"  

30.    />  

31.    

32.        android:

id="@+id/unbindservice"  

33.        android:

layout_width="fill_parent"  

34.        android:

layout_height="wrap_content"  

35.        android:

text="unbindService"  

36.    />  

37.  

第三步:

新建一个Service,命名为MyService.java代码如下:

viewplain

1.package com.tutor.servicedemo;  

2.import android.app.Service;  

3.import android.content.Intent;  

4.import android.os.Binder;  

5.import android.os.IBinder;  

6.import android.text.format.Time;  

7.import android.util.Log;  

8.public class MyService extends Service {  

9.    //定义个一个Tag标签  

10.    private static final String TAG = "MyService";  

11.    //这里定义吧一个Binder类,用在onBind()有方法里,这样Activity那边可以获取到  

12.    private MyBinder mBinder = new MyBinder();  

13.    @Override  

14.    public IBinder onBind(Intent intent) {  

15.        Log.e(TAG, "start IBinder~~~");  

16.        return mBinder;  

17.    }  

18.    @Override  

19.    public void onCreate() {  

20.        Log.e(TAG, "start onCreate~~~");  

21.        super.onCreate();  

22.    }  

23.      

24.    @Override  

25.    public void onStart(Intent intent, int startId) {  

26.        Log.e(TAG, "start onStart~~~");  

27.        super.onStart(intent, startId);   

28.    }  

29.      

30.    @Override  

31.    public void onDestroy() {  

32.        Log.e(TAG, "start onDestroy~~~");  

33.        super.onDestroy();  

34.    }  

35.      

36.      

37.    @Override  

38.    public boolean onUnbind(Intent intent) {  

39.        Log.e(TAG, "start onUnbind~~~");  

40.        return super.onUnbind(intent);  

41.    }  

42.      

43.    //这里我写了一个获取当前时间的函数,不过没有格式化就先这么着吧  

44.    public String getSystemTime(){  

45.          

46.        Time t = new Time();  

47.        t.setToNow();  

48.        return t.toString();  

49.    }  

50.      

51.    public class MyBinder extends Binder{  

52.        MyService getService()  

53.        {  

54.            return MyService.this;  

55.        }  

56.    }  

57.}  

第四步:

修改ServiceDemo.java,代码如下:

viewplain

1.package com.tutor.servicedemo;  

2.import android.app.Activity;  

3.import android.content.ComponentName;  

4.import android.content.Context;  

5.import android.content.Intent;  

6.import android.content.ServiceConnection;  

7.import android.os.Bundle;  

8.import android.os.IBinder;  

9.import android.view.View;  

10.import android.view.View.OnClickListener;  

11.import android.widget.Button;  

12.import android.widget.TextView;  

13.public class ServiceDemo extends Activity implements OnClickListener{  

14.     

15.    private MyService  mMyService;  

16.    private TextView mTextView;  

17.    private Button startServiceButton;  

18.    private Button stopServiceButton;  

19.    private Button bindServiceButton;  

20.    private Button unbindServiceButton;  

21.    private Context mContext;  

22.      

23.    //这里需要用到ServiceConnection在Context.bindService和context.unBindService()里用到  

24.    private ServiceConnection mServiceConnection = new ServiceConnection() {  

25.        //当我bindService时,让TextView显示MyService里getSystemTime()方法的返回值   

26.        public void onServiceConnected(ComponentName name, IBinder service) {  

27.            // TODO Auto-generated method stub  

28.            mMyService = ((MyService.MyBinder)service).getService();  

29.            mTextView.setText("I am frome Service :

" + mMyService.getSystemTime());  

30.        }  

31.          

32.        public void onServiceDisconnected(ComponentName name) {  

33.            // TODO Auto-generated method stub  

34.              

35.        }  

36.    };  

37.    public void onCreate(Bundle savedInstanceState) {  

38.        super.onCreate(savedInstanceState);  

39.        setContentView(R.layout.main);  

40.        setupViews();  

41.    }  

42.      

43.    public void setupViews(){  

44.      

45.        mContext = ServiceDemo.this;  

46.        mTextView = (TextView)findViewById(R.id.text);  

47.          

48.          

49.          

50.        startServiceButton = (Button)findViewById(R.id.startservice);  

51.        stopServiceButton = (Button)findViewById(R.id.stopservice);  

52.        bindServiceButton = (Button)findViewById(R.id.bindservice);  

53.        unbindServiceButton = (Button)findViewById(R.id.unbindservice);  

54.          

55.        startServiceButton.setOnClickListener(this);  

56.        stopServiceButton.setOnClickListener(this);  

57.        bindServiceButton.setOnClickListener(this);  

58.        unbindServiceButton.setOnClickListener(this);  

59.    }  

60.     

61.    public void onClick(View v) {  

62.        // TODO Auto-generated method stub  

63.        if(v == startServiceButton){  

64.            Intent i  = new Intent();  

65.            i.setClass(ServiceDemo.this, MyService.class);  

66.            mContext.startService(i);  

67.        }else if(v == stopServiceButton){  

68.            Intent i  = new Intent();  

69.            i.setClass(ServiceDemo.this, MyService.class);  

70.            mContext.stopService(i);  

71.        }else if(v == bindServiceButton){  

72.            Intent i  = new Intent();  

73.            i.setClass(ServiceDemo.this, MyService.class);  

74.            mContext.bindService(i, mServiceConnection, BIND_AUTO_CREATE);  

75.        }else{  

76.            mContext.unbindService(mServiceConnection);  

77.        }  

78.    }  

79.      

80.      

81.      

82.}  

第五步:

修改AndroidManifest.xml代码(将我们新建的MyService注册进去如下代码第14行:

) 

viewplain

1.

xml version="1.0" encoding="utf-8"?

>  

2.

android="  

3.      package="com.tutor.servicedemo"  

4.      android:

versionCode="1"  

5.      android:

versionName="1.0">  

6.    

icon="@drawable/icon" android:

label="@string/app_name">  

7.        

name=".ServiceDemo"  

8.                  android:

label="@string/app_name">  

9.              

10.                

name="android.intent.action.MAIN" />  

11.                

name="android.intent.category.LAUNCHER" />  

12.              

13.          

14.        

name=".MyService" android:

exported="true">  

15.      

16.    

minSdkVersion="7" />  

17.   

 六步:

执行上述工程,效果图如下:

点击startServie按钮时先后执行了Service中onCreate()->onStart()这两个方法,打开Logcat视窗效果如下图:

我们这时可以按HOME键进入Settings(设置)->Applications(应用)->RunningServices(正在运行的服务)看一下我们新启动了一个服务,效果如下:

点击stopService按钮时,Service则执行了onDestroy()方法,效果图如下所示:

这时候我们再次点击startService按钮,然后点击bindService按钮(通常bindService都是bind已经启动的Service),我们看一下Service执行了IBinder()方法,以及TextView的值也有所变化了,如下两张图所示:

 

最后点击unbindService按钮,则Service执行了onUnbind()方法,如下图所示:

大家好,好久不见,今天在开发中遇到的一个问题给大家分享一下,我先前做了一个音乐播放器,因为播放音乐一般都是用服务来处理的。

当用户点击播放按钮时,音乐在服务中播放,然后用用户退出程序(服务进程还在,音乐还继续),所以妥用户点再次进入应用时,我们播放器要处于播放状态,这里我作了简单的处理,判断这个音乐服务是否开启来完成的。

今天给大家的小例子是列出Android设备中所有启动的服务,及判断某个服务是否开启,具体步骤如下了:

第一步:

新建一个Android工程,命名为RunningService。

第二步:

修改RunningService.java代码如下:

viewplain

1.package com.tutor.runningservice;  

2.import java.util.List;  

3.import android.app.Activity;  

4.import android.app.ActivityManager;  

5.import android.os.Bundle;  

6.import android.widget.TextView;  

7.public class RunningService extends Activity {  

8.    /** Called when the activity is first created. */  

9.    @Override  

10.    public void onCreate(Bundle savedInstanceState) {  

11.        super.onCreate(savedInstanceState);  

12.        //setContentView(R.layout.main);  

展开阅读全文
相关资源
猜你喜欢
相关搜索

当前位置:首页 > PPT模板 > 其它模板

copyright@ 2008-2022 冰豆网网站版权所有

经营许可证编号:鄂ICP备2022015515号-1