Android 音乐播放器的开发教程(六)service的运用及音乐列表点击播放 ----- 小达

本文是Android音乐播放器开发系列的第六篇,主要讲解如何使用Service进行音乐播放,并添加ListView点击事件。通过在MyMusicFragment中注册监听器,启动Service播放音乐。接着创建PlayerService类,处理播放逻辑。目前,点击列表项可以播放音乐,但还需添加暂停和切歌功能,后续教程将继续完善。

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

service的运用及音乐列表点击播放



         按照前几篇博客的步骤,应该能看到自己手机里的音乐列表了,但是现在还只能看,不能点,还需要再给ListView添加点击事件的监听,接着启动一个Service来播放音乐,service是android四大组件之一,在官方的文档上是这样解释的:


A Service is an application component that can perform long-running operations in the background and does not provide a user interface. Another application component can start a service and it will continue to run in the background even if the user switches to another application. Additionally, a component can bind to a service to interact with it and even perform interprocess communication (IPC). For example, a service might handle network transactions, play music, perform file I/O, or interact with a content provider, all from the background.


        也就是说,Service(服务)是一个没有用户界面的在后台运行执行耗时操作的应用组件。其他应用组件能够启动Service,并且当用户切换到另外的应用场景,Service将持续在后台运行。另外,一个组件能够绑定到一个service与之交互(IPC机制),例如,一个service可能会处理网络操作,播放音乐,操作文件I/O或者与内容提供者(content provider)交互,所有这些活动都是在后台进行。


        我们先来给列表注册监听器,由于列表是显示在MyMusicFragment上面的,故注册监听器也应该在MyMusicFragment.java这个文件里面注册了,下面给出代码,红色部分为改动的地方:

package com.example.dada.myapplication;

import android.app.Activity;
import android.net.Uri;
import android.os.Bundle;
import android.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.ListView;

import java.util.List;


public class MyMusicFragment extends Fragment {

    private FindSongs finder;                                              //查找歌曲的类的实例
    private Activity MyActivity;
    private List<Mp3Info> mp3Infos;
    private MusicListAdapter musicListAdapter;

    private OnFragmentInteractionListener mListener;

<span style="color:#222222;">

    public static MyMusicFragment newInstance() {
        MyMusicFragment fragment = new MyMusicFragment();
        Bundle args = new Bundle();
        fragment.setArguments(args);
        return fragment;
    }

    public MyMusicFragment() {
        // Required empty public constructor
    }

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
评论 4
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值