Android之Service的简单实例

通过前面的学习,读者应该对Service有了一个全面的了解,也知道了创建与启动Service的具体步骤与方法。下面将通过实例带领大家一起学习如何使用Service

实例:以start方式创建与启动Service

通过前面的学习,我们知道了用start方式创建以及使用 Service的4个步骤,下面我们按照这4个步骤来进行讲解。

1、 创建一个继承 Service 的类 MyService,在类中实现它的几个主要方法,为了验证生命周期的结论,我们在生命周期方法中都加入了Log。同时,为了模拟真实的开发环境,我们建立了一个线程,并在onStartCommand(Intent intent,in flags,in startld)方法中使用这个线程,在onDestroy()挂起线程,并销毁线程对象。具体的代码如下;

package com.rfstar.servicetest01;
import android.app.Service;
import android.content.Intent;
import android.os.IBinder;
import android.util.Log;

import androidx.annotation.Nullable;

public class MyService extends Service {

    private  Thread thread;
    private ServiceThread serviceThread;

    @Override
    public void onCreate()
    {
        super.onCreate();
        Log.i("MyService","onCreate");
    }

    @Override
    public  int onStartCommand(Intent intent,int flags,int startId)
    {
        Log.i("MyService","onStartCommand");
        serviceThread=new ServiceThread();
        thread=new Thread(serviceThread);
        //开启一个线程
        thread.start();
        return super.onStartCommand(intent,flags,startId);
    }

    @Override
    public void onDestroy()
    {
        super.onDestroy();
        //结束run方法的循环
        serviceThread.flag=false;
        //挂起线程
        thread.interrupt();
        thread=null;
        L
  • 2
    点赞
  • 7
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值