1. 前面我们已经讲过可以使用两种方式开启服务

startService----stopService:

       oncreate() ---> onstartCommand() ---> onstartCommand()---> onDestory();

bindService----unbindService:

       oncreate() ---> onbind() --->onUnbind() ---> onDestory();

为什么需要采用混合的方式开启服务?

答:startService服务长期后天运行,不可以调用服务里面的方式;

bindService可以调用服务的方法,但是不能长期在后台运行。(bindService和Activity同时死)

综合上面两种方式的优点,采用混合的方式开启服务(继承了上面两种的优点):

(1)服务长期后台运行。

(2)可以调用服务的方法。

2.利用案例说明混合方式开启服务:

(1)创建一个Android项目如下:

(2)我们首先看看布局文件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:orientation="vertical"
android:layout_height="match_parent"
tools:context=".MainActivity" > <Button
android:onClick="start"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="开启服务" />
<Button
android:onClick="stop"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="停止服务" />
<Button
android:onClick="bind"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="绑定服务" />
<Button
android:onClick="unbind"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="解除绑定服务" />
<Button
android:onClick="call"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="调用服务的方法" /> </LinearLayout>

布局效果如下:

(3)其中MainActivity.java:

 package com.itheima.mix;

 import android.app.Activity;
import android.content.ComponentName;
import android.content.Intent;
import android.content.ServiceConnection;
import android.os.Bundle;
import android.os.IBinder;
import android.view.View; public class MainActivity extends Activity {
private MyConn conn;
private IService iService; @Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
//以start的方式i开启服务
public void start(View view){
Intent intent = new Intent(this,TestService.class);
startService(intent);
}
//停止服务
public void stop(View view){
Intent intent = new Intent(this,TestService.class);
stopService(intent);
}
//绑定服务u
public void bind(View view){
Intent intent = new Intent(this,TestService.class);
conn = new MyConn();
bindService(intent, conn, BIND_AUTO_CREATE);
}
private class MyConn implements ServiceConnection{
@Override
public void onServiceConnected(ComponentName name, IBinder service) {
iService = (IService) service;
} @Override
public void onServiceDisconnected(ComponentName name) { } }
//解绑服务
public void unbind(View view){
unbindService(conn);
} public void call (View view){
iService.callMethodInService();
} }

其中使用到的Service为自定义的TestService,如下:

 package com.itheima.mix;

 import android.app.Service;
import android.content.Intent;
import android.os.Binder;
import android.os.IBinder;
import android.widget.Toast; public class TestService extends Service { private class MyBinder extends Binder implements IService{
@Override
public void callMethodInService() {
methodInService();
}
} @Override
public IBinder onBind(Intent intent) {
System.out.println("服务被绑定 onBind");
return new MyBinder();
}
@Override
public boolean onUnbind(Intent intent) {
System.out.println("服务被解绑 onUnbind");
return super.onUnbind(intent);
} @Override
public void onCreate() {
System.out.println("服务被创建 oncreate");
super.onCreate();
}
@Override
public int onStartCommand(Intent intent, int flags, int startId) {
System.out.println("onStartCommand");
return super.onStartCommand(intent, flags, startId);
} @Override
public void onDestroy() {
System.out.println("服务被销毁 onDestroy");
super.onDestroy();
} public void methodInService(){
Toast.makeText(this, "我是服务里面的方法", 0).show();
}
}

还有上面使用到的接口IService,如下:

package com.itheima.mix;

public interface IService {
public void callMethodInService();
}

既然上面使用到了自定义的service的TestService,所以要在AndroidMainfest.xml注册TestService这个组件,如下:

 <?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.itheima.mix"
android:versionCode="1"
android:versionName="1.0" > <uses-sdk
android:minSdkVersion="8"
android:targetSdkVersion="17" /> <application
android:allowBackup="true"
android:icon="@drawable/ic_launcher"
android:label="@string/app_name"
android:theme="@style/AppTheme" >
<activity
android:name="com.itheima.mix.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="com.itheima.mix.TestService"></service>
</application> </manifest>

3. 特别注意:

混合模式开启服务  

推荐使用的步骤:

                   (1)startService()        ----> 保证服务长期后天运行

                   (2)如果要调用服务的方法  ---->bindService()绑定服务

                   (3)就可以调用服务的方法

                   (4)unbindservice    解绑服务

                   (5)服务还是长期后台运行

                   (6)如果要停止服务,stopService();

