
Service组件简析
onCreate():当Service第一次创建时调用,用于初始化资源。 onBind(Intent):当Service绑定到其他组件时调用,通常用于返回Binder对象。 onUnbind(Intent):当Service从组件解绑时调用,释放资源。 onDestroy():当Service被销毁时调用,释放所有资源。 调用 实现 通过
发布日期:2021-05-07 13:27:23
浏览次数:19
分类:精选文章
本文共 6540 字,大约阅读时间需要 21 分钟。
Android Service 组件开发实例:计数器应用
概述
在Android开发中,Service组件是处理与用户无交互的业务逻辑的重要组件。与Activity不同,Service主要用于执行后台任务,如计数器、音乐播放、文件下载等。Service的生命周期管理与Activity有所不同,通常用于多线程任务处理。
Service 组件的启动方式
Service组件的启动方式分为显示启动和隐式启动:
- 隐式启动:通过组件名称启动,例如
startService(new ComponentName("com.example.MyService", MyService.class))
。 - 显示启动:通过类名启动,例如
startService(new Intent("com.example.MyService"))
。
Service 组件的生命周期
Service组件的生命周期主要包括以下几个阶段:
实例:计数器服务开发
应用程序结构
Android/packages/apps/Counter/├── AndroidManifest.xml├── Android.mk├── src/│ ├── com/android/counter│ │ ├── ICounterCallback.java│ │ ├── ICounterService.java│ │ ├── CounterService.java│ │ └── Counter.java├── res/│ ├── layout/│ │ └── main.xml│ ├── values/│ │ └── Strings.xml│ └── drawable/│ └── icon.png
ICounterCallback 接口
package com.android.counter;public interface ICounterCallback { void count(int val);}
ICounterService 接口
package com.android.counter;public interface ICounterService { public void startCounter(int initVal, ICounterCallback callback); public void stopCounter();}
CounterService 实现
package com.android.counter;import android.app.Service;import android.content.Intent;import android.os.AsyncTask;import android.os.Binder;import android.os.IBinder;import android.util.Log;public class CounterService extends Service implements ICounterService { private static final String LOG_TAG = "CounterService"; private boolean stop = false; private ICounterCallback counterCallback = null; private final IBinder binder = new CounterBinder(); public class CounterBinder extends Binder { public CounterService getService() { return CounterService.this; } } @Override public IBinder onBind(Intent intent) { return binder; } @Override public void onCreate() { super.onCreate(); Log.i(LOG_TAG, "Counter Service Created"); } @Override public void startCounter(int initVal, ICounterCallback callback) { counterCallback = callback; AsyncTask task = new AsyncTask() { @Override protected Integer doInBackground(Integer... vals) { Integer initCounter = vals[0]; stop = false; while (!stop) { publishProgress(initCounter); try { Thread.sleep(1000); } catch (InterruptedException e) { e.printStackTrace(); } initCounter++; } return initCounter; } @Override protected void onProgressUpdate(Integer... values) { super.onProgressUpdate(values); int val = values[0]; counterCallback.count(val); } @Override protected void onPostExecute(Integer val) { counterCallback.count(val); } }; task.execute(initVal); } @Override public void stopCounter() { stop = true; }}
Counter Activity 实现
package com.android.counter;import android.app.Activity;import android.content.ComponentName;import android.content.Context;import android.content.Intent;import android.content.IntentFilter;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;import android.widget.TextView;public class Counter extends Activity implements OnClickListener, ICounterCallback { private static final String LOG_TAG = "Counter"; private Button startButton; private Button stopButton; private TextView counterText; private ICounterService counterService; private ServiceConnection serviceConnection; @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.main); startButton = (Button) findViewById(R.id.button_start); stopButton = (Button) findViewById(R.id.button_stop); counterText = (TextView) findViewById(R.id.textview_counter); startButton.setOnClickListener(this); stopButton.setOnClickListener(this); startButton.setEnabled(true); stopButton.setEnabled(false); Intent bindIntent = new Intent(this, CounterService.class); bindService(bindIntent, serviceConnection, Context.BIND_AUTO_CREATE); Log.i(LOG_TAG, "Counter Activity Created"); } @Override public void onDestroy() { super.onDestroy(); unbindService(serviceConnection); } @Override public void onClick(View v) { if (v.equals(startButton)) { if (counterService != null) { counterService.startCounter(0, this); startButton.setEnabled(false); stopButton.setEnabled(true); } } else if (v.equals(stopButton)) { if (counterService != null) { counterService.stopCounter(); startButton.setEnabled(true); stopButton.setEnabled(false); } } } @Override public void count(int val) { counterText.setText(String.valueOf(val)); } private ServiceConnection getServiceConnection() { return new ServiceConnection() { @Override public void onServiceConnected(ComponentName className, IBinder service) { counterService = ((CounterService.CounterBinder) service).getService(); Log.i(LOG_TAG, "Counter Service Connected"); } @Override public void onServiceDisconnected(ComponentName className) { counterService = null; Log.i(LOG_TAG, "Counter Service Disconnected"); } }; }}
Activity 组件与 Service 组件的绑定
在Counter Activity中:
bindService()
方法启动CounterService组件。ServiceConnection
接口,接收Service组件的生命周期回调。ICounterCallback
接口实时更新UI。服务绑定机制
通过bindService()
方法,Activity组件与Service组件建立绑定关系。Service组件在绑定时返回Binder对象,Activity组件则通过Binder获取Service接口,实现双向通信。
总结
通过以上实例,可以了解Service组件在Android应用程序中的重要作用,包括其生命周期管理、绑定机制以及如何通过异步任务实现后台计数功能。Service组件与Activity组件的协同工作是Android应用程序开发的关键部分。
发表评论
最新留言
哈哈,博客排版真的漂亮呢~
[***.90.31.176]2025年03月27日 00时44分59秒
关于作者

喝酒易醉,品茶养心,人生如梦,品茶悟道,何以解忧?唯有杜康!
-- 愿君每日到此一游!
推荐文章
Linux网络环境配置(设置ip地址)
2019-03-04
Idea使用Spring Initializr来快速创建springboot项目
2019-03-04
Dijkstra算法的总结
2019-03-04
SpringCloud和SprinBoot之间的关系
2019-03-04
javascript定义变量及数据类型介绍
2019-03-04
C语言的运算符和表达式
2019-03-04
椭圆曲线密码系统——椭圆曲线
2019-03-04
Vue实现选项卡功能
2019-03-04
数据结构——链表
2019-03-04
uni-app请求头中携带token
2019-03-04
vue中接收后台的图片验证码并显示
2019-03-04
springboot入门(1)---整合MyBatis
2019-03-04
Vue入门学习笔记(1)
2019-03-04
趣谈win10常用快捷键
2019-03-04
数学建模(NO.18灰色预测)
2019-03-04
数学建模更新12(数学线性规划模型1)
2019-03-04
Android,SharedPreferences的使用
2019-03-04
JPEG压缩技术
2019-03-04
两款用于检测内存泄漏的软件
2019-03-04