服务 Service 基本介绍
Activity
public class MainActivity extends ListActivity {private boolean flag;//是否开启线程public static final String ACTION_TEST_SERVICE = "com.bqt.service.TEST_SERVICE";private MyServiceConnection conn;private IBinderInterface mIBinder;//之所以另外定义一个接口IBinderInterface,而不是直接用MyService.MyBinder,是为了使用统一接口访问,达到解耦、隐藏的目的@Overrideprotected void onCreate(Bundle savedInstanceState) {super.onCreate(savedInstanceState);List<String> mData = new ArrayList<String>(Arrays.asList("开启一个线程,执行死循环操作", "关闭上面开启的所有线程",//"startService方式开启服务", "stopService方式关闭服务", "bindService方式开启服务 ", "unbindService方式解除绑定服务",//"startService启动服务后再bindService", "通过IBinder间接调用服务中的方法"));ListAdapter mAdapter = new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1, mData);setListAdapter(mAdapter);conn = new MyServiceConnection();}@Overrideprotected void onListItemClick(ListView l, View v, int position, long id) {switch (position) {case 0:flag = true;final long time = System.currentTimeMillis();//当前时间的毫秒值Toast.makeText(MainActivity.this, "一个新的线程已开启……", Toast.LENGTH_SHORT).show();new Thread(new Runnable() {@Overridepublic void run() {while (flag) {Log.i("bqt", (System.currentTimeMillis() - time) / 1000 + "");//多少秒try {Thread.sleep(1000);} catch (InterruptedException e) {e.printStackTrace();}}}}).start();break;case 1:flag = false;Toast.makeText(MainActivity.this, "所有线程已关闭……", Toast.LENGTH_SHORT).show();break;case 2://startService方式开启服务。onCreate()--> onStartCommand() --->onDestory() 。onBind()方法并没有startService(new Intent(this, MyService.class));//当调用者结束了自己的生命周期,但是只要没调用stopService,那么Service还是会继续运行break;case 3://stopService方式关闭服务。service不建议采用隐式方式启动,在高版本可能警告"不安全",更高版本可能直接异常退出stopService(new Intent(ACTION_TEST_SERVICE));//服务只会被停止一次,但多次调用并不会异常break;case 4://绑定的方式开启服务 onCreate() --->onBind();--->onUnbind()-->onDestory() 绑定服务不会调用onStartCommand方法bindService(new Intent(this, MyService.class), conn, BIND_AUTO_CREATE);//flags:绑定时如果Service还未创建是否自动创建;0:不自动创建;1:自动创建break;case 5:unbindService(conn);//多次调用会异常!mIBinder = null;//若不把mIBinder置为空,则服务销毁后仍然可以调用服务里的方法,因为内部类的引用还在break;case 6:startService(new Intent(this, MyService.class));//使用bindService来绑定一个【已启动】的Service时,系统只是将Service的内部IBinder对象传递给Activity,并不会将Service的生命周期与Activity绑定bindService(new Intent(this, MyService.class), conn, BIND_AUTO_CREATE);//所以,此时调用unBindService方法取消绑定后,Service不会调用onDestroy方法break;case 7:if (mIBinder != null) {mIBinder.callMethodInService(100);} else {Toast.makeText(this, "还没有绑定呦……", Toast.LENGTH_SHORT).show();}break;}}private class MyServiceConnection implements ServiceConnection {//Interface for monitoring监控 the state of an application service@Override/**此方法中的IBinder即为我们调用bindService方法时Service的onBind方法返回的对象,我们可以在此方法回调后通过这个IBinder与Service进行通信 */public void onServiceConnected(ComponentName name, IBinder service) {//访问者与Service连接成功时回调//Called when a connection连接 to the Service has been established确定、已建立, with the IBinder of the communication channel to the Service.mIBinder = (IBinderInterface) service;Toast.makeText(MainActivity.this, "服务已连接……", Toast.LENGTH_SHORT).show();}@Overridepublic void onServiceDisconnected(ComponentName name) {//异常终止或者其他原因终止导致Service与访问者断开连接时回调Toast.makeText(MainActivity.this, "服务已断开连接……", Toast.LENGTH_SHORT).show();}}}
Service
public class MyService extends Service {@Overridepublic void onCreate() {Log.i("bqt", "onCreate");super.onCreate();}@Overridepublic IBinder onBind(Intent intent) {//如果再次使用bindService绑定Service,系统不会再调用onBind()方法,而是直接把IBinder对象传递给其他后来增加的客户端Log.i("bqt", "onBind");return new MyBinder();//当访问者通过bindService方法与Service连接成功后,系统会将此返回的IBinder接口类型对象,通过bindService中的参数ServiceConnection对象的onServiceConnected方法,传递给访问者,访问者通过该对象便可以与Service组件进行通信}@Overridepublic void onRebind(Intent intent) {super.onRebind(intent);Log.i("bqt", "onRebind");}@Overridepublic int onStartCommand(Intent intent, int flags, int startId) {//客户端每次调用startService方法时都会回调此方法;调用bindService时不会回调此方法Log.i("bqt", "onStartCommand");return super.onStartCommand(intent, flags, startId);}@Overridepublic boolean onUnbind(Intent intent) {//绑定多客户端情况下,需要解除所有的绑定后才会(就会)调用onDestoryed方法,除非service也被startService()方法开启Log.i("bqt", "onUnbind");return super.onUnbind(intent);}@Overridepublic void onDestroy() {Log.i("bqt", "onDestroy");super.onDestroy();}//******************************************************************************************/**这是服务里面的一个方法,对外是隐藏的,只能通过IBinder间接访问*/private void methodInService() {Toast.makeText(this, "服务里的方法被调用了……", Toast.LENGTH_SHORT).show();}private class MyBinder extends Binder implements IBinderInterface {//须实现IBinder接口或继承Binder类。对外是隐藏的。public void callMethodInService(int money) {if (money > 0) {methodInService();//间接调用了服务中的方法}}}}
联系Activity和Service的中间接口
public interface IBinderInterface {public void callMethodInService(int money);}
清单文件
<?xml version="1.0" encoding="utf-8"?><manifest xmlns:android="http://schemas.android.com/apk/res/android"package="com.bqt.service"android:versionCode="1"android:versionName="1.0" ><uses-sdkandroid:minSdkVersion="8"android:targetSdkVersion="17" /><applicationandroid:allowBackup="true"android:icon="@drawable/ic_launcher"android:label="@string/app_name"android:theme="@style/AppTheme" ><activityandroid:name=".MainActivity"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="com.bqt.service.TEST_SERVICE" /></intent-filter></service></application></manifest>
服务 Service 基本介绍的更多相关文章
- WebService服务调用方法介绍
1 背景概述 由于在项目中需要多次调用webservice服务,本文主要总结了一下java调用WebService常见的6种方式,即:四种框架的五种调用方法以及使用AEAI ESB进行调用的方法. 2 ...
- 【AngularJS中的自定义服务service VS factory VS provider】---它们的区别,你知道么?
在介绍AngularJS自定义服务之前,我们先来了解一下AngularJS~ 学过HTML的人都知道,HTML是一门很好的伪静态文本展示设计的声明式语言,但是,要构建WEB应用的话它就显得乏力了. 而 ...
- Android服务——Service
服务 Service 是一个可以在后台执行长时间运行操作而不使用用户界面的应用组件.服务可由其他应用组件启动,而且即使用户切换到其他应用,服务仍将在后台继续运行. 此外,组件可以绑定到服务,以与之进行 ...
- linux中服务(service)管理
一.介绍 服务(service) 本质就是进程,但是是运行在后台的,通常都会监听某个端口,等待其它程序的请求,比如(mysql , sshd 防火墙等),因此我们又称为守护进程,是Linux 中非常重 ...
- Android系统编程入门系列之加载服务Service
之前几篇文章简单梳理了在Android系统的四大组件之一,最主要的界面Activity中,使应用程序与用户进行交互响应的相关知识点,那对于应用程序中不需要与用户交互的逻辑,又要用到哪些内容呢?本文开始 ...
- Android系统编程入门系列之服务Service齐头并进多线程任务
在上篇文章中初步了解了Android系统的四大组件之一的服务Service,在服务内可以执行无用户交互的耗时操作任务,但是包括之前关于界面系列文章在内,生命周期方法都是在主线程内被系统回调的.如果直接 ...
- 在 CentOS7 上将自定义的 jar 包注册为 linux 服务 service
在 CentOS7 上将自定义的 jar 包注册为 linux 服务 service 1.在 /etc/rc.d/init.d/ 目录下创建一个名字和服务名完全相同的 shell 脚本文件 joyup ...
- [推荐]dubbo分布式服务框架知识介绍
[推荐]dubbo分布式服务框架知识介绍 CentOS+Jdk+Jboss+dubbo+zookeeper集群配置教程 http://wenku.baidu.com/view/20e8f36bf ...
- 安卓第十三天笔记-服务(Service)
安卓第十三天笔记-服务(Service) Servcie服务 1.服务概念 服务 windows 服务没有界面,一直运行在后台, 运行在独立的一个进程里面 android 服务没有界面,一直运行在后台 ...
随机推荐
- MySQL利用binlog来恢复数据库
1.根据binlog解析出所有ring数据库的所有sql [mysql@localhost ]$ mysqlbinlog --no-defaults --database=ring --start-d ...
- 杂记之web篇
问题1:通过POST方式提交给后台的数据出现了乱码,用部分浏览器测试却是好的. 解决办法: 在web.config文件中加上 <globalization responseEncoding=&q ...
- JDK环境变量配置及Tomcat安装服务
1.测试jdk安装是否成功: 在cmd中输入java -version 2.环境变量: 1)新建系统变量JAVA_HOME,如:D:\Program Files\Java\jdk1.8.0_60 2) ...
- C# linq的学习及使用
linq可以对多种数据源和对象进行查询,如数据库.数据集.XML文档.数组等. 通过对linq的使用,可以减少代码量并优化检索操作. LINQ关键字 from 指定数据源和范围变量 where 根据布 ...
- Oracle Union All 排序
在oracle中使用union all或者 union 对两个结果集进行并集操作时,如果需要对查询结果集进行排序时,不能直接在后面加order by + 表字段 来排序 例如: 在oracle的soc ...
- android 手机信息获取
1. adb已安装 2. adb shell getprop 此时已列出所有相关信息
- jQuery中的$("#my_id").html()中一点要注意的
aaarticlea/png;base64,iVBORw0KGgoAAAANSUhEUgAAAXcAAAA3CAIAAAB4jZ1xAAAJdUlEQVR4nO2dPU/rPBTHn2/VoVMrXZ
- PHPCMS v9构建模块
■补课: 1.phpcms v9帮助文件,上面会写关于二次开发的一些方法. http://v9.help.phpcms.cn/ 2.找一个后台还没安装的模块,先把代码看一边.比如dianping模块 ...
- python 的内置函数(1)
19.内置函数: abs():求绝对值 bool():求一个值是True or False ,其中False值有 0 ,空字符串'',None,空 ...
- YII 事件event和行为Behavior
To declare an event in your CComponent child class, you should add a method with aname starting with ...