【Android四大组件】(本地,前台,可通信)Service的基本用法

本文详细介绍了Android四大组件之一的Service,包括Service的分类、特点及不同类型的Service解析:本地Service的创建与启动方式,可通信的Service如何与Activity绑定,前台Service的实现以及它们的使用场景。
摘要由CSDN通过智能技术生成

一、Service分类

1.1Service的分类

在这里插入图片描述

1.2不同Service的特点

在这里插入图片描述在这里插入图片描述

二、不同Service解析

2.1本地Service

2.1.1基础本地service的创建(demo展示):

public class MyService extends Service {
   


//启动Service之后,就可以在onCreate()或onStartCommand()方法里去执行一些具体的逻辑
//由于这里作Demo用,所以只打印一些语句
    @Override
    public void onCreate() {
   
        super.onCreate();
        System.out.println("执行了onCreat()");
    }

    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {
   
        System.out.println("执行了onStartCommand()");
        return super.onStartCommand(intent, flags, startId);


    }

    @Override
    public void onDestroy() {
   
        super.onDestroy();
        System.out.println("执行了onDestory()");
    }

    @Nullable
    @Override
    public IBinder onBind(Intent intent) {
   
        return null;
    }
}

启动和停止Service的方式:

 //构建启动服务的Intent对象
                Intent startIntent = new Intent(this, MyService.class);
                //调用startService()方法-传入Intent对象,以此启动服务
                startService(startIntent);
//构建停止服务的Intent对象
                Intent stopIntent = new Intent(this, MyService.class);
                //调用stopService()方法-传入Intent对象,以此停止服务
                stopService
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值