Service的生命周期与开启Activity的通信

一、Android的五个进程:

  1. ActivityProcess: 前台进程,Activity
  • VisibleProcess:可见进程,进程拥有暂停状态的Activity
  • StartedServiceProcess:服务进程,包含正在运行的Service
  • BackgroundProcess:后台进行,处于停止状态的Activity
  • EmptyProcess:被关闭的Activity:空进程,系统会保留启动Activity信息,残留信息;

二、启动Serivice的生命周期:

onCreate()-->onStartCommand()-->onStart()(2.0以后已经被onStartCommand()的代替)-->onDestroy()

效果图:
启动service的生命周期.jpg

三、绑定Service的生命周期:

onCreate()-->onBind()-->onUnBind()-->onDestroy()

效果图:
绑定service生命周期.jpg

四、启动绑定service生命周期:

1、先启动service,再 绑定service,再解绑service

onCreate()-->onStartCommand()-->onBind()-->onUnbind()

效果图:
先启动再绑定最后解绑.jpg
2、将启动的service,绑定之后,如果想销毁service,必须先解绑才能停止service

onCreate()-->onStartCommand-->onBind()-->onUnbind-->onDestroy()

效果图:
销毁先启动再绑定的Service.jpg
3、先启动,再绑定,解绑,再次绑定,将onUnbind()方法返回true,才能执行onRebind()方法
@Override
    public boolean onUnbind(Intent intent) {
        Log.i("dayang","-------------onUnbind---------------");
        return true;
    }

onCreate()-->onStartCommand()-->onBind()-->onUnbind()-->onRebind()-->onUnbind()-->onDestroy()

效果图:
解绑之后再次绑定.jpg

五、Activity与绑定的Service的通信:

通过ServiceConnection接口和IBinder接口实现通信;

  • 在Activity中绑定Service时,会创建ServiceConnection接口对象,重写onServiceConnected()方法,该方法有Service绑定成功时onBind()方法返回的IBinder接口对象;
  • 在Service的执行的onBind()方法返回IBinder接口对象;

对于Ibinder接口Android给出了实现类Binder,我们只需要继承这个Binder类,就可以实现IBinder接口并写自己的逻辑代码

Activity 通过ServiceConnection接口取得与之绑定Service返回的IBinder接口对象

MyService的代码
public class MyService extends Service {
    public class MyBinder extends Binder{
        int count=0;

        public int getCount() {
            return ++count;
        }
    }
    public MyService() {
    }
    @Override
    public IBinder onBind(Intent intent) {
        Log.i("dayang","-------------onBind-----------------");
        return new MyBinder();
    }
    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {
        Log.i("dayang","-------------onStartCommand---------------");
        return super.onStartCommand(intent, flags, startId);
    }
    @Override
    public void onStart(Intent intent, int startId) {
        super.onStart(intent, startId);
    }
    @Override
    public void onRebind(Intent intent) {
        super.onRebind(intent);
        Log.i("dayang","-------------onRebind---------------");
    }
    @Override
    public boolean onUnbind(Intent intent) {
        Log.i("dayang","-------------onUnbind---------------");
        return true;
    }
    @Override
    public void onCreate() {
        super.onCreate();
        Log.i("dayang","-------------onCreate---------------");
    }
    @Override
    public void onDestroy() {
        super.onDestroy();
        Log.i("dayang","-------------onDestroy---------------");
    }
}
绑定MyService的Actvity的代码
public class MainActivity extends AppCompatActivity {
    MyService.MyBinder myBinder=null;
    ServiceConnection mConn=new ServiceConnection() {
        @Override
        public void onServiceConnected(ComponentName componentName, IBinder iBinder) {
            myBinder= (MyService.MyBinder) iBinder;
        }

        @Override
        public void onServiceDisconnected(ComponentName componentName) {

        }
    };
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
    }
    public void startActivity(View view){
        Intent intent=new Intent(this,MyService.class);
        startService(intent);
    }
    public void stopActivity(View view){
        Intent intent=new Intent(this,MyService.class);
        stopService(intent);
    }
    public void bindService(View view){
        if(myBinder==null){
            Intent intent=new Intent(this,MyService.class);
            bindService(intent,mConn, Context.BIND_AUTO_CREATE);
        }else{
            Log.i("dayang",myBinder.getCount()+"得到次数-----");
        }
    }
    public void unBindSerivce(View view){
        Intent intent=new Intent(this,MyService.class);
        unbindService(mConn);
    }
}

绑定MyService的Actvity的布局文件
<?xml version="1.0" encoding="utf-8"?>
<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"
    tools:context="cn.ucai.day17_12_20_service.MainActivity">
    <Button
        android:onClick="startActivity"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="startActivty" />
    <Button
        android:onClick="stopActivity"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="stopActivity"
        />
    <Button
        android:onClick="bindService"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="bindService"
        />
    <Button
        android:onClick="unBindSerivce"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="unBindService"
        />
</LinearLayout>

六、在Service中启动Activity

因为Service运行时没有任务栈,要为开启的Activity指定一个新的任务栈:

1、在Activity中,启动一个Service并发送消息
Intent intent=new Intent(this,MyService.class);
intent.putExtra("flag",true);
startService(intent);
2、启动Service之后,执行onStartCommand(),在该方法开启一个新的Activity

给新的Activity一个任务栈

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

推荐阅读更多精彩内容

  • 概述 Service是一个可以在后台执行长时间运行操作而不使用用户界面的应用组件。 服务可由其他应用组件启动,且即...
    daking阅读 4,464评论 0 12
  • Service是Android四大组件中与Activity最相似的组件,他们都代表可执行的程序,Service与A...
    AndYMJ阅读 1,768评论 0 3
  • 前言:本文所写的是博主的个人见解,如有错误或者不恰当之处,欢迎私信博主,加以改正!原文链接,demo链接 Serv...
    PassersHowe阅读 1,392评论 0 5
  • 1 每周一都是开始也是最忙的一天,很多例会都在这一天,因此这一天也是非常充实的一天。今天对我来说是最近一段时间唯一...
    田田拾光阅读 1,001评论 5 5
  • 今天是第一次看《这个杀手不太冷》这部电影。以前听说过很多次,但是今天是第一次看。我觉得一部好电影和其他电影的区别就...
    斯图若彩虹_阅读 386评论 0 0