服务 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 服务没有界面,一直运行在后台 ...
随机推荐
- 如何动态修改grid的列名
有这样的需求,搜索时候会选择搜索类型,每种搜索类型展示的列名不一样 如何动态修改grid的列名 效果图:点击bColumn页面切换成bColumn 实现思路:通过grid的reconfigure方法, ...
- Objective-C学习篇08—NSDictionary与NSSet
NSDictionary与NSMutableDictionary NSSet与NSMutableSte 字典 字典:字典分为可变字典NSDictionary和不可变字典NSMutableDiction ...
- ContentProvider URI的组成
ContentProvider URI由哪几部分组成 ContentProvider URI与HTTP URI类似,由以下4部分组成: 1.content:// 相当于HTTP URI中的http ...
- Thinkphp 控制器
控 制 器: 1.命名方法:新建一个主页面的控制器 controller文件夹下新建一个文件,命名为:MainController.class.php首字母都大写,称为驼峰命名法 eg: <?p ...
- Oracle database启动过程分析
实例跟数据库的区别 实例(instance)是内存中的一块区域和一组后台进程的集合.它的作用是维护数据库文件的.而数据库(database)则是指存放数据的数据库文件.它是一系列格式化的数据的集合.它 ...
- 一次不是事故的SSH闪断问题
从前一天下午的一个瞬间,公司内所有的ssh 连接在没有任何征兆的情况下,全部开始闪断. 折腾了一天,关闭过SELinux, 清空过Iptables,软硬重启过服务器,交换机,路由,重新配置过sshd文 ...
- 网络请求时 返回 App Transport Security has blocked a cleartext HTTP
如上图,是因为 Xcode7 没有对 plist 进行 http 请求的配置 所致 这时需要 加上上面的plist的红框中 的内容 并且 设置 为 yes 如下图
- 用法总结:NSArray,NSSet,NSDictionary-备用
Foundation framework中用于收集cocoa对象(NSObject对象)的三种集合分别是: NSArray 用于对象有序集合(数组)NSSet 用于对象无序集合 (集合)NS ...
- 转:Qt编写串口通信程序全程图文讲解
转载:http://blog.csdn.net/yafeilinux/article/details/4717706 作者:yafeilinux (说明:我们的编程环境是windows xp下,在Q ...
- Xtrabackup 对MYSQL进行备份还原
在操作MYSQL中注意两个概念: 干什么都记得 flush privileges; grant all on *.* to root@'localhost' identified by 'passwo ...