package com.homily.training.service;

 import android.app.Service;
import android.content.Intent;
import android.os.Binder;
import android.os.IBinder;
import android.support.annotation.Nullable;
import android.util.Log; import com.homily.training.test.service.ICallbackResult; /**
* Created by Rubert on 2016/7/6.
*/
public class BindService extends Service{ private final static String TAG = BindService.class.getSimpleName(); private MBinder mMBinder;
private ICallbackResult mICallbackResult;
private boolean unBindTarget = false; @Nullable
@Override
public IBinder onBind(Intent intent) {
Log.i(TAG, "============onBind==================");
return mMBinder;
}
@Override
public void onCreate() {
super.onCreate();
Log.i(TAG, "============onCreate==================");
mMBinder = new MBinder();
} @Override
public int onStartCommand(Intent intent, int flags, int startId) {
Log.i(TAG, "============onStartCommand==================");
return super.onStartCommand(intent, flags, startId);
} @Override
public void onDestroy() {
unBindTarget = true;
super.onDestroy();
Log.i(TAG, "============onDestroy==================");
} @Override
public boolean onUnbind(Intent intent) {
Log.i(TAG, "============onUnbind==================");
unBindTarget = true;//该处代码需要这么写是因为,Service中开启了线程。如果该Service直接onUnbind了,但是线程没有停止,并且如果再次bind该Service时,程序会再次重新实例化一个线程,并之前的线程也会一直运行下去,除非该app销毁。
return super.onUnbind(intent);
} public class MBinder extends Binder {
public void start(){
Log.i(TAG, "============MBinder-start==================");
new Thread(new Runnable() {
@Override
public void run() { while (true) {
if(unBindTarget) {
break;
}
Log.i(TAG, Thread.currentThread().getName() + "============MBinder-start-run==================");
mICallbackResult.OnBackResult(null);
try {
Thread.currentThread().sleep(5000);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}).start();
} public void bind(ICallbackResult result) {
mICallbackResult = result;
} } }
 package com.homily.training.service;

 import android.app.Service;
import android.content.Intent;
import android.os.IBinder;
import android.support.annotation.Nullable;
import android.util.Log; /**
* Created by Rubert on 2016/7/6.
*/
public class StartService extends Service{ private final static String TAG = StartService.class.getSimpleName(); @Nullable
@Override
public IBinder onBind(Intent intent) {
Log.i(TAG, "============onBind==================");
return null;
} @Override
public void onCreate() {
super.onCreate();
Log.i(TAG, "============onCreate==================");
} @Override
public int onStartCommand(Intent intent, int flags, int startId) {
Log.i(TAG, "============onStartCommand==================");
return super.onStartCommand(intent, flags, startId);
} @Override
public void onDestroy() {
super.onDestroy();
Log.i(TAG, "============onDestroy==================");
} @Override
public boolean onUnbind(Intent intent) {
Log.i(TAG, "============onUnbind==================");
return super.onUnbind(intent);
}
}
 package com.homily.training.test.service;

 import android.app.Activity;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.ServiceConnection;
import android.os.Binder;
import android.os.Bundle;
import android.os.IBinder;
import android.util.Log;
import android.view.View;
import android.widget.Button; import com.homily.training.R;
import com.homily.training.service.BindService;
import com.homily.training.service.StartService; /**
* Created by Rubert on 2016/7/6.
* 主要验证startService 启动后再次启动;以及bindService绑定后,解绑再次绑定的情况。
*/
public class ServiceMainAct extends Activity implements View.OnClickListener{ private final static String TAG = ServiceMainAct.class.getSimpleName(); Button startServiceBtn;
Button closeServiceBtn;
Button bindServiceBtn;
Button unbindServiceBtn;
BindService.MBinder mMBinder;
boolean IsBinder = false; @Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.service_layout);
startServiceBtn = (Button)findViewById(R.id.startService);
closeServiceBtn = (Button)findViewById(R.id.closeService);
bindServiceBtn = (Button)findViewById(R.id.binService);
unbindServiceBtn = (Button)findViewById(R.id.unbinService); startServiceBtn.setOnClickListener(this);
closeServiceBtn.setOnClickListener(this);
bindServiceBtn.setOnClickListener(this);
unbindServiceBtn.setOnClickListener(this);
} ServiceConnection mConnection = new ServiceConnection(){
@Override
public void onServiceConnected(ComponentName componentName, IBinder iBinder) {
Log.i(TAG, "=============onServiceConnected==================");
mMBinder = (BindService.MBinder)iBinder;
mMBinder.bind(mICallbackResult);
mMBinder.start();
IsBinder = true;
}
@Override
public void onServiceDisconnected(ComponentName componentName) {
Log.i(TAG, "=============onServiceDisconnected==================");
IsBinder = false;
}
}; ICallbackResult mICallbackResult = new ICallbackResult(){
@Override
public void OnBackResult(Object result) {
Log.i(TAG, "=============result==================");
}
}; @Override
public void onClick(View view) {
switch (view.getId()) {
case R.id.startService:
Intent sintent = new Intent(ServiceMainAct.this, StartService.class);
startService(sintent);
break;
case R.id.closeService:
Intent cintent = new Intent(ServiceMainAct.this, StartService.class);
stopService(cintent);
break;
case R.id.binService:
Intent service = new Intent(ServiceMainAct.this, BindService.class);
bindService(service, mConnection, Context.BIND_AUTO_CREATE);
break;
case R.id.unbinService:
if(mConnection != null && IsBinder)
unbindService(mConnection);
break;
} } }
 package com.homily.training.test.service;

