一、Service(服务)

Service是Android程序中四大基础组件之一,它和Activity一样都是Context的子类,区别在于它没有UI界面,是在后台运行的组件。

public abstract class
Service
extends ContextWrapper
implements ComponentCallbacks java.lang.Object
↳ android.content.Context
↳ android.content.ContextWrapper
↳ android.app.Service

二、Service启动方法+相应的生命周期

Service的生命周期并不是固定的,而是要看启动Service的方式。

而启动Service的方式又分为两种startService和bindService

1、 StartService(启动运行在后台的服务,所谓后台即没有界页;作为四大组件之一,其是运行在主线程中的)

启动时:

Context.startService(intent)-->onCreate()àonStartCommand ()

停止时:

Context_stopService(intent)-->onDestroy()

使用方法:

(1)、创建一个自定义服务类继承Service,实现抽象方法

(2)、清单文件中注册自定义的服务类

(3)、在activity中通过startService和 stopService()

看一个Demo

 package com.example.demo01;

 import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.util.Log;
import android.view.View; public class MainActivity extends Activity {
@Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main); } public void btn_startService(View view)
{
Intent intent = new Intent(this,MyService.class);
intent.putExtra("info", "这里是传送的数据");
startService(intent);
Log.i("activity", "开启服务"); }
public void btn_closeService(View view)
{
Intent intent = new Intent(this,MyService.class);
Log.i("activity", "关闭服务");
stopService(intent);
}
}

MainActivity.class

 package com.example.demo01;

 import android.app.Service;
import android.content.Intent;
import android.os.IBinder;
import android.util.Log; public class MyService extends Service{ @Override
public void onCreate() {
// TODO Auto-generated method stub
super.onCreate();
Log.i("MyService", "--->onCreate"); } @Override
public IBinder onBind(Intent intent) {
// TODO Auto-generated method stub
Log.i("MyService", "--->onBind"); return null;
} @Override
public int onStartCommand(Intent intent, int flags, int startId) {
// TODO Auto-generated method stub
Log.i("MyService", "--->onStartCommand"); String str = intent.getStringExtra("info");
Log.i("MyService", "自定义服务MyService被activity启动并收到了activity发送过来信息:"+str); return super.onStartCommand(intent, flags, startId);
} @Override
public void onDestroy() {
// TODO Auto-generated method stub
super.onDestroy();
Log.i("MyService", "--->onDestroy");
} }

MyService.class自定义服务类

 <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"
> <Button
android:onClick="btn_startService"
android:text="开启服务并发送消息"
android:layout_width="wrap_content"
android:layout_height="wrap_content"> </Button>
<Button
android:onClick="btn_closeService"
android:text="关闭服务"
android:layout_width="wrap_content"
android:layout_height="wrap_content"> </Button>
</LinearLayout>

activity_main.xml 布局文件

清单文件注册自定义的服务类

         <service android:name="com.example.demo01.MyService"></service>

点击两次开启服务按钮,然后点击一次关闭服务按钮,

可见第一次开启服务的时候执行onCreate()服务, 再执行onStartCommand()方法,

当第二次开启服务的时候,则不再执行onCreate()方法,直接执行onStartCommand

当关闭服务的时候,执行onDestroy()方法

2、BindService(基于IBinder方式将两个组件进行绑定,然后相互传值,如果以绑定的方式启动的服务,在解除绑定时也会自动停止服务)

绑定时:

bindService-->onCreate()-->onBind()

解绑时:

unbindService-->onUnbind()-->onDestory()

使用方法:

(1)、创建一个自定义服务类继承Service,实现onBind()方法

(2)、创建Bindler的子类

(3)、在onBind()方法中返回自定义Bindler子类的对象

(4)、清单文件中组册自定义服务

(5)、创建ServiceConnection接口对象,实现 onServiceConnected()方法和 onServiceDisconnected方法

(6)、在activity中绑定bindService和解绑服务unbindService

Demo

 package com.example.demo02;

 import android.app.Service;
import android.content.Intent;
import android.os.Binder;
import android.os.IBinder;
import android.util.Log; public class MyService extends Service{ private MyBinder binder ; @Override
public IBinder onBind(Intent intent) {
// TODO Auto-generated method stub
Log.i("service", "-->onBind");
return new MyBinder();
} @Override
public void onCreate() {
// TODO Auto-generated method stub
Log.i("service", "-->onCreate");
super.onCreate();
} @Override
public int onStartCommand(Intent intent, int flags, int startId) {
// TODO Auto-generated method stub
Log.i("service", "-->onStartCommand");
return super.onStartCommand(intent, flags, startId);
} @Override
public void onDestroy() {
// TODO Auto-generated method stub
Log.i("service", "-->onDestroy");
super.onDestroy();
} class MyBinder extends Binder{
public void function(){
Log.i("service", "Binder-->function"); } } }

MyService.class

 <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"
> <Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="绑定服务"
android:onClick="btn_bindService"
/>
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="解绑服务"
android:onClick="btn_unbindService"
/>
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="执行自定义Binder子类的function方法"
android:onClick="btn_Binder"
/> </LinearLayout>

activity_main.xml 布局文件

清单文件注册:

        <service android:name="com.example.demo02.MyService"></service>

一共三个按钮

当点击“绑定服务”按钮时 执行

当点击“执行自定义Binder子类的function方法”按钮时 执行

