23.本地服务Services

本文详细介绍了Android中本地服务Services的创建和生命周期,包括onCreate、onStartCommand、onDestroy以及onBind方法。通过案例展示了具体实现代码,讲解了如何启动和停止服务。同时,对比了服务与线程的区别,强调服务主要负责协调管理,实际耗时操作由线程执行。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

一、服务简介

        执行耗时操作(后台)


二.如何创建本地服务知识概括



三.案例

1.具体实现代码

activity_main.xml

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

    <Button
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="启动服务"
        android:onClick="start"
        />
    <Button
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="停止服务"
        android:onClick="stop"
        />

</LinearLayout>

MainActivity.java

package com.zking.android23_services;

import android.content.Intent;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.view.View;

public class MainActivity extends AppCompatActivity {

    private Intent intent;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        intent = new Intent(this,MyServices.class);
    }

    //开始服务
    public void start(View view){
        startService(intent);//Ctrl+P告诉你要传一个Intent对象
    }

    //停止服务
    public void stop(View view){
        stopService(intent);
    }

}

服务的生命周期:onCreate  onStartCommand  onDestroy onBind

本地服务:onStartCommand返回值3

服务的停止:stopService  stopSelf(stopSelf() 、stopSelf(id))  

MyServices.java

package com.zking.android23_services;

import android.app.Service;
import android.content.Intent;
import android.os.IBinder;
import android.os.SystemClock;
import android.support.annotation.Nullable;
import android.util.Log;

/**
 * 面试题:线程和服务区别
 *
 * Service要配置:因为属于4大基本主键
 *
 * 本地服务有一个特点:当你执行完之后,这个服务要自杀onDestroy
 * stopSelf(startId) 无参:只要第一个服务执行完毕就会停止。有参:所以的服务执行完毕才会调用onDestroy方法
 *
 */

public class MyServices extends Service {

    //方法1:这个方法在远程服务中才会用
    @Nullable
    @Override
    public IBinder onBind(Intent intent) {
        return null;
    }

    //方法2
    @Override
    public void onCreate() {
        super.onCreate();
        Log.i("test","onCreate");
    }

    //方法3:执行所有耗时的操作
    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {//报错:右键Removw移除掉@IntDef
         new MyThread(startId).start();//启动这个线程 把startId传进来
         return Service.START_STICKY;//哪怕应用程序被干掉,服务过一段时间会重启
    }
    //子线程
    class MyThread extends Thread{
        private int startId;//是onStartCommand方法返回的值startId
        //构造方法
        public MyThread(int startId) {
            this.startId = startId;
        }

        @Override
        public void run() {
            super.run();
            for (int i = 0; i <=10 ; i++) {//模拟一个下载的操作
                Log.i("test","onStartCommand,"+i);
                SystemClock.sleep(500);//为了看效果,睡眠一下
            }
            stopSelf(startId);//把startId传进来  不管你有几个线程,当你全部执行完之后,他才会销毁
        }
    }

    //方法4
    @Override
    public void onDestroy() {
        super.onDestroy();
        Log.i("test","onDestroy");
    }
}

AndroidManifest.xml

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.zking.android23_services">

    <application android:allowBackup="true" android:icon="@mipmap/ic_launcher"
        android:label="@string/app_name" android:roundIcon="@mipmap/ic_launcher_round"
        android:supportsRtl="true" android:theme="@style/AppTheme">
        <activity android:name=".MainActivity">
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />

                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>

        <!--配置服务-->
        <service android:name=".MyServices"
            android:enabled="true"
            android:exported="true"
            ><!--enabled、exported属性:可以被其他的应用程序所启动-->
        </service>

    </application>

</manifest>

2.执行效果



四.线程和服务区别

线程执行耗时的操作,服务也执行耗时的操作,服务本身不能执行耗时的操作,还是依赖于线程
可以理解为:服务是老大,线程是小弟,干事情的永远是小弟,指挥小弟干事情的是老大,没有老大是不行的,因为老大是不容易死的,死了还可以恢复,小弟容易死。但是干事情的是小弟。




评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值