Android Service生命周期及用法

Android Service生命周期及用法
Service概念及用途:
Android中的服务,它与Activity不同,它是不能与用户交互的,不能自己启动的,运行在后台的程序,如果我们退出应用时,Service进程并没有结束,它仍然在后台运行,那 我们什么时候会用到Service呢?比如我们播放音乐的时候,有可能想边听音乐边干些其他事情,当我们退出播放音乐的应用,如果不用Service,我 们就听不到歌了,所以这时候就得用到Service了,又比如当我们一个应用的数据是通过网络获取的,不同时间(一段时间)的数据是不同的这时候我们可以 用Service在后台定时更新,而不用每打开应用的时候在去获取。
Service生命周期 :
Android Service的生命周期并不像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代码,我这里增加了四个按钮,代码如下:
view plain§copy to clipboard§print§?§
1<?xml version="1.0" encoding="utf-8"?>
2<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
3 android:orientation="vertical"
4 android:layout_width="fill_parent"
5 android:layout_height="fill_parent"
6 >
7 <TextView
8 android:id="@+id/text"
9 android:layout_width="fill_parent"
10 android:layout_height="wrap_content"
11 android:text="@string/hello"
12 />
13 <Button
14 android:id="@+id/startservice"
15 android:layout_width="fill_parent"
16 android:layout_height="wrap_content"
17 android:text="startService"
18 />
19 <Button
20 android:id="@+id/stopservice"
21 android:layout_width="fill_parent"
22 android:layout_height="wrap_content"
23 android:text="stopService"
24 />
25 <Button
26 android:id="@+id/bindservice"
27 android:layout_width="fill_parent"
28 android:layout_height="wrap_content"
29 android:text="bindService"
30 />
31 <Button
32 android:id="@+id/unbindservice"
33 android:layout_width="fill_parent"
34 android:layout_height="wrap_content"
35 android:text="unbindService"
36 />
37</LinearLayout>


第三步:新建一个Service,命名为MyService.java代码如下:
view plain§copy to clipboard§print§?§
38package com.tutor.servicedemo;
39import android.app.Service;
40import android.content.Intent;
41import android.os.Binder;
42import android.os.IBinder;
43import android.text.format.Time;
44import android.util.Log;
45public class MyService extends Service {
46 //定义个一个Tag标签
47 private static final String TAG = "MyService";
48 //这里定义吧一个Binder类,用在onBind()有方法里,这样Activity那边可以获取到
49 private MyBinder mBinder = new MyBinder();
50 @Override
51 public IBinder onBind(Intent intent) {
52 Log.e(TAG, "start IBinder~~~");
53 return mBinder;
54 }
55 @Override
56 public void onCreate() {
57 Log.e(TAG, "start onCreate~~~");
58 super.onCreate();
59 }
60
61 @Override
62 public void onStart(Intent intent, int startId) {
63 Log.e(TAG, "start onStart~~~");
64 super.onStart(intent, startId);
65 }
66
67 @Override
68 public void onDestroy() {
69 Log.e(TAG, "start onDestroy~~~");
70 super.onDestroy();
71 }
72
73
74 @Override
75 public boolean onUnbind(Intent intent) {
76 Log.e(TAG, "start onUnbind~~~");
77 return super.onUnbind(intent);
78 }
79
80 //这里我写了一个获取当前时间的函数,不过没有格式化就先这么着吧
81 public String getSystemTime(){
82
83 Time t = new Time();
84 t.setToNow();
85 return t.toString();
86 }
87
88 public class MyBinder extends Binder{
89 MyService getService()
90 {
91 return MyService.this;
92 }
93 }
94}


