服务 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 服务没有界面,一直运行在后台 ...
随机推荐
- Struts2 框架验证
struts2框架验证(xml方式): * 首先要从页面中获取对应的标签name属性的值,在动作类action中声明同名的属性,提供get和set方法 * 创建一个xml格式验证文 ...
- UVA11538Chess Queen(组合数学推公式)
转载请注明出处: http://www.cnblogs.com/fraud/ ——by fraud 题目意思:在n*m的棋盘中放置两个不同的皇后,使得两者能够相互攻击,共有多少种放置 ...
- TComboBox组件的重要属性
TComboBox组件的重要属性 CharCase--------此属性用于设置编辑框内文字的大小写DropDownCount---此属性用于设置当用户下拉组合框时不需要加滚动条就能显示的项的个数Dr ...
- c#播放声音文件
C#中声音的播放主要有三种方法: 1.使用API函数. 2.使用SoundPlayer类播放. 3.使用DirectX进行播放. 一.使用API函数进行播放. windows操作系统中的winmm.d ...
- htmlspecialchars()函数
htmlspecialchars() 函数把一些预定义的字符转换为 HTML 实体. 预定义的字符是: & (和号) 成为 & " (双引号) 成为 " ' (单引 ...
- Razor视图引擎
在MVC3.0版本的时候,微软终于引入了第二种模板引擎:Razor.在这之前,我们一直在使用WebForm时代沿留下来的ASPX引擎或者第三方的NVelocity模板引擎. (1)Razor文件类型: ...
- Hibernate+JPA
参考链接:http://blog.163.com/hero_213/blog/static/398912142010312024809 近年来ORM(Object-Relational Mapping ...
- 转:15 Best Responsive Web Design Testing Tools
Responsive Web Design is regarded as being the approach which suggests that web design and developme ...
- Update主循环、状态机的实现
从写一段程序,到写一个app,写一个游戏,到底其中有什么不同呢?一段程序的执行时间很短,一个应用的执行时间很长,仅此而已. 游戏中存在一个帧的概念. 这个概念大家都知道,类比的话,它就是电影胶卷的 ...
- 在网页中获取 facebook page 的内容
参考 : http://www.ibm.com/developerworks/cn/opensource/os-cn-facebookapi/ 1.首先你要有 facebook page, 内容要公开 ...