Android Service

  1. 本地服务(Local Service)
  • 应用程序内部
  • startService(启动服务)、stopService(在“启动源”或者 Activity 中停止服务)、stopSelf(在Service停止服务)、stopSelfResult(在Service中停止服务),后面两种都是服务的自我停止。
  • bindService(绑定服务)、unbindService(解绑)
    通过 startService 或者 bindService 都可以启动服务。
  1. 远程服务(Remote Service)
  • Android系统内部的应用程序之间(不是手机之间)
  • 定义 IBinder 接口,通过它,把数据暴露出来,然后把数据提供给启动源或者其他程序。
    远程服务只能通过 IBinder 去启动服务。

我们知道一个Activity是有生命周期的,并且必须在配置文档中进行注册。而Service和Activity是类似的,有类似的生命周期,也必须注册。
继承关系:
Service 继承 ContextWrapper,Activity 继承 ContextThemeWrapper,二者共同拥有一个“祖宗类”——Context。


如图所示是 Service 的两种生命周期(分别以startService和bindService启动)。
Start方式特点:

  • 服务跟启动源没有任何联系
  • 无法得到服务对象
    Bind方式特点:
  • 通过 Ibinder 接口实例,返回一个ServiceConnection对象给启动源
  • 通过 ServiceConnection对象的相关方法可以得到Service对象

BindService: 支持数据回传。
什么时候使用Start?当服务不需要和启动源有任何关联的时候。这样有可能造成的结果:程序都退出了,但Service依然存在,为什么呢?因为二者没有关系。
不过,利用这种特性,也可以做一些特殊的应用,比如:UI不要了,但后台操作仍然继续的例子。但比较麻烦是就是:数据没办法回传了。
所以,既想让它们(服务和启动源)分离,又想得到回传数据,就需要将 Start 和 Bind 混合使用。


首先注册service
然后,
main.xml

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical" >

    <TextView
        android:id="@+id/textView1"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Start:" />

    <Button
        android:id="@+id/start"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:onClick="doClick"
        android:text="StartService" />

    <Button
        android:id="@+id/stop"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:onClick="doClick"
        android:text="StopService" />

    <TextView
        android:id="@+id/textView2"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Bind:" />

    <Button
        android:id="@+id/bind"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:onClick="doClick"
        android:text="BindService" />

    <Button
        android:id="@+id/play"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:onClick="doClick"
        android:text="播放" />

    <Button
        android:id="@+id/pause"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:onClick="doClick"
        android:text="暂停" />

    <Button
        android:id="@+id/next"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:onClick="doClick"
        android:text="下一首" />

    <Button
        android:id="@+id/pervious"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:onClick="doClick"
        android:text="上一首" />

    <Button
        android:id="@+id/unbind"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:onClick="doClick"
        android:text="UnBindService" />

</LinearLayout>

MainActivity.java

import com.example.servicedemo.MyBindService.MyBinder;

import android.app.Activity;
import android.app.Service;
import android.content.ComponentName;
import android.content.Intent;
import android.content.ServiceConnection;
import android.os.Bundle;
import android.os.IBinder;
import android.view.Menu;
import android.view.View;

public class MainActivity extends Activity {
    Intent intent1;
    Intent intent2;
    MyBindService service;
    ServiceConnection conn = new ServiceConnection() {
        
        @Override//当服务跟启动源断开的时候 会自动回调
        public void onServiceDisconnected(ComponentName name) {
            // TODO Auto-generated method stub
            
        }
        
        @Override//当服务跟启动源连接的时候 会自动回调
        public void onServiceConnected(ComponentName name, IBinder binder) {
            // TODO Auto-generated method stub
            service = ((MyBinder)binder).getService();
        }
    };
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
    }
    public void doClick(View v){
        switch (v.getId()) {
        case R.id.start:
             intent1 =  new Intent(MainActivity.this, MyStartService.class);
            startService(intent1);
            break;

        case R.id.stop:
            stopService(intent1);
            break;
        case R.id.play:
            service.Play();
            break;
        case R.id.pause:
            service.Pause();
            break;
        case R.id.pervious:
            service.Pervious();
            break;
        case R.id.next:
            service.next();
            break;
        case R.id.bind:
            intent2 = new Intent(MainActivity.this, MyBindService.class);
            startService(intent2);
            bindService(intent2, conn, Service.BIND_AUTO_CREATE);
            break;
        case R.id.unbind:
            unbindService(conn);
            break;
        }
    }
    @Override
    protected void onDestroy() {
        // TODO Auto-generated method stub
        stopService(intent2);
        unbindService(conn);
        super.onDestroy();
    }
    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        // Inflate the menu; this adds items to the action bar if it is present.
        getMenuInflater().inflate(R.menu.main, menu);
        return true;
    }

}

MyStartService.java

import android.app.Service;
import android.content.Intent;
import android.os.IBinder;
import android.util.Log;

public class MyStartService extends Service {
    @Override
    public void onCreate() {
        // TODO Auto-generated method stub
        Log.i("info", "Service--onCreate()");
        super.onCreate();
    }

    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {
        // TODO Auto-generated method stub
        Log.i("info", "Service--onStartCommand()");
        return super.onStartCommand(intent, flags, startId);
    }

    @Override
    public void onDestroy() {
        // TODO Auto-generated method stub
        Log.i("info", "Service--onDestroy()");
        super.onDestroy();
    }

    @Override
    public IBinder onBind(Intent intent) {
        // TODO Auto-generated method stub
        Log.i("info", "Service--onBind()");
        return null;
    }

}

MyBindService.java

