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接口编程及闭包表达式的筒鞋. 概述 在实际开发中,常常遇到使用模板模式的场 ...
随机推荐
- 网站不能访问(httperrLog【Timer_MinBytesPerSecond】【Timer_ConnectionIdle】)(转载)
在\LogFiles\HTTPERR的日志(C:\Windows\System32\LogFiles\HTTPERR)中发现了大量Timer_MinBytesPerSecond,Timer_Conne ...
- 转:struts标签之select详解
<html:select>生成HTML<select>元素 <html:option>:生成HTML<option>元素 <html:option ...
- ARM的工作模式和寄存器
以前学的时候学的是S3C6410的开发板,它是三星公司推出的基于ARM v6架构(指令集),处理器是ARM11. ARM架构是构建每个ARM处理器的基础. 目前最新的是ARM v8架构:http:// ...
- Linux 的多线程编程的高效开发经验(转)
http://www.ibm.com/developerworks/cn/linux/l-cn-mthreadps/ 背景 Linux 平台上的多线程程序开发相对应其他平台(比如 Windows)的多 ...
- GNU C 扩展(转)
GNU CC 是一个功能非常强大的跨平台 C 编译器,它对 C 语言提供了很多扩展,这些扩展对优化.目标代码布局.更安全的检查等方面提供了很强的支持.这里对支持支持 GNU 扩展的 C 语言成为 GN ...
- PHP递归题目
$arr = [ 'a' => 'A', 'b' => 'B', 'c' => [ 'd'=> 'D', 'e'=>[ 'f'=>'F', 'g'=>['h' ...
- .net 开源相关
http://roslyn.codeplex.com/SourceControl/latest https://github.com/dotnet http://www.dotnetfoundatio ...
- Linux-以指定用户运行redis
redis中无配置启动用户信息,需要添加redis用户,后以其启动 useradd -s /bash/false -M redis >& &
- linux包之dmidecode
http://www.dmtf.org/standards/smbios Dmidecode 这款软件允许你在 Linux 系统下获取有关硬件方面的信息.Dmidecode 遵循 SMBIOS/DMI ...
- maxscript,执行选中代码片段
选中一行或几行代码,然后按数字小键盘上的Enter键,即可单独运行之.此法方便调试.