四大组件之一Service

本文详细介绍了Android中的Service组件,包括为何需要Service、Service的特点及其不同类型的使用方法。通过实例演示了如何创建并使用startService、bindService及IntentService。

Service

为什么要学习Service

我们在做一些项目时需要让它在后台执行(如:下载,音乐播放)这个时候我们就需要Service。

什么是Service

1.Service是Android四大组件之一,和Activity的级别相当。
2.Service是可以长时运行在后台的, 是不可见,是没有界面的组件。
3.Service是运行在主线程中的。
4.Service可以跨进程调用。

如何使用Service

使用startService方式启动Service步骤
1.新建类继承Service。
2.重写onCreate方法。
(Service在创建时调用的方法,可以用来做数据初始化,Service在没有停止之前,只会执行一次。)
3.实现onBind抽象方法。
(由于Service是一个抽象类,定义了一个onBind抽象方法,return null即可,此方法在startService方式用不上,无需理会即可。)
4.重写onStartCommand方法。
(Service创建后会调用onStartCommand,此方法中可以接收调用者传递过来的参数,并且可以编写需要的逻辑代码,当重复调用Service时,onStartCommand会重复执行,onStart方法弃用)。
5.重写onDestroy方法。
(Service在退出时调用,此方法中可以编写释放资源的操作。)
6.在AndroidManifest中注册Service。
(使用< Service >标签注册,同Activity注册。)
7.在有Context环境中通过startService启动Service。
8.在有Context环境中通过stopService停止Service。

startService启动Service以及Service中耗时操作演示

1.onCreate只会执行一次,只要调用startService,onStartCommand定会执行。
2.Service运行在main线程中,做耗时操作需另开子线程。
3.通过Intent进行传参,在onStartCommand中接收参数。
4.无法获得Service对象,不能直接操作Service中的属性和方法。
5.调用stopService后,Service会执行onDestroy方法后停止。

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

    <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之前需要注册一下
        <service android:name="MyService" >
        </service>
    </application>

</manifest>
package com.example.pc.service;

import android.app.Service;
import android.content.Intent;
import android.os.IBinder;
import android.util.Log;

/**
 * Created by pc on 2018/3/21.
 */

public class MyService extends Service {

    public static final String TAG = "MyService";

    @Override
    public void onCreate() {
        super.onCreate();
        //Thread.currentThread().getName()显示子线程的名字
        Log.e("Service"+Thread.currentThread().getName(), "onCreate() executed");
    }

    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {
        Log.e("Service", "onStartCommand() executed");
        //Service进行耗时操作
        new Thread(new Runnable() {
            @Override
            public void run() {
                for (int i=0;i<=20;i++){
                    Log.e("Service"+Thread.currentThread().getName(),i+"***");
                    try {
                        Thread.sleep(1000);
//                        stopSelf();
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                }
            }
        }).start();
        return super.onStartCommand(intent,flags,startId);
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        Log.e("Service"+Thread.currentThread().getName(), "onDestroy() executed");
    }

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

}
package com.example.pc.service;

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

public class MainActivity extends Activity implements View.OnClickListener {

    private Button startService;
    private Button stopService;
    private Intent intent;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        //赋ID,监听事件
        setContentView(R.layout.activity_main);
        startService = findViewById(R.id.start_service);
        stopService = findViewById(R.id.stop_service);
        startService.setOnClickListener(this);
        stopService.setOnClickListener(this);
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            //启动Service
            case R.id.start_service:
                intent = new Intent(this, MyService.class);
                startService(intent);
                break;
            //关闭
            case R.id.stop_service:
                stopService(intent);
                break;
            default:
                break;
        }
    }

}
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical" >

    <Button
        android:id="@+id/start_service"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="Start Service" />

    <Button
        android:id="@+id/stop_service"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="Stop Service" />

</LinearLayout>
bindService操作演示

1.新建类继承Service。
2.实现onBind抽象方法。
3.重写onCreate方法。
4.重写onUnbind方法。
5.重写onDestroy方法。
6.在AndroidManifest中注册Service。
7.在有Context环境中实现ServiceConnection接口。
8.在有Context环境中通过bindService绑定Service。
9.在有Context环境中通过unbindService绑定Service。

package com.example.pc.service;

import android.content.ComponentName;
import android.content.Intent;
import android.content.ServiceConnection;
import android.os.IBinder;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;