import android.app.Service;
import android.content.Intent;
import android.content.ServiceConnection;
import android.os.Binder;
import android.os.IBinder;
import android.util.Log;

public class MyBindService extends Service{
    @Override
    public void onCreate() {
        // TODO Auto-generated method stub
        Log.i("info", "BindService--onCreate()");
        super.onCreate();
    }
    public class MyBinder extends Binder{
        public MyBindService getService(){
            return MyBindService.this;
        }
    }
    @Override
    public IBinder onBind(Intent intent) {
        // TODO Auto-generated method stub
        Log.i("info", "BindService--onBind()");
        return new MyBinder();
    }
    @Override
    public void unbindService(ServiceConnection conn) {
        // TODO Auto-generated method stub
        Log.i("info", "BindService--unbindService()");
        super.unbindService(conn);
    }
    @Override
    public void onDestroy() {
        // TODO Auto-generated method stub
        Log.i("info", "BindService--onDestroy()");
        super.onDestroy();
    }
    public void Play(){
        Log.i("info", "播放");
    }
    public void Pause(){
        Log.i("info", "暂停");
    }
    public void Pervious(){
        Log.i("info", "上一首");
    }
    public void next(){
        Log.i("info", "下一首");
    }
}

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
  • 序言:七十年代末,一起剥皮案震惊了整个滨河市,随后出现的几起案子,更是在滨河造成了极大的恐慌,老刑警刘岩,带你破解...
    沈念sama阅读 217,657评论 6 505
  • 序言:滨河连续发生了三起死亡事件,死亡现场离奇诡异,居然都是意外死亡,警方通过查阅死者的电脑和手机,发现死者居然都...
    沈念sama阅读 92,889评论 3 394
  • 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
    开封第一讲书人阅读 164,057评论 0 354
  • 文/不坏的土叔 我叫张陵,是天一观的道长。 经常有香客问我,道长,这世上最难降的妖魔是什么? 我笑而不...
    开封第一讲书人阅读 58,509评论 1 293
  • 正文 为了忘掉前任,我火速办了婚礼,结果婚礼上,老公的妹妹穿的比我还像新娘。我一直安慰自己,他们只是感情好,可当我...
    茶点故事阅读 67,562评论 6 392
  • 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
    开封第一讲书人阅读 51,443评论 1 302
  • 那天,我揣着相机与录音,去河边找鬼。 笑死,一个胖子当着我的面吹牛,可吹牛的内容都是我干的。 我是一名探鬼主播,决...
    沈念sama阅读 40,251评论 3 418
  • 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
    开封第一讲书人阅读 39,129评论 0 276
  • 序言:老挝万荣一对情侣失踪,失踪者是张志新(化名)和其女友刘颖,没想到半个月后,有当地人在树林里发现了一具尸体,经...
    沈念sama阅读 45,561评论 1 314
  • 正文 独居荒郊野岭守林人离奇死亡,尸身上长有42处带血的脓包…… 初始之章·张勋 以下内容为张勋视角 年9月15日...
    茶点故事阅读 37,779评论 3 335
  • 正文 我和宋清朗相恋三年,在试婚纱的时候发现自己被绿了。 大学时的朋友给我发了我未婚夫和他白月光在一起吃饭的照片。...
    茶点故事阅读 39,902评论 1 348
  • 序言:一个原本活蹦乱跳的男人离奇死亡,死状恐怖,灵堂内的尸体忽然破棺而出,到底是诈尸还是另有隐情,我是刑警宁泽,带...
    沈念sama阅读 35,621评论 5 345
  • 正文 年R本政府宣布,位于F岛的核电站,受9级特大地震影响,放射性物质发生泄漏。R本人自食恶果不足惜,却给世界环境...
    茶点故事阅读 41,220评论 3 328
  • 文/蒙蒙 一、第九天 我趴在偏房一处隐蔽的房顶上张望。 院中可真热闹,春花似锦、人声如沸。这庄子的主人今日做“春日...
    开封第一讲书人阅读 31,838评论 0 22
  • 文/苍兰香墨 我抬头看了看天上的太阳。三九已至,却和暖如春,着一层夹袄步出监牢的瞬间,已是汗流浃背。 一阵脚步声响...
    开封第一讲书人阅读 32,971评论 1 269
  • 我被黑心中介骗来泰国打工, 没想到刚下飞机就差点儿被人妖公主榨干…… 1. 我叫王不留,地道东北人。 一个月前我还...
    沈念sama阅读 48,025评论 2 370
  • 正文 我出身青楼,却偏偏与公主长得像,于是被迫代替她去往敌国和亲。 传闻我的和亲对象是个残疾皇子,可洞房花烛夜当晚...
    茶点故事阅读 44,843评论 2 354

推荐阅读更多精彩内容

  • 1.Service简介 服务是一个应用程序组件,可以在后台执行长时间运行的操作,不提供用户界面。一个应用程序组件可...
    紫豪阅读 21,941评论 11 83
  • 第一种方式:通过StartService启动Service 通过startService启动后,service会一...
    Big不吃鱼阅读 118,215评论 8 94
  • 前言:本文所写的是博主的个人见解,如有错误或者不恰当之处,欢迎私信博主,加以改正!原文链接,demo链接 Serv...
    PassersHowe阅读 1,413评论 0 5
  • 参考:Android Service完全解析,关于服务你所需知道的一切(上)Android Service完全解析...
    zeo朱子宥阅读 456评论 0 1
  • 再次触及你青石铺就的肌肤 你所有的温柔依旧 白墙青瓦 偶露在额头的岁月 月下小桥 雨中斜巷 弥漫在心灵深处的妩媚 ...
    纳兰胡杨o阅读 112评论 0 1