android service笔记

1.Service作为android 4大组件之一,与Activity十分相似,都代表可执行的程序。Service再后台运行,没有用户界面,有自己的生命周期。


2.创建配置Service

右键点击代码包 new-->Service-->Service

配置属性 export   能否被其他应用访问

Enable 是否启用

Manifest.xml文件中添加配置

<service
            android:name=".MyService"
            android:enabled="true"
            android:exported="true"></service>
3.通过Intent启动关闭服务

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



4.绑定Service并通过Binder对象进行通信(重要)

在Service类中定义内部类继承Binder类,并在方法onBind返回对象

    MyBinder binder = new MyBinder();
    class MyBinder extends Binder{
        public void test(){
            
        }
    }
    @Override
    public IBinder onBind(Intent intent) {  //必须实现,返回一个IBinder对象,应用程序通过其与Service通信
        return binder;
    }

在Activity类中通过以下方法绑定与解绑:

bindService(Intent intent,ServiceConnection conn,int flags)

unbinderService(ServiceConnection conn)

conn对象用于监听访问者(Activity)与服务(Service)之间连接状况

flag值得是绑定时是否自动创建Service (0或BIND_AUTO_CREATE)

    private MyService.MyBinder myBinder; //通过Service返回的MyBinder对象,访问Service内部数据,实现通信
    private ServiceConnection connection = new ServiceConnection() {
        @Override
        public void onServiceConnected(ComponentName name, IBinder service) {//连接成功时回调该方法
                myBinder = (MyService.MyBinder)service;
                myBinder.test();  //通信逻辑
        }
        @Override
        public void onServiceDisconnected(ComponentName name) { //Service所在进程异常终止或其他原因终止,导致连接断开时调用

        }
    };	
	bindService(intent,connection,BIND_AUTO_CREATE);
        unbindService(connection);

5.Service生命周期



6.IntentService (异步的、会自动停止的服务)

Service默认在主线程中,进行耗时操作容易ANR

IntentService采用队列管理Intent,开启一条新的worker线程处理Intent,只需重写onHandleIntent()方法,处理逻辑

 public MyIntentService() {
        super("MyIntentService");
    }

    @Override
    protected void onHandleIntent(Intent intent) {
}



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

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值