Android Studio初学者实例:仿网易音乐播放器

这篇具有很好参考价值的文章主要介绍了Android Studio初学者实例:仿网易音乐播放器。希望对大家有所帮助。如果存在错误或未考虑完全的地方,请大家不吝赐教,您也可以点击"举报违法"按钮提交疑问。

本期带来的是以Service为主要的知识点的网易音乐播放器

看一下效果图

android音乐播放器代码,Android初学者,android,android studioandroid音乐播放器代码,Android初学者,android,android studio

 首先项目准备:

在res下新建raw文件夹,并在文件夹中添加喜爱的mp3音乐

android音乐播放器代码,Android初学者,android,android studio

 OK,第一步,先写一个背景文件,在res/drawable文件夹中新建xml文件:

btn_bg_selector.xml

<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android">
    <item android:state_pressed="true" >
        <shape android:shape="rectangle">
            <corners android:radius="3dp"/>
            <solid android:color="#d4d4d4"/>
        </shape>
    </item>
    <item android:state_pressed="false" >
        <shape android:shape="rectangle">
            <corners android:radius="3dp"/>
            <solid android:color="#ffffff" />
        </shape>
    </item>
</selector>

 编写主界面代码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"
    android:orientation="vertical"
    android:gravity="center"
    android:background="@drawable/music_bg"
    tools:context=".MainActivity">

    <RelativeLayout
        android:layout_width="match_parent"
        android:layout_height="160dp">
        <RelativeLayout
            android:layout_width="300dp"
            android:layout_height="70dp"
            android:id="@+id/rl_title"
            android:layout_centerHorizontal="true"
            android:background="@drawable/title_bg"
            android:gravity="center_horizontal"
            android:paddingLeft="80dp">

            <TextView
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:id="@+id/tv_music_title"
                android:layout_marginTop="8dp"
                android:text="体面"
                android:textSize="12sp"
                android:textStyle="bold"
                android:textColor="@color/black"/>
            <TextView
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:id="@+id/tv_type"
                android:layout_marginTop="4dp"
                android:layout_below="@id/tv_music_title"
                android:layout_alignLeft="@id/tv_music_title"
                android:text="流行音乐"
                android:textSize="10dp"/>
            <SeekBar
                android:layout_width="150dp"
                android:layout_height="wrap_content"
                android:id="@+id/sb"
                android:layout_below="@+id/rl_time"
                android:layout_alignParentBottom="true"
                android:thumb="@null"/>
            <RelativeLayout
                android:layout_width="150dp"
                android:layout_height="wrap_content"
                android:layout_marginTop="4dp"
                android:id="@+id/rl_time"
                android:layout_below="@id/tv_type">
                <TextView
                    android:layout_width="wrap_content"
                    android:layout_height="wrap_content"
                    android:id="@+id/tv_progress"
                    android:text="00:00"
                    android:textSize="10dp"/>
                <TextView
                    android:layout_width="wrap_content"
                    android:layout_height="wrap_content"
                    android:id="@+id/tv_total"
                    android:layout_alignParentRight="true"
                    android:text="00:00"/>

            </RelativeLayout>
        </RelativeLayout>
        <LinearLayout
            android:layout_width="340dp"
            android:layout_height="90dp"
            android:layout_below="@id/rl_title"
            android:layout_centerHorizontal="true"
            android:background="@drawable/btn_bg"
            android:gravity="center_vertical"
            android:paddingLeft="120dp"
            android:paddingRight="10dp">
            <Button
                android:layout_width="0dp"
                android:layout_height="25dp"
                android:layout_margin="4dp"
                android:id="@+id/btn_play"
                android:layout_weight="1"
                android:background="@drawable/btn_bg_selector"
                android:text="播放"
                android:textSize="10sp"/>
            <Button
                android:layout_width="0dp"
                android:layout_height="25dp"
                android:id="@+id/btn_pause"
                android:layout_margin="4dp"
                android:layout_weight="1"
                android:background="@drawable/btn_bg_selector"
                android:text="暂停"
                android:textSize="10sp"/>
            <Button
                android:layout_width="0dp"
                android:layout_height="25dp"
                android:id="@+id/btn_continue_play"
                android:layout_margin="4dp"
                android:layout_weight="1"
                android:background="@drawable/btn_bg_selector"
                android:text="继续"
                android:textSize="10sp"/>
            <Button
                android:layout_width="0dp"
                android:layout_height="25dp"
                android:id="@+id/btn_exit"
                android:layout_margin="4dp"
                android:layout_weight="1"
                android:background="@drawable/btn_bg_selector"
                android:text="退出"
                android:textSize="10sp"/>
        </LinearLayout>
        <ImageView
            android:layout_width="100dp"
            android:layout_height="100dp"
            android:id="@+id/iv_music"
            android:layout_centerVertical="true"
            android:layout_marginLeft="35dp"
            android:layout_marginBottom="50dp"
            android:src="@drawable/img_music"/>
    </RelativeLayout>
