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. .net 实例化对象

    定义TestClass,在调用的地方 TestClass a; 如果下面有引用 a.Property,VS会报错,而如果 TestClass a = null; 再次调用的话则不会报错. TestCl ...

  2. 简单学C——第一天

    基本功 一.数据类型: 在C语言中,有数据类型这一说法.为何有这一说法?是因为在现实生活中存在着不同的数据,(例如整数,小数,字符即a b c d , . ; "  之类).由于计算机中所有 ...

  3. ural1057Amount of Degrees

    Description Create a code to determine the amount of integers, lying in the set [ X; Y] and being a ...

  4. AdminLTE

    AdminLTE搭建前端   0 Asp.Net Core 项目实战之权限管理系统(0) 无中生有 1 Asp.Net Core 项目实战之权限管理系统(1) 使用AdminLTE搭建前端 2 Asp ...

  5. 实现OC与JS的交互

        oc-->js stringByEvaluatingJavaScriptFromString,其参数是一NSString 字符串内容是js代码(这又可以是一个js函数.一句js代码或他们 ...

  6. BZOJ 1296 粉刷匠

    Description windy有\(N\)条木板需要被粉刷.每条木板被分为\(M\)个格子. 每个格子要被刷成红色或蓝色. windy每次粉刷,只能选择一条木板上一段连续的格子,然后涂上一种颜色. ...

  7. 在SystemOut.log中发现HMGR0152W: 检测到CPU 饥饿的消息 <转载>

    今天系统报警了!!!!!顿时人又不好了!!!查看系统日志, 报错如下: Did not receive adequate CPU time slice. Last known CPU usage ti ...

  8. 工程师必知ZigBee技术问答精华汇总

    本文是关于ZigBee技术的一些基础知识.行业应用方面的精华汇总.希望通过本文的分析,能让大家对ZigBee技术的起源.发展.特点.前景及其在通信网络中的相关应用有全面直观的了解. 1.基础知识篇 Q ...

  9. div大小如何改变设置

    如果改变更改div大小尺寸. 首先我们要知道DIV大小是由高和宽确定,要修改DIV容积大小我们设置css宽度和css高度即可实现改变DIV盒子大小. 一.改变div大小实例 为了实验便于观察DIV盒子 ...

  10. 【调侃】IOC前世今生(转)

    前些天,参与了公司内部小组的一次技术交流,主要是针对<IOC与AOP>,本着学而时习之的态度及积极分享的精神,我就结合一个小故事来初浅地剖析一下我眼中的“IOC前世今生”,以方便初学者能更 ...