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接口编程及闭包表达式的筒鞋. 概述 在实际开发中,常常遇到使用模板模式的场 ...
随机推荐
- eBay_Relist(退换刊登费)
如果物品首次刊登结束时没有人中标,或是买家并没有付款完成交易,那么卖家以通过重新刊登的方法来再次销售.如果该物品在第二次刊登时成功售出,且满足eBay的重新刊登退费条件,那么eBay便会退还重新刊登的 ...
- ubuntu 以root 运行程序
body{ font-family: "Microsoft YaHei UI","Microsoft YaHei",SimSun,"Segoe UI& ...
- error_log() 范例
<?php// 如果无法连接到数据库,发送通知到服务器日志if (!Ora_Logon($username, $password)) { error_log("Oracle da ...
- python字符串关键点总结
python字符串关键点有下面几点: 1.一些引号分隔的字符 你可以把字符串看出是Python的一种数据类型,在Python单引号或者双引号之间的字符数组或者连续的字符集合.在python中最常用的引 ...
- 基于window.onerror事件 建立前端错误日志
QA不是万能的,用户的浏览环境非常复杂,很多情况无法靠测试用例去覆盖,所以最好建立一个前端错误日志,在真实用户端收集bug. try&catch是一个捕获前端错误的常见方法,比如: { //给 ...
- C# Timer用法及实例详解
C# Timer用法有哪些呢?我们在使用C# Timer时都会有自己的一些总结,那么这里向你介绍3种方法,希望对你了解和学习C# Timer使用的方法有所帮助. 关于C# Timer类 在C#里关于 ...
- Suricata+Barnyard2+Base的IDS前端Snorby
搭建基于Suricata+Barnyard2+Base的IDS前端Snorby 4.Barnyard2:http://www.securixlive.com/barnyard2/download.ph ...
- Android ListView 第一次设置Adapter时候getView调用多次
之前遇到这个奇怪现象,记录一下: 使用Listview并设置Adapter时, 会回调多次getView,比如我有4个items,按理说getView应该是调用一次(打出4个log),结果回调有4次( ...
- struts2介绍
struts2简介 Struts2框架发展 Struts于2000年5月由Craig McClanahan发起,并于 2001年7月发布了1.0版本,Struts一出现便大受欢迎,更成为了以后几年内w ...
- mysql中添加一个和root一样的用户用于远程连接
mysql中添加一个和root一样的用户用于远程连接: 大家在拿站时应该碰到过.root用户的mysql,只可以本地连,对外拒绝连接. 下面语句添加一个新用户administrtor: CREATE ...