Android 四大组件之 Service_3_音乐播放器(本地Service)

一、 基本介绍

简单的音乐播放器实例, 提供播放、停止、暂停、退出音乐操作。 先由Activity 实现,再引出由Service(本地Service)实现。

二、Acitivity实现

1. 布局文件

<?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=".MainActivity">

    <Button
        android:layout_width="match_parent"
        android:layout_height="60dp"
        android:text="Play"
        android:onClick="playMusic"/>
    <Button
        android:layout_width="match_parent"
        android:layout_height="60dp"
        android:text="Stop"
        android:onClick="stopMusic"/>
    <Button
        android:layout_width="match_parent"
        android:layout_height="60dp"
        android:text="Pause"
        android:onClick="pauseMusic"/>
    <Button
        android:layout_width="match_parent"
        android:layout_height="60dp"
        android:text="Exit"
        android:onClick="exitMusic"/>

</LinearLayout>

2. Activity中实现音乐操作

package com.example.musicplayer;

import androidx.appcompat.app.AppCompatActivity;

import android.media.MediaPlayer;
import android.os.Bundle;
import android.util.Log;
import android.view.View;

public class MainActivity extends AppCompatActivity {
    private static final String TAG = "MainActivity";
    private MediaPlayer mPlayer = null;

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

    public void playMusic(View view) {
        log("playMusic");
        if (mPlayer == null) {
            mPlayer = MediaPlayer.create(this, R.raw.simple_music);
        }
        mPlayer.start();
        log("playMusic done");
    }

    public void stopMusic(View view) {
        log("stopMusic");
        if (mPlayer != null) {
            mPlayer.stop();
            mPlayer.reset(); //重置(进度)
            mPlayer.release(); //释放资源
            mPlayer = null;
            log("stopMusic done");
        }
    }

    public void pauseMusic(View view) {
        log("pause Music");
        if (mPlayer != null && mPlayer.isPlaying()) {
            mPlay
### Service 的作用 ServiceAndroid 四大组件之一,其主要作用是在后台执行长时间运行的任务,而不需要与用户进行交互。它没有界面,适用于执行如网络请求、播放音乐、文件 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(例如前台服务)可能需要在清单文件中声明额外的权限。
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值