开门见山

开启服务有三种情况:假设直接使用服务,则没有必要进行绑定,可是假设要使用服务里面的方法。则要进行绑定。

具体的启动情况有下:
①调用startService()。再调用stopService()
②单独调用bindService()方法,再unbindService()后,以运行服务内部的方法。
③先调用startService(),再调用bindService()方法,再调用unbindService()。最后调用stopService()

特殊情况:
仅仅要使用了bindService,无论之后是否解绑和停止服务,都能够调用服务中的方法

以下针对这三种启动顺序分别做具体说明。

在解说之前先贴一下代码:

MyService类。里面就不加凝视了

public class MyService extends Service {

    @Override
public IBinder onBind(Intent intent) {
return new MyBinder();
} @Override
public void onCreate() {
System.out.println("MyService onCreate():Called by the system when the service is first created");
super.onCreate();
} @Override
public boolean onUnbind(Intent intent) {
System.out.println("MyService onUnbind():Called when all clients have disconnected from a particular interface published by the service.");
return super.onUnbind(intent);
} @Override
public int onStartCommand(Intent intent, int flags, int startId) {
System.out.println("MyService onStartCommand():Called by the system every time a client explicitly starts the service by calling android.content.Context.startService, providing the arguments it supplied and a unique integer token representing the start request.");
return super.onStartCommand(intent, flags, startId);
} @Override
public void onDestroy() {
System.out.println("MyService onDestroy():Called by the system to notify a Service that it is no longer used and is being removed. ");
super.onDestroy();
} public void method1() {
System.out.println("MyService is method1");
} public void method2() {
System.out.println("MyService is method2");
} class MyBinder extends Binder { public void callMethod1() {
method1();
} public void callMethod2() {
method2();
}
}
}

MainActivity类

public class MainActivity extends Activity {
private MyBinder myBinder; @Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
conn = new MyServiceConnection();
} ServiceConnection conn; public void start(View v) {
Intent service = new Intent(this, MyService.class);
startService(service);
} public void bind(View v) {
Intent service = new Intent(this, MyService.class);
bindService(service, conn, Context.BIND_AUTO_CREATE);
} public void unbind(View v) {
unbindService(conn);
} public void stop(View v) {
Intent service = new Intent(this, MyService.class);
stopService(service);
} public void callmethod1(View v) {
myBinder.callMethod1();
} private class MyServiceConnection implements ServiceConnection { @Override
public void onServiceConnected(ComponentName name, IBinder service) {
System.out.println("MyServiceConnection connection success");
myBinder = (MyBinder) service;
} @Override
public void onServiceDisconnected(ComponentName name) {
System.out.println("MyServiceConnection disconnection success");
}
}
}

activity_main.xml页面布局

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
tools:context=".MainActivity" > <Button
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:onClick="start"
android:text="startService" /> <Button
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:onClick="bind"
android:text="bindService" /> <Button
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:onClick="unbind"
android:text="unbindService" /> <Button
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:onClick="stop"
android:text="stopService" /> <Button
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:onClick="callmethod1"
android:text="call Method1" /> </LinearLayout>

第一种

调用startService(),再调用stopService()。这样的情况适用于直接使用Service。不须要外部调用服务内部的方法。

在这一种中,我们分别会点击startService和stopService。在类MyService中,会以onCreate()開始 — 代表第一次创建服务;以onDestory()结束 — 代表服务被销毁。中间会一次或者多次调用(当重复startService时)onStartCommand()方法 — 来表示客户端想明白的启动服务。

当点击startService时,会触发onCreate()onStartCommand()方法。表示服务是第一次创建而且是客户端明白要求的。

这两个方法运行完成后。后台的服务线程启动。

看一下这张图:



这个过程相应的Log图和应用后台服务进程图例如以下:

能够清楚的看到。调用了onCreate()onStartCommand()方法,同一时候后台的服务进程也已经启动。

