Service 基础用法简介

1 Service简介

        服务(Service)  是Android中实现程序后台运行的解决方案,它非常适合去执行那些不需要 和用户交互而且还要求长期运行的任务。服务的运行不依赖于任何用户界面,即使程序被切换到 后台,或者用户打开了另外一个应用程序,服务仍然能够保持正常运行。

        服务并不是运行在一个独立的进程当中的,而是依赖于创建服务时所在 的应用程序进程。当某个应用程序进程被杀掉时,所有依赖于该进程的服务也会停止运行。

        服务并不会自动幵启线程,所有的代码都是 默认运行在主线程当中的。我们需要在服务的内部手动创建子线程,并在这里执行具 体的任务,否则就有可能出现主线程被阻塞住的情况。

 

2  Service的两种启动方式

  1  使用ContextstartService(Intent)方法启动Service

  • 步骤
  1. 定义一个类继承Service
  2. 在Manifest.xml文件中配置该Service
  3. 使用Context的startService(Intent)方法启动该Service
  4. 不再使用时,调用stopService(Intent)或者stopSelf()方法停止该服务
  • 生命周期

       onCreate()--->onStartCommand()(onStart()方法已过时)---> onDestory()

  • 特点
  1. 如果服务已经开启,不会重复的执行onCreate(), 而是会调用onStartCommand()。服务停止的时候调用 onDestory()。服务只会被停止一次。

     2. 一旦服务开启跟调用者(开启者)就没有任何关系了。开启者退出了,开启者挂了,服务还在后台长期的运行。开启者不能调用服务里面的方法。

  • 代码示例        

            Actiivity 中代码            

public class MainActivity extends AppCompatActivity implements View.OnClickListener {
    private static final String TAG = "MainActivity";
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        Button startService = findViewById(R.id.start_service);
        Button stopService = findViewById(R.id.stop_services);
        startService.setOnClickListener(this);
        stopService.setOnClickListener(this);

    }

    @Override
    public void onClick(View view) {
        switch (view.getId()){
            case R.id.start_service:
                Intent startIntent=new Intent(this,MyService.class);
                //开启服务
                startService(startIntent);
                break;
            case R.id.stop_services:
                Intent stopIntent=new Intent(this,MyService.class);
                //结束服务
                stopService(stopIntent);
                break;
            default:
                break;
        }
    }
}

          xml 中代码

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical"
    tools:context=".MainActivity">

   <Button
       android:id="@+id/start_service"
       android:layout_width="match_parent"
       android:layout_height="wrap_content"
       android:text="Start Service"/>
   <Button
       android:layout_marginTop="10dp"
       android:id="@+id/stop_service"
       android:layout_width="match_parent"
       android:layout_height="w
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值