Android中的Service使用
Service的生命周期 (适用于2.1及以上)
1. 被startService的
无论是否有任何活动绑定到该Service,都在后台运行。onCreate(若需要) -> onStart(int id, Bundle args). 多次startService,则onStart调用多次,但不会创建多个Service实例,只需要一次stop。该Service一直后台运行,直到stopService或者自己的stopSelf()或者资源不足由平台结束。
2. 被bindService的
调用bindService绑定,连接建立服务一直运行。未被startService只是BindService,则onCreate()执行,onStart(int,Bundle)不被调用;这种情况下绑定被解除,平台就可以清除该Service(连接销毁后,会导致解除,解除后就会销毁)。
3. 被启动又被绑定
类似startService的生命周期,onCreate onStart都会调用。
4. 停止服务时
stopService时显式onDestroy()。或不再有绑定(没有启动时)时隐式调用。有bind情况下stopService()不起作用。
以下是一个简单的实现例子,某些部分需要配合logcat观察。
AcMain.java
- package jtapp.myservicesamples;
- import android.app.Activity;
- import android.content.ComponentName;
- import android.content.Context;
- 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;
- import android.widget.Toast;
- public class AcMain extends Activity implements OnClickListener {
- private static final String TAG = "AcMain";
- private Button btnStart;
- private Button btnStop;
- private Button btnBind;
- private Button btnExit;
- /** Called when the activity is first created. */
- @Override
- public void onCreate(Bundle savedInstanceState) {
- super.onCreate(savedInstanceState);
- setContentView(R.layout.main);
- findView();
- }
- private void findView() {
- btnStart = (Button) findViewById(R.id.Start);
- btnStop = (Button) findViewById(R.id.Stop);
- btnBind = (Button) findViewById(R.id.Bind);
- btnExit = (Button) findViewById(R.id.Exit);
- btnStart.setOnClickListener(this);
- btnStop.setOnClickListener(this);
- btnBind.setOnClickListener(this);
- btnExit.setOnClickListener(this);
- }
- @Override
- public void onClick(View v) {
- Intent intent = new Intent("jtapp.myservicesamples.myservice");
- switch(v.getId()) {
- case R.id.Start:
- startService(intent);
- Toast.makeText(this,
- "myservice running " + MyService.msec/1000.0 + "s.",
- Toast.LENGTH_LONG).show();
- break;
- case R.id.Stop:
- stopService(intent);
- Toast.makeText(this,
- "myservice running " + MyService.msec/1000.0 + "s.",
- Toast.LENGTH_LONG).show();
- break;
- case R.id.Bind:
- bindService(intent, sc, Context.BIND_AUTO_CREATE);
- break;
- case R.id.Exit:
- this.finish();
- break;
- }
- }
- private MyService serviceBinder;
- private ServiceConnection sc = new ServiceConnection() {
- @Override
- public void onServiceDisconnected(ComponentName name) {
- Log.d(TAG, "in onServiceDisconnected");
- serviceBinder = null;
- }
- @Override
- public void onServiceConnected(ComponentName name, IBinder service) {
- Log.d(TAG, "in onServiceConnected");
- serviceBinder = ((MyService.MyBinder)service).getService();
- }
- };
- @Override
- protected void onDestroy() {
- //this.unbindService(sc);
- //this.stopService(
- // new Intent("jtapp.myservicesamples.myservice"));
- super.onDestroy();
- }
- }
复制代码
main.xml
- <?xml version="1.0" encoding="utf-8"?>
- <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
- android:orientation="vertical" android:layout_width="fill_parent"
- android:layout_height="fill_parent">
- <TextView android:layout_width="fill_parent"
- android:layout_height="wrap_content" android:text="@string/hello" />
- <Button android:text="Start MyService" android:id="@+id/Start"
- android:layout_width="wrap_content" android:layout_height="wrap_content"/>
- <Button android:text="Stop MyService" android:id="@+id/Stop"
- android:layout_width="wrap_content" android:layout_height="wrap_content"/>
- <Button android:text="Bind MyService" android:id="@+id/Bind"
- android:layout_width="wrap_content" android:layout_height="wrap_content"/>
- <Button android:text="Exit AcMain" android:id="@+id/Exit"
- android:layout_width="wrap_content" android:layout_height="wrap_content"/>
- </LinearLayout>
复制代码
MyService.java
- package jtapp.myservicesamples;
- 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 final String TAG = "MyService";
- public static long msec = 0;
- private boolean bThreadRunning = true;
- private final IBinder binder = new MyBinder();
- public class MyBinder extends Binder {
- MyService getService() {
- return MyService.this;
- }
- }
- @Override
- public IBinder onBind(Intent intent) {
- return binder;
- }
- @Override
- public void onCreate() {
- new Thread(new Runnable(){
- @Override
- public void run() {
- while (bThreadRunning) {
- try {
- Thread.sleep(100);
- } catch (InterruptedException e) {
- }
- Log.i(TAG, "myservice running " + (msec+=100) + "ms.");
- }
- }
- }).start();
- }
- @Override
- public void onDestroy() {
- bThreadRunning = false;
- super.onDestroy(); // 可以不用
- }
- }
复制代码
AnndroidManifest.xml
- <?xml version="1.0" encoding="utf-8"?>
- <manifest xmlns:android="http://schemas.android.com/apk/res/android"
- package="jtapp.myservicesamples" android:versionCode="1"
- android:versionName="1.0">
- <application android:icon="@drawable/icon" android:label="@string/app_name"
- android:debuggable="true">
- <activity android:name=".AcMain" android:label="@string/app_name">
- <intent-filter>
- <action android:name="android.intent.action.MAIN" />
- <category android:name="android.intent.category.LAUNCHER" />
- </intent-filter>
- </activity>
- <service android:name="MyService">
- <intent-filter>
- <action android:name="jtapp.myservicesamples.myservice"></action>
- </intent-filter>
- </service>
- </application>
- </manifest>
复制代码
Android中的Service使用的更多相关文章
- Android 中的 Service 全面总结(转载)
转载地址:http://www.cnblogs.com/newcj/archive/2011/05/30/2061370.html 感谢作者 Android 中的 Service 全面总结 1.Ser ...
- (转载)Android中的Service:Binder,Messenger,AIDL(2)
前言 前面一篇博文介绍了关于Service的一些基本知识,包括service是什么,怎么创建一个service,创建了一个service之后如何启动它等等.在这一篇博文里有一些需要前一篇铺垫的东西,建 ...
- (转载)所有分类 > 开发语言与工具 > 移动开发 > Android开发 Android中的Service:默默的奉献者 (1)
前言 这段时间在看一些IPC相关的东西,这里面就不可避免的要涉及到service,进程线程这些知识点,而且在研究的过程中我惊觉自己对这些东西的记忆已经开始有些模糊了——这可要不得.于是我就干脆花了点心 ...
- Android中的Service小结
简介 Service适合执行不需要和用户交互,而且长期运行的任务.即使程序被切换回后台,服务仍然可以正常运行.Service并不自动开启线程,默认运行在主线程中. Service中需要重载的函数 on ...
- Android 中的 Service 全面总结
1.Service的种类 按运行地点分类: 类别 区别 优点 缺点 应用 本地服务(Local) 该服务依附在主进程上, 服务依附在主进程上而不是独立的进程,这样在一定程度上节约了资源,另 ...
- Android 中的 Service 全面总结 (转)
原文地址:http://www.cnblogs.com/newcj/archive/2011/05/30/2061370.html 1.Service的种类 按运行地点分类: 类别 区别 优点 ...
- 【转】Android中保持Service的存活
这几天一直在准备考试,总算有个半天时间可以休息下,写写博客. 如何让Service keep alive是一个很常见的问题. 在APP开发过程中,需要Service持续提供服务的应用场景太多了,比如闹 ...
- Android中的service
1.service简介:service可以在和多场合的应用中使用,比如播放多媒体的时候用户启动了其他Activity这个时候程序要在后台继续播放,比如检测SD卡上文件的变化,再或者在后台记录你地理信息 ...
- Android中的Service与进程间通信(IPC)详解
Service 什么是Service 在后台长期运行的没有界面的组件.其他组件可以启动Service让他在后台运行,或者绑定Service与它进行交互,甚至实现进程间通信(IPC).例如,可以让服务在 ...
- Android中的Service组件具体解释
Service与Activity的差别在于:Service一直在后台执行,他没实用户界面,绝不会到前台来. 一,创建和配置Service 开发Service须要两个步骤:1.继承Service子类,2 ...
随机推荐
- 使用SGD(Stochastic Gradient Descent)进行大规模机器学习
原贴地址:http://fuliang.iteye.com/blog/1482002 其它参考资料:http://en.wikipedia.org/wiki/Stochastic_gradient_ ...
- 动态图片 Movie android-gif-drawable GifView
Movie 类 文档位置:/sdk/docs/reference/android/graphics/Movie.html 官方对这个类连一句介绍都没有,并且所有的方法也没有一行注释,可见多么不受重视! ...
- Unable to find manifest signing certificate in the certificate store
方法一:把DEF项目的属性->Signing选项->Sign the ClickOnce manifests 勾去掉,这样就可以编绎通过了: 方法二:用记事本打开 *.csproj文件 , ...
- 在Android中使用Android Ksoap2调用WebService
一.WebService介绍 WebService是基于SOAP协议可实现web服务器与web服务器之间的通信,因采用SOAP协议传送XML数据具有平台无关性,也是成为解决异构平台之间通信的重要解决方 ...
- Splunk的安装与使用
一.简单介绍 Splunk 是机器数据的引擎.使用 Splunk 可收集.索引和利用全部应用程序.server和设备(物理.虚拟和云中)生成的高速移动型计算机数据 .从一个位置搜索并分 ...
- 使用泛型集合取代datatable作为返回值实现面向对象
开会的时候,师父说.我们在机房重构时,尽量不要用datatable作为返回值.改用泛型集合的方式,这样能够实现真正的面向对象. 通过查资料和同学交流,把这个问题给攻克了. 对于泛型集合.我也有了一些认 ...
- mybatis如何根据mapper接口生成其实现类(springboot)
序 mybatis里头给sqlSession指定执行哪条sql的时候,有两种方式,一种是写mapper的xml的namespace+statementId,如下: public Student fin ...
- windows 用户变量和系统变量的差别
点击"我的电脑→属性→高级系统设置"标签的"环境变量"button,出现"环境变量"对话框,假设当前是以Administrator登录系统的 ...
- CentOS6.3 安装配置 ant
OS:CentOS6.3 ant版本:apache-ant-1.9.2-bin 第1步:下载ant apache-ant-1.9.2-bin.tar.gz 第2步:解压 tar -zxvf apach ...
- 在 Ubuntu 12.04 上通过源码安装 Open vSwitch (OVS)
安装 Ubuntu 12.04, 而且更新系统 apt-getupdate; apt-getupgrade; 安装所需的package apt-get install automake autocon ...