 /**
* Created by Rubert on 2016/7/6.
*/
public interface ICallbackResult {
void OnBackResult(Object result);
}
<application
android:allowBackup="true"
android:icon="@mipmap/ic_launcher"
android:label="@string/app_name"
android:theme="@style/AppTheme" > <service android:name="com.homily.training.service.StartService" />
<service android:name="com.homily.training.service.BindService" /> <activity android:name=".test.service.ServiceMainAct">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
</application>
 <?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
> <Button
android:id="@+id/startService"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="startService"
/>
<Button
android:id="@+id/closeService"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="closeService"
/> <Button
android:id="@+id/binService"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="binService"
/>
<Button
android:id="@+id/unbinService"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="unbinService"
/> </LinearLayout>
Android开发的过程中,每次调用startService(Intent)的时候,都会调用该Service对象的onStartCommand(Intent,int,int)方法,然后在onStartCommand方法中做一些处理。然后我们注意到这个函数有一个int的返回值,这篇文章就是简单地讲讲int返回值的作用。
从Android官方文档中,我们知道onStartCommand有4种返回值:
 
START_STICKY:如果service进程被kill掉,保留service的状态为开始状态,但不保留递送的intent对象。随后系统会尝试重新创建service,由于服务状态为开始状态,所以创建服务后一定会调用onStartCommand(Intent,int,int)方法。如果在此期间没有任何启动命令被传递到service,那么参数Intent将为null。
 
START_NOT_STICKY:“非粘性的”。使用这个返回值时,如果在执行完onStartCommand后,服务被异常kill掉,系统不会自动重启该服务。
 
START_REDELIVER_INTENT:重传Intent。使用这个返回值时,如果在执行完onStartCommand后,服务被异常kill掉,系统会自动重启该服务,并将Intent的值传入。
 
START_STICKY_COMPATIBILITY:START_STICKY的兼容版本,但不保证服务被kill后一定能重启。

Service代码示例的更多相关文章

  1. [转]如何利用ndk-stack工具查看so库的调用堆栈【代码示例】?

    如何利用ndk-stack工具查看so库的调用堆栈[代码示例]? http://hi.baidu.com/subo4110/item/d00395b3bf63e4432bebe36d Step1:An ...

  2. My.Ioc 代码示例——使用观察者机制捕获注册项状态的变化

    在 My.Ioc 中,要想在服务注销/注册时获得通知,可以通过订阅 ObjectBuilderRegistered 和 ObjectBuilderUnregistering 这两个事件来实现.但是,使 ...

  3. JAVA NIO工作原理及代码示例

    简介:本文主要介绍了JAVA NIO中的Buffer, Channel, Selector的工作原理以及使用它们的若干注意事项,最后是利用它们实现服务器和客户端通信的代码实例. 欢迎探讨,如有错误敬请 ...

  4. Ice简介+Qt代码示例

    1.ICE是什么? ICE是ZEROC的开源通信协议产品,它的全称是:The Internet Communications Engine,翻译为中文是互联网通信引擎,是一个面向对象的中间件,它封装并 ...

