Android Service的生命周期和基本使用

Service是Android四大组件与Activity最为相似的组件,他们的区别在于Service没有可视化界面,而且Service是一直在后台运行的,不能跑到前台的,今天和大家分享下Service的生命周期和基本使用

一:创建Service

1.创建MyService继承于Service

public class MyService extends Service {
 
	public static final String TAG = "MyService";
 
	@Override
	public void onCreate() {
		super.onCreate();
		Log.d(TAG, "onCreate() executed");
	}
 
	@Override
	public int onStartCommand(Intent intent, int flags, int startId) {
		Log.d(TAG, "onStartCommand() executed");
		return super.onStartCommand(intent, flags, startId);
	}
	
	@Override
	public void onDestroy() {
		super.onDestroy();
		Log.d(TAG, "onDestroy() executed");
	}
 
	@Override
	public IBinder onBind(Intent intent) {
		return null;
	}
 

2.AndroidManifest.xm注册

 <service android:name=".MyService"/>

二:启动和停止Service

1.开启

Intent intent = new Intent(this, MyService.class);
startService(intent);

2.停止

Intent intent = new Intent(this, MyService.class);
stopService(intent);

3.绑定服务

  Intent intent = new Intent(this, MyService.class);
   conn = new MyConn();
        //绑定服务,
        // 第一个参数是intent对象,表面开启的服务。
        // 第二个参数是绑定服务的监听器
        // 第三个参数一般为BIND_AUTO_CREATE常量,表示自动创建bind
   bindService(intent, conn, BIND_AUTO_CREATE);

4.解绑服务

unbindService(conn);// 解除绑定,断开连接

5,传值

Intent intent = new Intent(this, MyService.class);
intent.putExtra("key", true);
intent.putExtra("key2", "123");
startService(intent);

4.接收

在这里插入代码片

三:生命周期

onCreate():

首次创建服务时,系统将调用此方法。如果服务已在运行,则不会调用此方法,该方法只调用一次。

onStartCommand():

当另一个组件通过调用startService()请求启动服务时,系统将调用此方法

onDestroy():

当服务不再使用且将被销毁时,系统将调用此方法

onBind():

当另一个组件通过调用bindService()与服务绑定时,系统将调用此方法

onUnbind():

当另一个组件通过调用unbindService()与服务解绑时,系统将调用此方法

onRebind():

当旧的组件与服务解绑后,另一个新的组件与服务绑定,onUnbind()返回true时,系统将调用此方法

四:普通服务和绑定式服务区别

1.普通服务

Service会经历 onCreate --> onStart
stopService的时候直接onDestroy
如果bai是 调用者 直接退出而du没有调用stopService的话,Service会一zhi直在后台运行。
下次调用者再起来仍然dao可以stopService。

2.绑定式服务

Service只会运行onCreate, 这个时候 调用者和Service绑定在一起
调用者退出了,Srevice就会调用onUnbind–>onDestroyed
所谓绑定在一起就共存亡了。

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值