Service生命周期详解

随时随地阅读更多技术实战干货,获取项目源码、学习资料,请关注源代码社区公众号(ydmsq666)

在前面已多次使用了Service,相信大家对Service的生命周期大概已经有所了解了,这里简要归纳一下。

1、只以StartService方式启动:onCreate---->onStartCommand---->onDestroy。可以看出这个非常简单

注意:如果没有执行stopService而多次连续启动,只会多次执行onStartCommand,而不会多次执行onCreate。附上图片:

2、只以bindService方式启动:

onCreate---->onBind---->onUnbind---->onDestroy

注意:此过程可以循环执行,但是在调用unBindService方法前连续调bindService对应的onBind()只会调用一次。

附上图片:

3、StartService、bindService混合执行(先StartService再bindService再unBindService再bindService):

①onUnbind 方法return true(第二次bindService时会执行onRebind):

onCreate---->onStartCommand---->onBind---->onUnbind---->onRebind

②onUnbind 方法return super.onUnbind(intent)(第二次bindService时不会执行onRebind也不会执行onBind):

onCreate---->onStartCommand---->onBind---->onUnbind

此情况与上面情况相同点在于:执行了onUnbind后都可以再重新绑定,但这种情况不会调用onRebind也不会调用onBind,也就是说在一个生命周期内,onBind只能执行一次。

至于onStartCommand和onBind的顺序取决于先执行StartService还是先执行bindService。

附上图片:

下面通过一个示例来演示:

Activity:

package com.home.activity;

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;
import android.widget.Button;
import android.widget.TextView;

import com.home.service.MyService;
import com.home.servicelife.R;

public class ServiceLifeTestActivity extends Activity {
	private Intent intent;
	private TextView show;
	private Button unbindBtn;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.main);
		show = (TextView) findViewById(R.id.main_tv_show);
		unbindBtn = (Button) findViewById(R.id.main_btn_unbind);
		intent = new Intent(this, MyService.class);
	}

	public void click(View v) {
		if (v.getId() == R.id.main_btn_start) {
			startService(intent);
		} else if (v.getId() == R.id.main_btn_bind) {
			bindService(intent, myServiceConnection, BIND_AUTO_CREATE);
			unbindBtn.setEnabled(true);
		} else if (v.getId() == R.id.main_btn_unbind) {
			unbindService(myServiceConnection);
			unbindBtn.setEnabled(false);
		} else if (v.getId() == R.id.main_btn_stop) {
			intent = new Intent(this, MyService.class);
			stopService(intent);
		}
	}

	private ServiceConnection myServiceConnection = new ServiceConnection() {

		@Override
		public void onServiceConnected(ComponentName name, IBinder service) {
			String systemTime = ((MyService.MyBinder) service).getSystemTime();
			show.setText("当前系统时间为:" + systemTime);
		}

		@Override
		public void onServiceDisconnected(ComponentName name) {
		}
	};
}


Service:

package com.home.service;

import java.text.SimpleDateFormat;
import java.util.Date;

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 myBinder = new MyBinder();

	/**
	 * 必须实现的方法,只有以bindService方式启动才会调用,该方法返回一个建立连接后的IBinder接口对象
	 */
	@Override
	public IBinder onBind(Intent arg0) {
		Log.i("MyService", "执行onBind");
		return myBinder;
	}

	/**
	 * 当Service第一次被创建时执行该方法
	 */
	@Override
	public void onCreate() {
		Log.i("MyService", "执行onCreate");
		super.onCreate();
	}

	/**
	 * 以startService方式启动时会调用,该方法可能被多次调用
	 */
	@Override
	public int onStartCommand(Intent intent, int flags, int startId) {
		Log.i("MyService", "执行onStartCommand");
		return super.onStartCommand(intent, flags, startId);
	}

	/**
	 * 当Service被断开连接时回调该方法
	 */
	@Override
	public boolean onUnbind(Intent intent) {
		Log.i("MyService", "onUnbind");
		return super.onUnbind(intent);
		// return true;
	}

	/**
	 * 重新绑定时执行该方法,前提是onUnbind返回true
	 */
	@Override
	public void onRebind(Intent intent) {
		Log.i("MyService", "onRebind");
		super.onRebind(intent);
	}

	/**
	 * Service被关闭之前回调该方法
	 */
	@Override
	public void onDestroy() {
		Log.i("MyService", "onDestroy");
		super.onDestroy();
	}

	public class MyBinder extends Binder {
		/**
		 * 获取系统时间
		 * 
		 * @return 系统时间
		 */
		public String getSystemTime() {
			SimpleDateFormat simpleDateFormat = new SimpleDateFormat(
					"yyyy-MM-dd HH:mm:ss");
			return simpleDateFormat.format(new Date());
		}
	}
}

布局XML:

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical" >

    <Button
        android:id="@+id/main_btn_start"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:onClick="click"
        android:text="startService" />

    <Button
        android:id="@+id/main_btn_bind"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:onClick="click"
        android:text="bindService" />

    <Button
        android:id="@+id/main_btn_unbind"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:onClick="click"
        android:text="unbindService" />

    <Button
        android:id="@+id/main_btn_stop"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:onClick="click"
        android:text="stopService" />

    <TextView
        android:id="@+id/main_tv_show"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content" />

</LinearLayout>


大家可以自己试试,看看打印的出来的日志,便一目了然。

  • 1
    点赞
  • 6
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

u010142437

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值