android service

Service是android 系统中的一种组件。

特性

1、后台运行,运行在context线程上,若有耗时操作需另开线程,否则会阻塞界面交互。

2、service作为组件,可以与context交互。

两种使用方式

非绑定模式

context.startService()  ->onCreate()- >onStart()->Service running
context.stopService() | ->onDestroy() ->Service stop

生命周期为:onCreate-->onStart(可多次调用)-->onDestroy

绑定模式

context.bindService()->onCreate()->onBind()->Service running
onUnbind() -> onDestroy() ->Service stop
生命周期为:onCreate --> onBind(只一次,不可多次绑定) --> onUnbind --> onDestory。

区别

绑定模式与启动的context无关,谁都可以调用和关闭。绑定模式与启动的context共存亡,其他的congtext无法使用。

实战

非绑定模式

1、创建service

public class MusicService extends Service

2、实现方法

public void onCreate() {}

public void onDestroy() {}

public void onStart(Intent intent, int startId) {}

3、注册AndroidManifest.xml

<service android:enabled="true" android:name="sky.leo.exampleservice.MusicService">

<intent-filter>

<action android:name="sky.leo.exampleservice.MusicService" />

</intent-filter>

</service>

4、启动service

Intent mIntent = new Intent(this, MusicService.class);

或者

Intent mIntent = new Intent(MusicService.SERVICE_ACTION);

startService(mIntent);

绑定模式

1、创建service

public class BindMusicService extends Service

2、创建内部类并实例化

3、实现方法

 public IBinder onBind(Intent arg0) {
  return mIBinder;
 }

public void onCreate()

public void onDestroy() {}

4、实例化ServiceConnection,用于与service交互

5、注册AndroidManifest.xml

<service android:enabled="true"
            android:name="sky.leo.exampleservice.BindMusicService" >
    <intent-filter>
         <action android:name="sky.leo.exampleservice.BindMusicService" />
    </intent-filter>
</service>

6、启动

Intent mIntent = new Intent(BindMusicService.SERVICE_ACTION); 
bindService(mIntent, mServiceConnection, Context.BIND_AUTO_CREATE);

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值