跳转到内容

Service

来自代码酷
Admin留言 | 贡献2025年5月1日 (四) 04:44的版本 (Created by Admin WikiAgent (referenced from Android (Java)))

(差异) ←上一版本 | 已核准修订 (差异) | 最后版本 (差异) | 下一版本→ (差异)
  1. Service

Service(服务)是Android (Java)平台中的一种核心组件,用于在后台执行长时间运行的操作,而不需要与用户界面进行交互。Service通常用于处理网络事务、播放音乐、执行文件I/O等任务,这些任务可能需要持续运行即使用户切换到其他应用。

    1. 概述

在Android系统中,Service是一种可以在后台执行操作的应用程序组件,它不提供用户界面。与Activity不同,Service可以在应用不可见时继续运行,这使得它特别适合执行那些不需要用户直接交互的任务。

Service主要有两种类型: 1. Started Service(启动服务):通过调用`startService()`启动,会一直运行直到调用`stopSelf()`或其他组件调用`stopService()` 2. Bound Service(绑定服务):通过调用`bindService()`启动,允许多个组件同时与之交互,当所有组件都解除绑定时,服务会被销毁

    1. 生命周期

Service的生命周期方法包括:

```mermaid graph TD

   A[onCreate] --> B[onStartCommand]
   B --> C[运行中]
   C --> D[onDestroy]
   E[onBind] --> F[运行中]
   F --> G[onUnbind]
   G --> D

```

    1. 实现示例
      1. 基本Service实现

以下是一个简单的Service实现示例:

public class MyService extends Service {
    private static final String TAG = "MyService";
    
    @Override
    public void onCreate() {
        super.onCreate();
        Log.d(TAG, "Service onCreate");
    }
    
    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {
        Log.d(TAG, "Service onStartCommand");
        // 执行后台任务
        performLongRunningOperation();
        return START_STICKY;
    }
    
    @Override
    public IBinder onBind(Intent intent) {
        // 如果是绑定服务,需要返回IBinder接口
        return null;
    }
    
    @Override
    public void onDestroy() {
        super.onDestroy();
        Log.d(TAG, "Service onDestroy");
    }
    
    private void performLongRunningOperation() {
        // 模拟长时间运行的任务
        new Thread(() -> {
            // 执行任务...
            stopSelf(); // 任务完成后停止服务
        }).start();
    }
}
      1. 在AndroidManifest.xml中声明

所有Service都必须在AndroidManifest.xml文件中声明:

<service android:name=".MyService" />
    1. 启动和停止Service

从Activity或其他组件中启动Service:

// 启动服务
Intent serviceIntent = new Intent(this, MyService.class);
startService(serviceIntent);

// 停止服务
stopService(serviceIntent);
    1. 绑定服务

绑定服务允许组件与服务交互:

public class MyBoundService extends Service {
    private final IBinder binder = new LocalBinder();
    
    public class LocalBinder extends Binder {
        MyBoundService getService() {
            return MyBoundService.this;
        }
    }
    
    @Override
    public IBinder onBind(Intent intent) {
        return binder;
    }
    
    public int getRandomNumber() {
        return new Random().nextInt(100);
    }
}

绑定到服务:

private ServiceConnection connection = new ServiceConnection() {
    @Override
    public void onServiceConnected(ComponentName name, IBinder service) {
        MyBoundService.LocalBinder binder = (MyBoundService.LocalBinder) service;
        myBoundService = binder.getService();
        isBound = true;
    }
    
    @Override
    public void onServiceDisconnected(ComponentName name) {
        isBound = false;
    }
};

Intent intent = new Intent(this, MyBoundService.class);
bindService(intent, connection, Context.BIND_AUTO_CREATE);
    1. 前台服务

从Android 8.0 (API 26)开始,后台服务受到限制,推荐使用前台服务:

Notification notification = new Notification.Builder(this, CHANNEL_ID)
        .setContentTitle("服务运行中")
        .setContentText("正在执行重要任务")
        .setSmallIcon(R.drawable.notification_icon)
        .build();

startForeground(ONGOING_NOTIFICATION_ID, notification);
    1. 实际应用场景

1. **音乐播放器**:在后台播放音乐,即使用户切换到其他应用 2. **文件下载**:执行大文件下载,即使应用不在前台 3. **数据同步**:定期与服务器同步数据 4. **位置跟踪**:持续获取和记录设备位置信息

    1. 注意事项

1. **主线程阻塞**:Service默认运行在主线程,长时间操作应使用工作线程 2. **电量优化**:长时间运行的服务应考虑电量消耗问题 3. **Android 8.0+限制**:后台服务受到限制,应考虑使用JobSchedulerWorkManager 4. **内存管理**:系统可能在内存不足时终止服务

    1. 参见