Android(java)学习笔记231:服务(service)之混合方式开启服务的更多相关文章

  1. Android(java)学习笔记174:服务(service)之混合方式开启服务

    1. 前面我们已经讲过可以使用两种方式开启服务 startService----stopService:        oncreate() ---> onstartCommand() ---& ...

  2. 《Java学习笔记(第8版)》学习指导

    <Java学习笔记(第8版)>学习指导 目录 图书简况 学习指导 第一章 Java平台概论 第二章 从JDK到IDE 第三章 基础语法 第四章 认识对象 第五章 对象封装 第六章 继承与多 ...

  3. Java学习笔记4

    Java学习笔记4 1. JDK.JRE和JVM分别是什么,区别是什么? 答: ①.JDK 是整个Java的核心,包括了Java运行环境.Java工具和Java基础类库. ②.JRE(Java Run ...

  4. 20155234 2016-2017-2第十周《Java学习笔记》学习总结

    20155234第十周<Java学习笔记>学习总结 教材学习内容总结 网络编程 在两个或两个以上的设备(例如计算机)之间传输数据.程序员所作的事情就是把数据发送到指定的位置,或者接收到指定 ...

  5. Android:日常学习笔记(2)——分析第一个Android应用程序

    Android:日常学习笔记(2)——分析第一个Android应用程序 Android项目结构 整体目录结构分析 说明: 除了APP目录外,其他目录都是自动生成的.APP目录的下的内容才是我们的工作重 ...

  6. java学习笔记之基础篇

    java选择语句之switch   //switch可以用于等值判断 switch (e) //int ,或则可以自动转化成int 的类型,(byte char short)枚举jdk 7中可以防止字 ...

  7. Android Studio 学习笔记(一)环境搭建、文件目录等相关说明

    Android Studio 学习笔记(一)环境搭建.文件目录等相关说明 引入 对APP开发而言,Android和iOS是两大主流开发平台,其中区别在于 Android用java语言,用Android ...

  8. 0028 Java学习笔记-面向对象-Lambda表达式

    匿名内部类与Lambda表达式示例 下面代码来源于:0027 Java学习笔记-面向对象-(非静态.静态.局部.匿名)内部类 package testpack; public class Test1{ ...

  9. Android自动化学习笔记:编写MonkeyRunner脚本的几种方式

    ---------------------------------------------------------------------------------------------------- ...

随机推荐

  1. opencv数据结构总结

    OpenCV里面用到了很多图像相关的数据结构,熟练掌握它们是学习图像的基础. 1.IplImage IplImage IplImage IPL 图像头 typedef struct _IplImage ...

  2. CentOS 6.3 卷组挂载硬盘教程 linux的VPS如何分区

    XEN架构VPS提供的容量一般都不会低于10G,但大部分基于Xensystem面板的VPS默认挂载10G硬盘(第一磁盘),剩下的容量(第二磁盘)就需要通过手动挂载才能扩充默认的10G容量了.默认装完系 ...

  3. I题 - A+B for Input-Output Practice (VIII)

      Time Limit:1000MS     Memory Limit:32768KB     64bit IO Format:%I64d & %I64u   Description You ...

  4. yii2 日志(log)的配置与使用

    原文地址: http://blog.csdn.net/gao_yu_long/article/details/51732181

  5. iOS类别(Category)与扩展(Extension)-b

    苹果的官方文档 Category在iOS开发中使用非常频繁.尤其是在为系统类进行拓展的时候,我们可以不用继承系统类,直接给系统类添加方法,最大程度的体现了Objective-C的动态语言特性. #im ...

  6. Android 安装过程中的问题

    Android  安装过程中的问题 上一篇我说到配置android环境,但是在具体的安装过程中,因为下载的软件或者方法不同,导致没有正确的结果,如果有一些错误的时候,可以试一试关闭eclipse软件, ...

  7. exceptions.IOError: decoder jpeg not available

    1.确保安装PIL所需的系统库 yum -y install zlib yum -y install  zlib-devel yum -y install libjpeg yum -y install ...

  8. IBM Websphere 说明文档

    http://pic.dhe.ibm.com/infocenter/wasinfo/v6r1/index.jsp?topic=%2Fcom.ibm.websphere.nd.doc%2Finfo%2F ...

  9. libevent带负载均衡的多线程使用示例

    功能: 主线程根据负载工作线程负载均衡算法,每隔一秒钟向特定的工作线程发送一条字符串信息,工作线程简单的把字符串信息打开出来.   Makefile   eventtest : eventtest.c ...

  10. sql server更改机器名后更改数据库机器名

    方式一: 本地机器名查询: select * from sys.servers 修改机器名: sp_dropserver 'old server name' sp_addserver 'new ser ...