当点击“解绑服务”按钮时 执行

BIND_AUTO_CREATE标识表示:绑定的服务组件如果不存,则会自动创建,
由bindService方式启动的Service,其生命周期会受到绑定组件的影响,即当绑定组件Activity销毁时,Service也会停止

安卓开发_浅谈Service的更多相关文章

  1. 安卓开发_浅谈ListView(SimpleAdapter数组适配器)

    安卓开发_浅谈ListView(ArrayAdapter数组适配器) 学习使用ListView组件和SimapleAdapter适配器实现一个带图标的ListView列表 总共3部分 一.MainAc ...

  2. 安卓开发_浅谈Android动画(四)

    Property动画 概念:属性动画,即通过改变对象属性的动画. 特点:属性动画真正改变了一个UI控件,包括其事件触发焦点的位置 一.重要的动画类及属性值: 1.  ValueAnimator 基本属 ...

  3. 安卓开发_浅谈ListView(自定义适配器)

    ListView作为一个实际开发中使用率非常高的视图,一般的系统自带的适配器都无法满足开发中的需求,这时候就需要开发人员来自定义适配器使得ListView能够有一个不错的显示效果 有这样一个Demo ...

  4. 安卓开发_浅谈Fragment之ListFragment

    ListFragment,即Fragment的一个子类,当我们用的一个Fragment只需要一个listview视图的时候使用 该类有几个特点: 1.ListFragment 本身具只有一个ListV ...

  5. 安卓开发_浅谈OptionsMenus(选项菜单)

    Android平台下所提供的菜单大体上可分为三类:选项菜单.上下文菜单和子菜单. 当Activity在前台运行时,如果用户按下手机上的Menu键,此时就会在屏幕低端弹出相应的选项菜单.但这个功能需要开 ...

  6. 安卓开发_浅谈Notification(通知栏)

    Notification通知栏是显示在手机状态的消息,代表一种全局效果的通知 快速创建一个Notification的步骤简单可以分为以下四步: 第一步:通过getSystemService()方法得到 ...

  7. 安卓开发_浅谈ListView之分页列表

    前言: 在开发的过程中,有时候我们需要从网络解析一些数据,比如最近的一些新闻,我们需要把这些数据用ListView显示出来. 因为是解析一个网络数据源,这样将会一下子将所有的数据解析出来,当数据源数据 ...

  8. 安卓开发_浅谈AsyncTask

    现在就来学习一下AsyncTask. 一.先介绍一下AsyncTask: 在开发Android移动客户端的时候往往要使用多线程来进行操作,我们通常会将耗时的操作放在单独的线程执行,避免其占用主线程而给 ...

  9. 安卓开发_浅谈主配置文件(AndroidManifest.xml)

    AndroidManifest.xml本质:是整个应用的主配置清单文件包含:该应用的包名,版本号,组件,权限等信息作用:记录该应用的相关的配置信息 一.常用标签(1).全局篇(包名,版本信息)(2). ...

随机推荐

  1. Version of SQLCE in WP8

    The version on the device is compatible with version 3.5 on the desktop, but the Windows Phone versi ...

  2. 利用SVN工具下载OpenCore代码

    OpenCore原来使用的是CVS管理代码的.从09年起,更换用SVN管理代码,大家可以用TortoiseSVN软件下载代码,网址是:http://tortoisesvn.net/,安装后tortoi ...

  3. Elasticsearch及java客户端jest使用

    本文使用Github中的Elasticsearch-rtf,已经集成了众多的插件,例如必须使用的中文分词等,可以简单的通过配置来启用中文分词.本文主要分为以下几部分: 1.配置和启用中文分词: 2.定 ...

  4. sqlserver -- 学习笔记(四)将一个数据库的表复制到另外一个数据库(备忘)

    --复制结构+数据 select * into 数据库名.dbo.新表名 from 数据库名.dbo.原表名 select * into Stockholder.dbo.SHInfo from dsp ...

  5. 关于4K Block Size的Device和 Aligned IO

    背景:最近采购了一批新的服务器,底层的存储设备的默认physical sector size从原有的 512B 改为了 4K. 装完系统以后,在做数据库物理备份恢复时xtrabackup报了这么一个错 ...

  6. tar的-t参数使用

    -t, --list           list the contents of an archive 例如: pengdl@localhost:~/test$ tar -czvf shell.ta ...

  7. 妹味6:ajax与ajax封装

    (功能)ajax能且仅能 从服务器读取文件 (环境)需要服务器环境才能测试,可以用工具建立本地服务器环境 (缓存)解决缓存问题:url加时间戳让每次请求地址唯一,如 url='abc.txt?t='+ ...

  8. php中mysql操作的buffer知识

    php与mysql的连接有三种方式,mysql,mysqli,pdo.不管使用哪种方式进行连接,都有使用buffer和不使用buffer的区别. 什么叫使用buffer和不使用buffer呢? 客户端 ...

  9. IOS7中自动计算label的宽度和高度的方法

    #import "ViewController.h" @implementation ViewController - (void)viewDidLoad { [super vie ...

  10. android SQLite(安卓数据库的插入显示删除)

    1.利用android自带数据库实现增加.删除.显示用户等操作 只是一个基本模型,为即将的与 复利计算apk整合做牺牲. 就不上传百度云供大家下载了 等整合了复利计算再上传. 数据的插入和显示:   ...