Android Service

一、Service的基本用法

1.定义一个Service

public class MyService extends Service {
    public static final String TAG = "MyService";
    public 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 mBinder;
    }
}
onCreate()方法会在Service第一次创建的时候调用,onStartCommand()方法会在每次Service启动的时候调用,onDestory()方法会在Service销毁的时候调用。

Service启动立刻执行某个动作,可以将逻辑写在onStartCommand()方法里。在onDestory()方法中回收不再使用的资源。

Service需要在AndroidManifest.xml文件中进行注册才能生效。


2.启动和停止Service 

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

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


3.Activity和Service进行通信

在Service中创建一个Binder实例,提供一系列方法。在Activity中绑定Service,在ServiceConnection中获取该Binder实例,执行需要的方法。

 private ServiceConnection connection = new ServiceConnection(){

        @Override
        public void onServiceConnected(ComponentName name, IBinder service) {
        
        }
        @Override
        public void onServiceDisconnected(ComponentName name) {

        }
    };
onServiceConnected():Activity和Service成功绑定时调用。

onServiceDisconneced():Activity和Service解除绑定时调用。


 绑定Service

 Intent bindIntent = new Intent(this,MyService.class);
 bindService(bindIntent,connection,BIND_AUTO_CREATE);

 bindService()方法接受三个参数,第一个参数是Intent,第二个参数是ServiceConnection,第三个参数是个标记位,传入BIND_AUTO_CREATE表示Activity绑定Service后自动创 建Service。


 解绑Service

 unbindService(connection);

二、Service的生命周期

调用Context的startService()方法,如果Service是第一次被创建,则先执行onCreate()方法,然后执行onStartCommand()方法,直到stopService()或stopSelf()调用后执行onDestory()方法。如果Service已经创建过,则每调用一次startService()方法,onStartCommand()方法就会执行一次。

调用Context的bindService()方法,如果Service是第一次创建,则先执行onCreate()方法,然后执行onBind()方法,直到stopService()或stopSelf()调用后执行onDestory()方法。

如果Service已经创建过,则onCreate()方法和onBind()方法不会再执行。

如果一起调用了startService()和bindService()方法,则需要同时调用stopService和unBindService()方法onDestory()才可以执行。


前台Service

Service的系统优先级较低,当系统出现内存不足的时候,就有可能回收掉正在后台运行的Service。如果希望Service一直保持运行状态,不会由于系统内存不足的原因导致被回收,就可以考虑使用前台Service。


IntentService

IntentService是一个异步的,会自动停止的Service,集开线程和自动停止于一身。

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值