当点击stopService时,会触发onDesctory(),此时会去销毁后台服务进程。

看一下这张图:



这个过程相应的Log图和应用后台服务进程图例如以下:

能够清楚的看到,调用onDesctory()方法。同一时候后台服务线程也被销毁了。

另外一种

单独调用bindService()方法将Activity和Service绑定,以达到服务内部方法的目的。再调用unbindService()解绑。

在这一种中,我们分别会点击bindService和unbindService,在类MyService中,会以onCreate()開始 — 代表第一次创建服务;以onDestory()结束 — 代表服务被销毁;在中间。当绑定成功时,会调用onServiceConnected()表明Activity和Service连接成功;当解除绑定时,会调用onUnbind()表明Activity和Service解除连接成功。

当点击bindService时,会触发onCreate()onServiceConnected()方法。以达到调用服务内部方法的目的。可是。请注意后台服务进程并没有启动

看一下这张图:



这个过程相应的Log图和应用后台服务进程图例如以下:

能够清楚的看到,调用了onCreate()onServiceConnected()方法,可是。后台的服务进程却没有启动

绑定后就能够调用服务内部的方法了。而MyService is method1就是证明。

当点击unbindService时,会触发onUnbind()onDestory()方法表明解除绑定和销毁服务。

看一下这张图:



这个过程相应的Log图和应用后台服务进程图例如以下:

能够清楚的看到,调用onUnbind()onDesctory()方法,后台也没有服务线程。可是,尽管解除了绑定,我们却依然能够调用服务中的方法。

第三种

先调用startService()。再调用bindService()方法,再调用unbindService(),最后调用stopService(),这样的情况适用于希望服务能够在后台长期运行。仅仅要不stopService就不停止,也能够让Activity调用服务中的方法。

当着四种组合使用时。请依照下图的方式点击调用:

我们能够看到,运行方法的顺序是一级一级的。当上一级没有触发时,是无法进入到下一级的。

当点击完startService和bindService时,Log和后台进程图例如以下所看到的:



能够看到。后台进程启动,而且Activity和Service绑定成功。且能够调用后台的方法。

当点击完unbindService时,会运行onUnbind()方法解除绑定,Log和后台进程图例如以下:



能够看到,尽管解除绑定了,可是服务没有销毁,服务中的内容依然能够被调用。

当点击完stopService时,服务被销毁onDestory()方法被运行,Log和后台进程图例如以下:



能够看到,后台的服务已经被销毁了,可是。重点中的重点,服务中的方法依然能够被调用。

总结

开启服务有三种情况:假设直接使用服务,则没有必要进行绑定,可是假设要使用服务里面的方法,则要进行绑定。

另外,仅仅要使用了bindService,无论之后是否解绑和停止服务,都能够调用服务中的方法

版权声明:本文博主原创文章,博客,未经同意不得转载。