</LinearLayout>

编写MusicService

import android.app.Service;
import android.content.Intent;
import android.media.MediaPlayer;
import android.os.Binder;
import android.os.Bundle;
import android.os.IBinder;
import android.os.Message;

import androidx.annotation.Nullable;

import java.util.Timer;
import java.util.TimerTask;

public class MusicService extends Service {
    private MediaPlayer player;
    private Timer timer;
    public MusicService(){
    }
    @Nullable
    @Override
    public IBinder onBind(Intent intent) {
        return new MusicControl();
    }

    @Override
    public void onCreate() {
        super.onCreate();
        player=new MediaPlayer();
    }
    public  void addTimer(){
        if (timer==null){
            timer=new Timer();
            TimerTask task=new TimerTask() {
                @Override
                public void run() {
                    if (player==null)return;
                    int duration=player.getDuration();
                    int currentPosition=player.getCurrentPosition();
                    Message msg=MainActivity.handler.obtainMessage();
                    Bundle bundle=new Bundle();
                    bundle.putInt("duration",duration);
                    bundle.putInt("currentPosition",currentPosition);
                    msg.setData(bundle);
                    MainActivity.handler.sendMessage(msg);
                }
            };
            timer.schedule(task,5,500);
        }
    }
    class MusicControl extends Binder{
        public void play(){
            try{
                player.reset();
                player=MediaPlayer.create(getApplicationContext(),R.raw.music);
                addTimer();
            }catch (Exception e){
                e.printStackTrace();
            }
        }
        public  void pausePlay(){
            player.pause();
        }
        public  void continuePlay(){
            player.start();
        }
        public void seekTo(int progress){
            player.seekTo(progress);
        }

    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        if (player==null)return;
        if (player.isPlaying())player.stop();
        player.release();
        player=null;
    }
}

注意:检查AndroidManifest.xml文件中是否注册了Service

android音乐播放器代码,Android初学者,android,android studio

 android音乐播放器代码,Android初学者,android,android studio

        <service android:name=".MusicService"
            android:enabled="true"
            android:exported="true"/>

编写主界面逻辑代码MainActivity

import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;

import android.animation.ObjectAnimator;
import android.animation.ValueAnimator;
import android.content.ComponentName;
import android.content.Intent;
import android.content.ServiceConnection;
import android.os.Bundle;
import android.os.Handler;
import android.os.IBinder;
import android.os.Message;
import android.view.View;
import android.view.animation.LinearInterpolator;
import android.widget.ImageView;
import android.widget.SeekBar;
import android.widget.TextView;

public class MainActivity extends AppCompatActivity implements View.OnClickListener {

