Service代码示例
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>
Service代码示例的更多相关文章
- [转]如何利用ndk-stack工具查看so库的调用堆栈【代码示例】?
如何利用ndk-stack工具查看so库的调用堆栈[代码示例]? http://hi.baidu.com/subo4110/item/d00395b3bf63e4432bebe36d Step1:An ...
- My.Ioc 代码示例——使用观察者机制捕获注册项状态的变化
在 My.Ioc 中,要想在服务注销/注册时获得通知,可以通过订阅 ObjectBuilderRegistered 和 ObjectBuilderUnregistering 这两个事件来实现.但是,使 ...
- JAVA NIO工作原理及代码示例
简介:本文主要介绍了JAVA NIO中的Buffer, Channel, Selector的工作原理以及使用它们的若干注意事项,最后是利用它们实现服务器和客户端通信的代码实例. 欢迎探讨,如有错误敬请 ...
- Ice简介+Qt代码示例
1.ICE是什么? ICE是ZEROC的开源通信协议产品,它的全称是:The Internet Communications Engine,翻译为中文是互联网通信引擎,是一个面向对象的中间件,它封装并 ...
- Unity构造函数注入代码示例
Unity构造函数注入代码示例 如果使用 Unity 实例化一个类,该类的构造函数依赖一个或多个其他类,则 Unity 会为构造函数自动创建参数中指定的被依赖的类的实例.例如,下面的代码展示了一个名为 ...
- 实战SpringCloud响应式微服务系列教程(第十章)响应式RESTful服务完整代码示例
本文为实战SpringCloud响应式微服务系列教程第十章,本章给出响应式RESTful服务完整代码示例.建议没有之前基础的童鞋,先看之前的章节,章节目录放在文末. 1.搭建响应式RESTful服务. ...
- Spring 注解学习 详细代码示例
学习Sping注解,编写示例,最终整理成文章.如有错误,请指出. 该文章主要是针对新手的简单使用示例,讲述如何使用该注释,没有过多的原理解析. 已整理的注解请看右侧目录.写的示例代码也会在结尾附出. ...
- 高级渲染技巧和代码示例 GPU Pro 7
下载代码示例 移动设备正呈现着像素越来越高,屏幕尺寸越来越小的发展趋势. 由于像素着色的能耗非常大,因此 DPI 的增加以及移动设备固有的功耗受限环境为降低像素着色成本带来了巨大的压力. MSAA 有 ...
- Java8-Function使用及Groovy闭包的代码示例
导航 定位 概述 代码示例 Java-Function Groovy闭包 定位 本文适用于想要了解Java8 Function接口编程及闭包表达式的筒鞋. 概述 在实际开发中,常常遇到使用模板模式的场 ...
随机推荐
- Nanopore sensors for nucleic acid analysis 论文阅读笔记
Nanopore sensors for nucleic acid analysis Bala Murali Venkatesan and Rashid Bashir 用于核酸分析的纳米孔传感器 纳米 ...
- 最大化 AIX 上的 Java 性能,第 1 部分: 基础
http://www.ibm.com/developerworks/cn/aix/library/es-Javaperf/es-Javaperf1.html 最大化 AIX 上的 Java 性能,第 ...
- Linux文件普通权限
1.文件所有者,所属用户组,其他用户1)文件所有者:创建文件的用户2)所属用户组:文件属于哪个用户组3)其他用户:不是文件所有者,不属于文件所属用户组的用户,称为其他用户 2.Linux文件权限我们切 ...
- 使用Myeclipse 2015 进行 Hdp 4 windows 开发
在本地环境下进行开发,使用cygwin安装 Hdp那就是一个呵呵岂能概括. 所以啊,还是用Hdp windows进行开发测试吧.这样感觉省心点.具体 Hdp windows的安装参看前面的文章或自行G ...
- CentOs6.5中安装和配置vsftp
一.vsftp安装篇 复制代码代码如下: # 安装vsftpdyum -y install vsftpd# 启动service vsftpd start# 开启启动chkconfig vsftpd o ...
- Kettle合并记录步骤
转载: http://blog.itpub.net/post/37422/464323 该步骤用于将两个不同来源的数据合并,这两个来源的数据分别为旧数据和新数据,该步骤将旧数据和新数据按照指定的关键字 ...
- webqq协议请求交互过程
1.http://my.oschina.net/ij2ee/blog/191692 2.http://www.qqxieyi.com/fenxi_show.asp?id=34
- Hibernate常用配置文件详解
本文转载自:http://blog.csdn.net/csh624366188/article/details/7578939 初学hibernate的童鞋,刚开应该都有这种感觉,hibernate的 ...
- 拖动控件 javascript原生,兼容IE6-11、chrome、firefox、Opera、Safari
鼠标拖动元素,对于初学者来说,是一个很难的话题,其实只要应用好事件,就能很好的控制拖动的对象,其主要事件是 mousedown,mousemove,mouseup,其原理是在鼠标点击元素时,在给定鼠标 ...
- 会话控制:SESSION,COOKIE
1.http协议: HTTP—超文本传输协议,在TCP协议(长连接.像一个硬件)基础上; 特点:短连接,无状态协议,没法记录本次连接的状态;适用于静态页面的访问,对于后期某些页面是需要浏览器预知客户信 ...