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. php && 逻辑与运算符使用说明

    例子:!defined('MAGIC_QUOTES_GPC') && define('MAGIC_QUOTES_GPC', get_magic_quotes_gpc()); o(︶︿︶ ...

  2. C#☞软件设计模型_基础

    建模图有助于理解.阐明和传达代码的构思和软件系统必须支持的用户需求. 若要描述和传达用户需求,您可以使用统一建模语言 (UML) 用例图.活动图.类图和序列图. 若要描述和传达系统的功能,您可以使用 ...

  3. 使用appium做自动化时如何切换activity

    在使用appium过程中遇到了执行一个用例时有多个不同的acitivity的情况,以下为app内部切换acitivity的方法: 如果仅需要切换一次activity,可以通过设置desired_cap ...

  4. 全是干货---Linux 高可用(HA)集群基本概念详解

    http://www.linuxidc.com/Linux/2013-08/88522.htm 高可用集群的衡量标准    HA(High Available), 高可用性群集是通过系统的可靠性(re ...

  5. keil uVision4一些使用总结(汉字注释,C关键字等)

    近日心血来潮,下载了最新的版的keil,再加上protues ,想弄个虚拟环境.主要原因还是经济问题.电子元件,是要花钱的... 今天遇到些keil uVision 4使用方面的问题,记录下来,方便以 ...

  6. Java实现二叉树的构建与遍历

    转载:http://ocaicai.iteye.com/blog/1047397 目录: 1.把一个数组的值赋值给一颗二叉树 2.具体代码 1.树的构建方法 2.具体代码 package tree; ...

  7. Unity KGFMapSystem插件制作小地图

    KGFMapSystem版本:2.3 在我们开发游戏或者虚拟现实中,一般都会用到小地图,如果要我们去写小地图,可以用到unity 3d中就有一个插件,是专门开发小地图用的,这个插件就是KGFMapSy ...

  8. poj 2503 Babelfish(字典树哈希)

    Time Limit: 3000MS Memory Limit: 65536K Total Submissions: 29059 Accepted: 12565 Description You hav ...

  9. HDU Collect More Jewels 1044

    BFS + 状态压缩 险过 这个并不是最好的算法 但是写起来比较简单 , 可以AC,但是耗时比较多 下面是代码 就不多说了 #include <cstdio> #include <c ...

  10. Final对象

    常量指不能改变的量. 在Java中用final标志,声明方式和变量类似: final double PI = 3.1415927; 虽然常量名也可以用小写,但为了便于识别,通常使用大写字母表示常量. ...