    private static SeekBar sb;
    private static TextView tv_progress,tv_total;
    private ObjectAnimator animator;
    private MusicService.MusicControl musicControl;
    MyServiceConn conn;
    Intent intent;
    private boolean isUnbind=false;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        init();
    }
    private void  init(){
        tv_progress=findViewById(R.id.tv_progress);
        tv_total=findViewById(R.id.tv_total);
        sb=findViewById(R.id.sb);
        findViewById(R.id.btn_play).setOnClickListener(this);
        findViewById(R.id.btn_pause).setOnClickListener(this);
        findViewById(R.id.btn_continue_play).setOnClickListener(this);
        findViewById(R.id.btn_exit).setOnClickListener(this);
        intent=new Intent(this,MusicService.class);
        conn=new MyServiceConn();
        bindService(intent,conn,BIND_AUTO_CREATE);
        sb.setOnSeekBarChangeListener(new SeekBar.OnSeekBarChangeListener() {
            @Override
            public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) {
                if (progress==seekBar.getMax()){
                    animator.pause();
                }
            }


            @Override
            public void onStartTrackingTouch(SeekBar seekBar) {

            }

            @Override
            public void onStopTrackingTouch(SeekBar seekBar) {
                int progress=seekBar.getProgress();
                musicControl.seekTo(progress);
            }
        });
        ImageView iv_music = (ImageView) findViewById(R.id.iv_music);
        animator = ObjectAnimator.ofFloat(iv_music, "rotation", 0f, 360.0f);
        animator.setDuration(10000);  //动画旋转一周的时间为10秒
        animator.setInterpolator(new LinearInterpolator());
        animator.setRepeatCount(-1);  //-1表示设置动画无限循环
    }
    public  static Handler handler=new Handler(){
        @Override
        public void handleMessage(@NonNull Message msg) {
            Bundle bundle=msg.getData();
            int duration=bundle.getInt("duration");
            int currentPosition=bundle.getInt("currentPosition");
            sb.setMax(duration);
            sb.setProgress(currentPosition);
            int minute=duration/1000/60;
            int second=duration/1000%60;
            String strMinute=null;
            String strSecond=null;
            if (minute<10){
                strMinute="0"+minute;
            }else {
                strMinute=minute+"";
            }
            if (second<10){
                strSecond="0"+second;
            }else {
                strSecond=second+"";
            }
            tv_total.setText(strMinute+":"+strSecond);
            minute=currentPosition/1000/60;
            second=currentPosition/1000%60;
            if (minute<10){
                strMinute="0"+minute;
            }else {
                strMinute=minute+"";
            }
            if (second<10){
                strSecond="0"+second;
            }else {
                strSecond=second+"";
            }
            tv_progress.setText(strMinute+":"+strSecond);
            super.handleMessage(msg);
        }
    };
    class MyServiceConn implements ServiceConnection{

        @Override
        public void onServiceConnected(ComponentName name, IBinder service) {
            musicControl= (MusicService.MusicControl) service;
        }

        @Override
        public void onServiceDisconnected(ComponentName name) {

        }
    }
    private void unbind(boolean isUnbind){
        if (!isUnbind){
            musicControl.pausePlay();
            unbindService(conn);
            stopService(intent);
        }
    }
    @Override
    public void onClick(View v) {
        switch (v.getId()){
            case R.id.btn_play:
                musicControl.play();
                animator.start();
                break;
            case R.id.btn_pause:
                musicControl.pausePlay();
                animator.pause();
                break;
            case R.id.btn_continue_play:
                musicControl.continuePlay();
                animator.start();
                break;
            case R.id.btn_exit:
                unbind(isUnbind);
                isUnbind=true;
                finish();
                break;
        }
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        unbind(isUnbind);
    }
}

期末比较繁忙,讲解后续补充,如有问题私信、评论联系文章来源地址https://www.toymoban.com/news/detail-754309.html

到了这里,关于Android Studio初学者实例:仿网易音乐播放器的文章就介绍完了。如果您还想了解更多内容,请在右上角搜索TOY模板网以前的文章或继续浏览下面的相关文章,希望大家以后多多支持TOY模板网!

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处: 如若内容造成侵权/违法违规/事实不符,请点击违法举报进行投诉反馈,一经查实,立即删除!

领支付宝红包 赞助服务器费用

