AndroidStudio实现(service)后台播放音乐(带有进度条)

AndroidStudio实现(service)后台播放音乐(带有进度条)

思路:通过SevericeConnect来实现对audio.java 的mediaplay的调用再在Binder里建立player.的各类方法使得可以在Mainactivity里使用。

首先在res目录下新建一个raw包用来装音乐文件

AndroidStudio实现(service)后台播放音乐(带有进度条)_第1张图片

新建一个.java文件用来实现service

public class Audio extends Service{
   public MediaPlayer player;

    @Nullable
    @Override
    public IBinder onBind(Intent intent) {//可以实现在ManActivity调用MediaPlay的方法
        return new Finder();
    }
   public class  Finder extends Binder {
        public int getDuration(){//获取总进度条
            return player.getDuration();
        }
        public int getCurrentPosition(){//获取当前进度条
            return player.getCurrentPosition();
        }
        public void setProgress(int s){//更改当前音乐进度
            player.seekTo(s);
        }
    }
    public void onCreate(){//创建后台服务
        super.onCreate();
        player =MediaPlayer.create(this,R.raw.mtest);//创建媒体播放对象
        Toast.makeText(this,"创建后台服务...",Toast.LENGTH_SHORT).show();//提示框
    }
    public int onStartCommand(Intent intent,int flags,int startId){//启动后台服务
        super.onStartCommand(intent,flags,startId);
        switch (intent.getIntExtra("play",-1)){
            case 1:
                player.start();//开始
                Toast.makeText(this,"启动后台服务,播放音乐...",Toast.LENGTH_SHORT).show();//提示
                break;
            case 2:
                if (player!=null&&player.isPlaying()){
                  player.pause();//暂停
                  Toast.makeText(this,"暂停...",Toast.LENGTH_SHORT).show();//提示框
                }
                else {
                player.start();//继续
                    Toast.makeText(this,"继续...",Toast.LENGTH_SHORT).show();//提示框
                }
                break;
            case 3:
                player.stop();//停止
                player.release();//释放内存
                Toast.makeText(this,"销毁后台服务...",Toast.LENGTH_SHORT).show();//提示框
                break;
        }

        return START_STICKY;
    }
    @Override
    public void onDestroy() {
       super.onDestroy();
    }
}

在ManActivity.java中实现对seekbar的控制和对service的运用

public class MainActivity extends AppCompatActivity {
    Button btn,btn2,btn3;
    Intent intent;
    SeekBar seekBar;
    TextView textView,textView2;
    MyConnection myConnection;
    Audio.Finder controller;


    public  Handler handler=new Handler(){
        public void handleMessage(Message message){//实时更新进度条
            super.handleMessage(message);
            System.out.println(message.what);
            Update();
            System.out.println(1);//用于检查是否实现
        }
    };


    public void Update(){
        int currentTime=controller.getCurrentPosition();//获取当前进度
        seekBar.setProgress(currentTime);//设置进度条
        textView.setText(formatTime(currentTime));//设置显示时间
        handler.sendEmptyMessageDelayed(0,500);//每隔500ms更新一次
    };

    private String formatTime(int length)//时间转化
    {
        Date date=new Date(length);
        SimpleDateFormat sdf=new SimpleDateFormat("mm:ss");
        String totalTime=sdf.format(date);
        return totalTime;
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        seekBar=(SeekBar)findViewById(R.id.seekBar);
        btn=(Button)findViewById(R.id.button);
        btn3=(Button)findViewById(R.id.button2);
        btn2=(Button)findViewById(R.id.button3);
        intent=new Intent(MainActivity.this,Audio.class);
        btn.setOnClickListener(new mClick());
        btn2.setOnClickListener(new mClick());
        btn3.setOnClickListener(new mClick());
        textView=(TextView)findViewById(R.id.textView) ;
        textView2=(TextView)findViewById(R.id.textView2);
        seekBar.setOnSeekBarChangeListener(new sClick());
    }
     class sClick implements SeekBar.OnSeekBarChangeListener{
         @Override
         public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) {

         }

         @Override
         public void onStartTrackingTouch(SeekBar seekBar) {
         }

         @Override
         public void onStopTrackingTouch(SeekBar seekBar) {//拖动进度条实时监控
               int progress=seekBar.getProgress();//获取当前进度条位置
               seekBar.setProgress(progress);//更新进度条
               controller.setProgress(progress);//更新音乐进度
         }

     }
    class  mClick implements View.OnClickListener{
       public void onClick(View view){
         if(view==btn){//开始
             intent.putExtra("play",1);
             MainActivity.this.startService(intent);//开启服务
             myConnection=new MyConnection();//建立新连接对象
             bindService(intent,myConnection,BIND_AUTO_CREATE);//建立和service连接
         }
         else if(view==btn2){//暂停
             intent.putExtra("play",2);
             MainActivity.this.startService(intent);
             System.out.println(2);

         }
         else if(view==btn3){//结束
             intent.putExtra("play",3);
             MainActivity.this.startService(intent);
       }
       }
    }
       class MyConnection implements ServiceConnection{//控制连接实现mediaPlay的调用
           @Override
           public void onServiceConnected(ComponentName name, IBinder service) {
               controller= (Audio.Finder) service;//获取控制连接对象
               int duration = controller.getDuration();//获取音乐总时长
               textView2.setText(formatTime(duration));//设置总时长
               seekBar.setMax(duration);//设置进度条的最大值
               Update();//提醒进度条更新
           }
           @Override
           public void onServiceDisconnected(ComponentName name) {

           }
       }
    }


AndroidManifest.xml的文件配置

AndroidStudio实现(service)后台播放音乐(带有进度条)_第2张图片

相应的组件设计

<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout 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"
    tools:context=".MainActivity">

    <Button
        android:id="@+id/button"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginStart="136dp"
        android:layout_marginTop="212dp"
        android:text="启动后台音乐服务"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toTopOf="parent" />

    <Button
        android:id="@+id/button2"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginTop="104dp"
        android:text="关闭后台音乐服务"
        app:layout_constraintStart_toStartOf="@+id/button"
        app:layout_constraintTop_toBottomOf="@+id/button" />

    <TextView
        android:id="@+id/textView"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginStart="112dp"
        android:layout_marginTop="100dp"
        android:text="后台音乐服务"
        android:textColor="#03A9F4"
        android:textSize="30sp"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toTopOf="parent" />

    <Button
        android:id="@+id/button3"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginTop="28dp"
        android:text="暂停后台音乐服务"
        app:layout_constraintStart_toStartOf="@+id/button"
        app:layout_constraintTop_toBottomOf="@+id/button" />

    <SeekBar
        android:id="@+id/seekBar"
        android:layout_width="301dp"
        android:layout_height="50dp"
        android:layout_marginStart="52dp"
        android:layout_marginTop="100dp"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toBottomOf="@+id/button2" />

    <TextView
        android:id="@+id/textView2"
        android:layout_width="45dp"
        android:layout_height="40dp"
        app:layout_constraintBottom_toBottomOf="@+id/seekBar"
        app:layout_constraintEnd_toStartOf="@+id/seekBar" />

    <TextView
        android:id="@+id/textView3"
        android:layout_width="50dp"
        android:layout_height="39dp"
        app:layout_constraintBottom_toBottomOf="@+id/seekBar"
        app:layout_constraintStart_toEndOf="@+id/seekBar" />
</androidx.constraintlayout.widget.ConstraintLayout>

AndroidStudio实现(service)后台播放音乐(带有进度条)_第3张图片

你可能感兴趣的:(service)