您现在的位置是:首页 >学无止境 >Android Studio初学者实例:仿网易音乐播放器网站首页学无止境

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

林林要一直努力 2024-10-17 00:01:02
简介Android Studio初学者实例:仿网易音乐播放器

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

看一下效果图

 首先项目准备:

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

 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

 

        <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);
    }
}

期末比较繁忙,讲解后续补充,如有问题私信、评论联系

风语者!平时喜欢研究各种技术,目前在从事后端开发工作,热爱生活、热爱工作。