相关文章

  • Android Studio初学者实例:SQLite实验:绿豆通讯录

    本次实验是使用SQLite对一个通讯录表进行简单增删改查 以下是实验效果:  首先是继承SQLiteOpenHelper的数据库自定义类 对于此类必须继承于SQLiteOpenHelper ,当new创造该类的实例的时候会执行创建数据库以及表的操作,例如本代码中数据库名为itcast,数据库表名为informatoin。db

    2024年02月08日
    浏览(36)
  • Android Studio初学者实例:ContentProvider读取手机通讯录

    该实验是通过ContentProvider读取手机通讯录 知识点包含了RecyclerView控件、UriMatcher、ContentResolver 先看效果,显示手机通讯录  首先是界面的布局代码 activity_main59.xml 其次是RecyclerView的item布局代码,其中使用了CardView是为了方便快捷的弄个圆角储来 main59_item.xml 一个联系人的实体

    2024年02月03日
    浏览(36)
  • Android Studio初学者实例:Fragment学习--仿美团外卖界面

    本次课程为Fragment为主题,课程的示例仿美团外卖界面,不同于底部导航栏的Fragment案例,此界面分为左侧切换与顶部切换。本文先是发布代码与效果,后续讲解将会在后续补充。先看看效果: 首先是布局文件代码:Activity布局:activity_main.xml: 首先父布局用的LinearLayout布局,

    2024年02月03日
    浏览(50)
  • git初学者使用教程(包含Android studio中git使用)

    参考博客 git地址 如: 点击创建后会出这个页面 我推荐使用这个部分命令行来设置仓库 在想要创建git仓库的文件夹右键打开Git Bash Here(前提是安装了git) 输入命令(每次输入一句) 3. 右键打开Git设置 在Git中就会出现用户信息(我电脑的Git用户是别人的,我没有修改) 先看

    2024年02月06日
    浏览(34)
  • R语言爬虫实例 初学者自用

    本文记录了使用rvest RSelenium 包进行爬虫与网页渲染的相关知识点及本人的编程操作过程。涉及到基本爬取操作、爬取缺失部分如何处理、操作网页过滤等步骤。 本人非计算机专业,如有措辞不慎敬请提出。 这学期为了凑学分,选了一门R语言的课,才发现R语言远比我们想象

    2024年02月02日
    浏览(33)
  • OpenCV实例解析(OpenCV初学者)

    一、计算机视觉 1.定义:给计算机安装上眼睛(照相机)和大脑(算法),让其能感知周围的环境。它是对生物视觉的一种模拟,通常的做法是通过对采集的图像或视频进行处理来获得相应场景的三维信息。 2.应用: 计算机科学和工程、信号处理、物理学、应用数学和统计学

    2024年02月08日
    浏览(32)
  • 在 Android 中使用 C/C++:初学者综合指南

    Java 作为一种编程语言,具有许多良好的功能,使其成为应用程序开发的首选语言。它独立于平台(因为虚拟机执行)、JIT 编译、多线程支持以及为程序员提供的富有表现力的简单语法。由于其与平台无关的特性,Java 包可以跨 CPU 架构移植,这使得库开发变得更加容易,从而

    2024年03月13日
    浏览(51)
  • Mac安装配置Visual Studio Code(vscode)以及Java环境详细教程(初学者必看)

    原本博主今天想继续给大家出Java接下来的教程,但是就在昨天我在配置vscode的时候遇到了一些问题,Windows系统的小伙伴配置起来肯定很方便,但是在Mac的小伙伴却显得十分无奈,所以我想给大家出一篇Mac的Visual Studio Code配置以及Java环境搭建教程! 博客主页:Jovy.的博客_CSDN博客-领

    2024年02月01日
    浏览(66)
  • 初学者不会写接口怎么办?微软Visual Studio 2022无脑式API接口创建——Swagger一键导入APIKit快速测试

    目录 VsualStudio2022各版本说明 社区版本具体说明 VisualStudio2022下载选项 VisualStudio2022启动样式 VisualStudio2022图标样式 VisualStudio2022初始内存消耗 创建项目ASP.NET Core项目 具体项目创建 编辑项目名称与项目位置 创建配置 创建API控制器 修改路由配置 配置跨域 准备创建接口 创建【

    2024年02月05日
    浏览(35)
  • 守护进程(初学者必备)

    目录 一.进程组和会话 二.守护进程的概念 三.守护线程的特点 四.守护进程创建的基本步骤 1.进程组的相关概念: 进程除了有进程的PID之外还有一个进程组,进程组是由一个进程或者多个进程组成。通常他们与同一作业相关联可以收到同一终端的信号 每个进程组有唯一的进程

    2024年02月08日
    浏览(44)

觉得文章有用就打赏一下文章作者

支付宝扫一扫打赏

博客赞助

微信扫一扫打赏

请作者喝杯咖啡吧~博客赞助

支付宝扫一扫领取红包,优惠每天领

二维码1

领取红包

二维码2

领红包