  5. Unity构造函数注入代码示例

    Unity构造函数注入代码示例 如果使用 Unity 实例化一个类,该类的构造函数依赖一个或多个其他类,则 Unity 会为构造函数自动创建参数中指定的被依赖的类的实例.例如,下面的代码展示了一个名为 ...

  6. 实战SpringCloud响应式微服务系列教程(第十章)响应式RESTful服务完整代码示例

    本文为实战SpringCloud响应式微服务系列教程第十章,本章给出响应式RESTful服务完整代码示例.建议没有之前基础的童鞋,先看之前的章节,章节目录放在文末. 1.搭建响应式RESTful服务. ...

  7. Spring 注解学习 详细代码示例

    学习Sping注解,编写示例,最终整理成文章.如有错误,请指出. 该文章主要是针对新手的简单使用示例,讲述如何使用该注释,没有过多的原理解析. 已整理的注解请看右侧目录.写的示例代码也会在结尾附出. ...

  8. 高级渲染技巧和代码示例 GPU Pro 7

    下载代码示例 移动设备正呈现着像素越来越高,屏幕尺寸越来越小的发展趋势. 由于像素着色的能耗非常大,因此 DPI 的增加以及移动设备固有的功耗受限环境为降低像素着色成本带来了巨大的压力. MSAA 有 ...

  9. Java8-Function使用及Groovy闭包的代码示例

    导航 定位 概述 代码示例 Java-Function Groovy闭包 定位 本文适用于想要了解Java8 Function接口编程及闭包表达式的筒鞋. 概述 在实际开发中,常常遇到使用模板模式的场 ...

随机推荐

  1. ubuntu 14.04 apache maven 安装

    下载maven http://maven.apache.org/download.cgi  解压 tar -xzvf apache-maven-3.0.5-bin.tar.gz -C /usr/loc ...

  2. java编程之:Unsafe类

    Unsafe类在jdk 源码的多个类中用到,这个类的提供了一些绕开JVM的更底层功能,基于它的实现可以提高效率.但是,它是一把双刃剑:正如它的名字所预示的那样,它是 Unsafe的,它所分配的内存需要 ...

  3. 谓词的使用 -ios

    #import <Foundation/Foundation.h> @interface Person : NSObject<NSCopying> @property(nona ...

  4. myBatis 参数配置

    关于参数的类型 有四种类型: http://www.07net01.com/zhishi/402787.html 以上链接有所介绍,四种类型有:单个参数.多个参数.Map封装参数.List封装IN 如 ...

  5. 虚拟化之vmware-截图解释

    故障检测和主机网络隔离 代理会相互通信,并监控群集内各台主机的活跃度.默认情况下,此操作通过每秒交换一次检测信号来完成.如 果15 秒过去后仍未收到检测信号,而且 ping 不到该主机,则系统会声明该 ...

  6. 简单配置IIS 以及web service 实现js跨域

    因为浏览器的安全模型,js 是不能跨域的. 解决的方法有以下几种: 1. 使用代理服务转发 2. 目前服务器添加:Access-Control-Allow-Origin 3. 使用jsonp 4. 使 ...

  7. 【转】一个域名对应多个IP地址,接下来系统是依据什么决定使用哪个IP地址的?

    例如下图所示:nslookup http://www.sina.com.cn返回了多个IP地址,当使用curl通过域名进行访问时,则自动选择了其中一个地址进行访问,这个选择的过程里发生了什么事情? 绝 ...

  8. Jmeter使用

    好久没有试过Jmeter了,下载个新版本试试,顺便温习一下. 1. 如何修改JMeter语言环境 在菜单栏中通过“选项”–“选择语言”选了英文后,下次登录JMeter,还是显示的中文,修改语言无效.关 ...

  9. python有序查找算法:二分法

    二分法是一种快速查找的方法,时间复杂度低,逻辑简单易懂,总的来说就是不断的除以2除以2... 例如需要查找有序数组arr里面的某个关键字key的位置,那么首先确认arr的中位数或者中点center,下 ...

  10. 服务器返回的各种HTTP状态码介绍

    [摘要]HTTP状态码(HTTP Status Code)是用以表示网页服务器HTTP响应状态的3位数字代码.它由 RFC 2616 规范定义的,并得到RFC 2518.RFC 2817.RFC 22 ...