Android基调(十六)- Service:startService()、stopService()、bindService()、unbindService()加的更多相关文章

  1. Android进阶(十六)子线程调用Toast报Can't create handler inside thread that has not called Looper.prepare() 错误

    原子线程调用Toast报Can't create handler inside thread that has not called Looper.prepare() 错误 今天用子线程调Toast报 ...

  2. Android入门(十六)调用摄像头相册

    原文链接:http://www.orlion.ga/665/ 一.调用摄像头 创建一个项目ChoosePicDemo,修改activity_main.xml: <LinearLayout xml ...

  3. Android之旅七 Service简介

    1.          Service是什么:它是一个应用程序组件.没有图形化界面.通常用来处理一些耗时比较长的操作(例如下载.播放MP3等等).可以使用Service更新ContentProvide ...

  4. [Android Pro] Service (startservice , bindservice , unbindservice, stopService)

    1: startService -------stopService (this will call onDestroy) 2: bindService -------unbindService    ...

  5. 深入理解Android的startservice和bindservice

    一.首先,让我们确认下什么是service?         service就是android系统中的服务,它有这么几个特点:它无法与用户直接进行交互.它必须由用户或者其他程序显式的启动.它的优先级比 ...

  6. 理解Android的startservice和bindservice(转)

    一.首先,让我们确认下什么是service? service就是android系统中的服务,它有这么几个特点:它无法与用户直接进行交互.它必须由用户或者其他程序显式的启动.它的优先级比较高,它比处于前 ...

  7. 初学Android,创建,启动,停止Service(五十八)

    Service跟Windows系统里的服务概念差不多,都在后台执行,它跟Activity的最大区别就是,它是无界面的 开发Service与开发Activity的步骤类似 1.定义一个继承Service ...

  8. Android多媒体学习六:利用Service实现背景音乐的播放

    Android同意我们使用Service组件来完毕后台任务.这些任务的同意不会影响到用户其它的交互. 1.Activity类 [java] view plaincopy package demo.ca ...

  9. Android实现简单音乐播放器(startService和bindService后台运行程序)

    Android实现简单音乐播放器(MediaPlayer) 开发工具:Andorid Studio 1.3运行环境:Android 4.4 KitKat 工程内容 实现一个简单的音乐播放器,要求功能有 ...

随机推荐

  1. zoj 1083 Frame Stacking

    其实就是一个拓补排序.(动态记录第i个之上的j存不存在,反过来就是第j个之下的i) 首先确立每个框的位置(题目明确说了每一边都不会被完全覆盖)./*可以通过搜索,搜索到该框的所有四个角*/||如果题目 ...

  2. 利用 squid 反向代理提高网站性能

    http://www.ibm.com/developerworks/cn/linux/l-cn-squid/ http://www.squid-cache.org/ http://www.beijin ...

  3. C++中 指针 与 引用 的区别

    四点区别:可否为空,可否修改,使用时是否需要判断,使用场景 非空区别. 引用必须指向某个对象,而指针可以指向空. 可修改区别. 引用总是与初始化时的那个对象绑定,不可变更:指针可以重新赋值,指向另外一 ...

  4. BZOJ 3931: [CQOI2015]网络吞吐量( 最短路 + 最大流 )

    最短路 + 最大流 , 没什么好说的... 因为long long WA 了两次.... ------------------------------------------------------- ...

  5. FOREIGN KEY相关

    在添加外键的时候可以在最后通过ON指定行为和三个参数,来表示操作主表数据之后外表的变化 比如若是删除主表之后的变化,就可以 ON DELETE + 三个参数 --删除department表中相关数据行 ...

  6. python自定义排序函数

    Python内置的 sorted()函数可对list进行排序: >>>sorted([36, 5, 12, 9, 21]) [5, 9, 12, 21, 36] 但 sorted() ...

  7. python 以面向对象的方式创建线程 实现售票系统

    ---恢复内容开始--- 转载或借鉴请注明转自http://www.cnblogs.com/FG123/p/5068556.html   谢谢! 通过面向对象的方法实现多线程,其核心是继承thread ...

  8. [转] iOS多线程编程之Grand Central Dispatch(GCD)介绍和使用

    介绍: Grand Central Dispatch 简称(GCD)是苹果公司开发的技术,以优化的应用程序支持多核心处理器和其他的对称多处理系统的系统.这建立在任务并行执行的线程池模式的基础上的.它首 ...

  9. 解决用户 'IIS APPPOOL\Classic .NET AppPool' 登录失败

    解决用户 'IIS APPPOOL\Classic .NET AppPool' 登录失败 windows 7进入iis管理器 本地应用程序池 选中classic. net appPool 选择右侧的 ...

  10. Hbuilder 常用快捷键汇总

    朋友推荐用Hbuilder编辑器,看了下Hbuilder官网和那视频,感觉牛逼哄哄的, 自己也就体验了一下,打开Hbuilder的快捷键列表,每个快捷键都体验了一下,以下展示出来的,每一个都是精华,每 ...