public class ZhangsanActivity extends AppCompatActivity implements View.OnClickListener {

    private Button bindBtn;
    private Button unBindBtn;
    private Button lisiBtn;

    private ServiceConnection serviceConnection = new ServiceConnection() {
        @Override
        public void onServiceConnected(ComponentName name, IBinder service) {
            //通过管家的中介作用,拿到TestService对象
            TestService testService = ((TestService.Guanjia) service).getServiceObject();
            testService.fly();
        }

        @Override
        public void onServiceDisconnected(ComponentName name) {

        }
    };

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

    private void bindID() {
        bindBtn = findViewById(R.id.btn1);
        unBindBtn = findViewById(R.id.btn2);
        lisiBtn = findViewById(R.id.btn3);
        unBindBtn.setOnClickListener(this);
        bindBtn.setOnClickListener(this);
        lisiBtn.setOnClickListener(this);
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()){
            case R.id.btn1:
//                Intent intent = new Intent(this,TestService.class);
//                bindService(intent,serviceConnection,BIND_AUTO_CREATE);
                Intent intent = new Intent(this,MyIntentService.class);
                startService(intent);
                break;
            case R.id.btn2:
                unbindService(serviceConnection);
                break;
            case R.id.btn3:
                Intent intent1 = new Intent(this,LisiActivity.class);
                startActivity(intent1);
                break;
        }
    }
}
package com.example.pc.service;

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

/**
 * Created by pc on 2018/3/23.
 */

public class TestService extends Service {

    private String TAG = "TestService";

    private Guanjia guanjia = new Guanjia();

    class Guanjia extends Binder{
        //作用:得到当前Service的对象
        public TestService getServiceObject(){
            return TestService.this;
        }
    }

    public void fly(){
        Log.e(TAG,"开飞机");
    }

    @Nullable
    @Override
    public IBinder onBind(Intent intent) {
        Log.e(TAG,"onBind...");
        return guanjia;
    }

    @Override
    public boolean onUnbind(Intent intent) {
        Log.e(TAG,"onUnbind");
        return super.onUnbind(intent);
    }

    @Override
    public void onCreate() {
        super.onCreate();
        Log.e(TAG,"onCreate");
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        Log.e(TAG,"onDestroy");
    }
}

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

    <Button
        android:id="@+id/btn1"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="BinderService绑定"/>

    <Button
        android:id="@+id/btn2"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="BinderService解绑"/>

    <Button
        android:id="@+id/btn3"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="跳转到lisi"/>

</LinearLayout>
IntentService操作演示

1.新建类继承IntentService
2.实现父类的构造方法
3.重写onHandleIntent方法
4.重写Oncreat方法
5.重写onDestory方法
6.在AndroidManifest中注册Service
7.在有Context环境中实现ServiceConnection接口
8.在有Context环境中通过startService绑定Service
9.在有Context环境中通过stopService解绑Service

package com.example.pc.service;

import android.app.IntentService;
import android.content.Intent;
import android.support.annotation.Nullable;
import android.util.Log;

import java.io.InputStream;

/**
 * Created by pc on 2018/3/23.
 */

public class MyIntentService extends IntentService {
    /**
     * Creates an IntentService.  Invoked by your subclass's constructor.
     *
     * @param name Used to name the worker thread, important only for debugging.
     */
    public MyIntentService(String name) {
        super(name);
    }
    public MyIntentService(){
        super("");

    }

    @Override
    protected void onHandleIntent(@Nullable Intent intent) {

        for (int i=0;i<10;i++){
            try {
                Log.e("MyIntentService",i+"***");
                Thread.sleep(1000);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }

    }

    @Override
    public void onCreate() {
        super.onCreate();
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
    }
}
<?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"
    android:orientation="vertical"
    tools:context="com.example.pc.service.LisiActivity">
<Button
    android:id="@+id/lisi_bind_btn"
    android:layout_width="match_parent"
    android:layout_height="50dp"
    android:text="绑定Service"/>
    <Button
        android:id="@+id/lisi_unbind_btn"
        android:layout_width="match_parent"
        android:layout_height="50dp"
        android:text="解绑Service"/>
</LinearLayout>
package com.example.pc.service;

import android.content.ComponentName;
import android.content.Intent;
import android.content.ServiceConnection;
import android.os.IBinder;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Button;

public class LisiActivity extends AppCompatActivity implements View.OnClickListener {