第四步:修改ServiceDemo.java,代码如下:
view plain§copy to clipboard§print§?§
95package com.tutor.servicedemo;
96import android.app.Activity;
97import android.content.ComponentName;
98import android.content.Context;
99import android.content.Intent;
100import android.content.ServiceConnection;
101import android.os.Bundle;
102import android.os.IBinder;
103import android.view.View;
104import android.view.View.OnClickListener;
105import android.widget.Button;
106import android.widget.TextView;
107public class ServiceDemo extends Activity implements OnClickListener{
108
109 private MyService mMyService;
110 private TextView mTextView;
111 private Button startServiceButton;
112 private Button stopServiceButton;
113 private Button bindServiceButton;
114 private Button unbindServiceButton;
115 private Context mContext;
116
117 //这里需要用到ServiceConnection在Context.bindService和context.unBindService()里用到
118 private ServiceConnection mServiceConnection = new ServiceConnection() {
119 //当我bindService时,让TextView显示MyService里getSystemTime()方法的返回值
120 public void onServiceConnected(ComponentName name, IBinder service) {
121 // TODO Auto-generated method stub
122 mMyService = ((MyService.MyBinder)service).getService();
123 mTextView.setText("I am frome Service :" + mMyService.getSystemTime());
124 }
125
126 public void onServiceDisconnected(ComponentName name) {
127 // TODO Auto-generated method stub
128
129 }
130 };
131 public void onCreate(Bundle savedInstanceState) {
132 super.onCreate(savedInstanceState);
133 setContentView(R.layout.main);
134 setupViews();
135 }
136
137 public void setupViews(){
138
139 mContext = ServiceDemo.this;
140 mTextView = (TextView)findViewById(R.id.text);
141
142
143
144 startServiceButton = (Button)findViewById(R.id.startservice);
145 stopServiceButton = (Button)findViewById(R.id.stopservice);
146 bindServiceButton = (Button)findViewById(R.id.bindservice);
147 unbindServiceButton = (Button)findViewById(R.id.unbindservice);
148
149 startServiceButton.setOnClickListener(this);
150 stopServiceButton.setOnClickListener(this);
151 bindServiceButton.setOnClickListener(this);
152 unbindServiceButton.setOnClickListener(this);
153 }
154
155 public void onClick(View v) {
156 // TODO Auto-generated method stub
157 if(v == startServiceButton){
158 Intent i = new Intent();
159 i.setClass(ServiceDemo.this, MyService.class);
160 mContext.startService(i);
161 }else if(v == stopServiceButton){
162 Intent i = new Intent();
163 i.setClass(ServiceDemo.this, MyService.class);
164 mContext.stopService(i);
165 }else if(v == bindServiceButton){
166 Intent i = new Intent();
167 i.setClass(ServiceDemo.this, MyService.class);
168 mContext.bindService(i, mServiceConnection, BIND_AUTO_CREATE);
169 }else{
170 mContext.unbindService(mServiceConnection);
171 }
172 }
173
174
175
176}


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

view plain§copy to clipboard§print§?§
177<?xml version="1.0" encoding="utf-8"?>
178<manifest xmlns:android="http://schemas.android.com/apk/res/android"
179 package="com.tutor.servicedemo"
180 android:versionCode="1"
181 android:versionName="1.0">
182 <application android:icon="@drawable/icon" android:label="@string/app_name">
183 <activity android:name=".ServiceDemo"
184 android:label="@string/app_name">
185 <intent-filter>
186 <action android:name="android.intent.action.MAIN" />
187 <category android:name="android.intent.category.LAUNCHER" />
188 </intent-filter>
189 </activity>
190 <service android:name=".MyService" android:exported="true"></service>
191 </application>
192 <uses-sdk android:minSdkVersion="7" />
193</manifest>


第六步:执行上述工程

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

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

点击stopService按钮时,Service则执行了onDestroy()方法

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

最后点击unbindService按钮,则Service执行了onUnbind()方法
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
资源包主要包含以下内容: ASP项目源码:每个资源包中都包含完整的ASP项目源码,这些源码采用了经典的ASP技术开发,结构清晰、注释详细,帮助用户轻松理解整个项目的逻辑和实现方式。通过这些源码,用户可以学习到ASP的基本语法、服务器端脚本编写方法、数据库操作、用户权限管理等关键技术。 数据库设计文件:为了方便用户更好地理解系统的后台逻辑,每个项目中都附带了完整的数据库设计文件。这些文件通常包括数据库结构图、数据表设计文档,以及示例数据SQL脚本。用户可以通过这些文件快速搭建项目所需的数据库环境,并了解各个数据表之间的关系和作用。 详细的开发文档:每个资源包都附有详细的开发文档,文档内容包括项目背景介绍、功能模块说明、系统流程图、用户界面设计以及关键代码解析等。这些文档为用户提供了深入的学习材料,使得即便是从零开始的开发者也能逐步掌握项目开发的全过程。 项目演示与使用指南:为帮助用户更好地理解和使用这些ASP项目,每个资源包中都包含项目的演示文件和使用指南。演示文件通常以视频或图文形式展示项目的主要功能和操作流程,使用指南则详细说明了如何配置开发环境、部署项目以及常见问题的解决方法。 毕业设计参考:对于正在准备毕业设计的学生来说,这些资源包是绝佳的参考材料。每个项目不仅功能完善、结构清晰,还符合常见的毕业设计要求和标准。通过这些项目,学生可以学习到如何从零开始构建一个完整的Web系统,并积累丰富的项目经验。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值