    private Button bindBtn;
    private Button unbindBtn;

    private String TAG = "LisiActivity";
    private ServiceConnection connection = new ServiceConnection() {
        @Override
        public void onServiceConnected(ComponentName name, IBinder service) {
            Log.e(TAG,"onServiceConnected...");
            TestService testService = ((TestService.Guanjia)service).getServiceObject();
            testService.fly();
        }

        @Override
        public void onServiceDisconnected(ComponentName name) {
            Log.e(TAG,"onServiceDisconnected...");
        }
    };

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

        bindID();
    }

    private void bindID() {

        bindBtn = findViewById(R.id.lisi_bind_btn);
        unbindBtn = findViewById(R.id.lisi_unbind_btn);

        bindBtn.setOnClickListener(this);
        unbindBtn.setOnClickListener(this);
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()){
            case R.id.lisi_bind_btn:
                Intent intent = new Intent(this,TestService.class);
                bindService(intent,connection,BIND_AUTO_CREATE);
                break;
            case R.id.lisi_unbind_btn:
                unbindService(connection);
                break;
        }
    }
}
先展示下效果 https://pan.quark.cn/s/e81b877737c1 Node.js 是一种基于 Chrome V8 引擎的 JavaScript 执行环境,它使开发者能够在服务器端执行 JavaScript 编程,显著促进了全栈开发的应用普及。 在 Node.js 的开发流程中,`node_modules` 文件夹用于存储所有依赖的模块,随着项目的进展,该文件夹可能会变得异常庞大,其中包含了众多可能已不再需要的文件和文件夹,这不仅会消耗大量的硬盘空间,还可能减慢项目的加载时间。 `ModClean 2.0` 正是为了应对这一挑战而设计的工具。 `ModClean` 是一款用于清理 `node_modules` 的软件,其核心功能是移除那些不再被使用的文件和文件夹,从而确保项目的整洁性和运行效率。 `ModClean 2.0` 是此工具的改进版本,在原有功能上增加了更多特性,从而提高了清理工作的效率和精确度。 在 `ModClean 2.0` 中,用户可以设置清理规则,例如排除特定的模块或文件类型,以防止误删重要文件。 该工具通常会保留项目所依赖的核心模块,但会移除测试、文档、示例代码等非运行时必需的部分。 通过这种方式,`ModClean` 能够协助开发者优化项目结构,减少不必要的依赖,加快项目的构建速度。 使用 `ModClean` 的步骤大致如下:1. 需要先安装 `ModClean`,在项目的根目录中执行以下命令: ``` npm install modclean -g ```2. 创建配置文件 `.modcleanrc.json` 或 `.modcleanrc.js`,设定希望清理的规则。 比如,可能需要忽略 `LICENSE` 文件或整个 `docs`...
2026最新微信在线AI客服系统源码 微信客服AI系统是一款基于PHP开发的智能客服解决方案,完美集成企业微信客服,为企业提供7×24小时智能客服服务。系统支持文本对话、图片分析、视频分析等多种交互方式,并具备完善的对话管理、人工转接、咨询提醒等高级功能。 核心功能 ### 1.  智能AI客服 #### 自动回复 - **上下文理解**:系统自动保存用户对话历史,AI能够理解上下文,提供连贯的对话体验 - **个性化配置**:可自定义系统提示词、最大输出长度等AI参数 #### 产品知识库集成 - **公司信息**:支持配置公司简介、官网、竞争对手等信息 - **产品列表**:可添加多个产品,包括产品名称、配置、价格、适用人群、特点等 - **常见问题FAQ**:预设常见问题及答案,AI优先使用知识库内容回答 - **促销活动**:支持配置当前优惠活动,AI会自动向用户推荐 ### 2. 多媒体支持 #### 图片分析 - 支持用户发送图片,AI自动分析图片内容 - 可结合文字描述,提供更精准的分析结果 - 支持常见图片格式:JPG、PNG、GIF、WebP等 #### 视频分析 - 支持用户发送视频,AI自动分析视频内容 - 视频文件自动保存到服务器,提供公网访问 - 支持常见视频格式:MP4、等 ### 3.  人工客服转接 #### 关键词触发 - **自定义关键词**:可配置多个转人工触发关键词(如:人工、客服、转人工等) - **自动转接**:用户消息包含关键词时,自动转接给指定人工客服 - **友好提示**:转接前向用户发送提示消息,提升用户体验 #### 一键介入功能 - **后台管理**:管理员可在对话管理页面查看所有对话记录 - **快速转接**:点击"一键介入"按钮,立即将用户转接给人工客服
### Service 的作用 Service 是 Android 四大组件之一,其主要作用是在后台执行长时间运行的任务,而不需要与用户进行交互。它没有界面,适用于执行如网络请求、播放音乐、文件 I/O 等需要在后台持续运行的操作。Service 可以独立于 Activity 运行,即使用户切换到其他应用,Service 仍然可以在后台继续运行 [^1]。 此外,Service 也可以被其他应用调用,从而提供一些特定的功能,例如后台数据处理或资源共享 [^2]。 ### Service 的生命周期 Service 的生命周期相对简单,主要包含以下几个关键方法: - `onCreate()`:当 Service 第一次被创建时调用,用于执行一次性初始化操作。 - `onStartCommand(Intent intent, int flags, int startId)`:当通过 `startService()` 启动 Service 时调用,用于处理传入的 Intent 请求。 - `onBind(Intent intent)`:当通过 `bindService()` 绑定 Service 时调用,返回一个 `IBinder` 对象用于实现组件间的通信。 - `onUnbind(Intent intent)`:当解除绑定时调用。 - `onDestroy()`:当 Service 被销毁时调用,用于释放资源。 根据启动方式的不同,Service 的生命周期会有所不同。 ### Service 的启动方式 Service 可以通过两种方式启动: 1. **通过 `startService()` 启动** - 使用 `startService()` 启动的 Service 会独立运行,与启动它的组件没有直接的绑定关系。 - 一旦启动,Service 会一直运行直到调用 `stopSelf()` 或外部调用 `stopService()`。 - 适用于执行一次性任务,例如下载文件或播放音乐。 2. **通过 `bindService()` 启动** - 使用 `bindService()` 启动的 Service 会与调用者(例如 Activity)建立绑定关系。 - 通过 `onBind()` 方法返回的 `IBinder` 对象,调用者可以与 Service 进行交互。 - 当调用者解除绑定时,Service 不会立即停止,只有当所有绑定都解除后,才会调用 `onUnbind()` 并最终调用 `onDestroy()` [^4]。 ### Service 的使用示例 #### 启动 Service ```java Intent serviceIntent = new Intent(context, MyService.class); context.startService(serviceIntent); ``` #### 停止 Service ```java Intent serviceIntent = new Intent(context, MyService.class); context.stopService(serviceIntent); ``` #### 绑定 Service ```java Intent serviceIntent = new Intent(context, MyService.class); context.bindService(serviceIntent, serviceConnection, Context.BIND_AUTO_CREATE); ``` 其中,`serviceConnection` 是一个实现了 `ServiceConnection` 接口的对象,用于接收 Service 绑定后的回调。 #### 解除绑定 ```java context.unbindService(serviceConnection); ``` ### Service 的声明 每个 Service 都需要在 `AndroidManifest.xml` 文件中进行声明,否则无法正常运行。声明方式如下: ```xml <service android:name=".MyService" /> ``` ### 前台 Service 如果需要让 Service 在前台运行,以避免被系统优先级机制杀死,可以使用 `startForegroundService()` 方法启动 Service,并在 Service 中调用 `startForeground()` 方法,将 Service 提升为前台服务 [^3]。 ```java Intent serviceIntent = new Intent(context, MyForegroundService.class); context.startForegroundService(serviceIntent); ``` 在 Service 的 `onStartCommand()` 方法中: ```java Notification notification = new Notification.Builder(this, "channel_id") .setContentTitle("Foreground Service") .setSmallIcon(R.drawable.ic_notification) .build(); startForeground(1, notification); ``` ### 注意事项 - **资源管理**:由于 Service 在后台运行,需要注意资源的合理使用,避免过度消耗系统资源。 - **生命周期管理**:使用 `bindService()` 启动的 Service 必须通过 `unbindService()` 解除绑定,否则可能导致内存泄漏。 - **权限声明**:某些特殊用途的 Service(例如前台服务)可能需要在清单文件中声明额外的权限。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值