android music player, adjustable progress bar

1. Extract the method in the service and ask the interface
2. Add a Timer timer to send the current music playback progress to MainActivity. 3. The main thread updates the UI according to the received information 4. Set the monitor setOnSeekBarChangeListener for the SeekBar, and add seekto in the service method (also added in the interface), player.seekto() in the seekto method; call the seekto() method in the Service in the onStopTrackingTouch() method
int duration = player.getDuration();
int currentposition = player.getCurrentPosition();



MainActivity.java

package com.itheima.musicplayer;

import android.content.ComponentName;
import android.content.Intent;
import android.content.ServiceConnection;
import android.os.Handler;
import android.os.IBinder;
import android.os.Message;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.SeekBar;

public class MainActivity extends AppCompatActivity {

    static Handler handler = new Handler(){

        int currentposition;

        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            Bundle bundle = msg.getData();
            int duration = bundle.getInt("duration");
            currentposition = bundle.getInt("currentposition");
            sb.setMax(duration);
            sb.setProgress(currentposition);
        }
    };

    MusicInterface mi;
    private static SeekBar sb;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        sb= (SeekBar) findViewById(R.id.sb);
        sb.setOnSeekBarChangeListener(new 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();
                mi.seekto(progress);
            }
        });
        Intent intent = new Intent(this,PlayerService.class);
        MyServiceConn cnn = new MyServiceConn();

        //混合启动服务
        startService(intent);
        bindService(intent,cnn,BIND_AUTO_CREATE);

    }

    class MyServiceConn implements ServiceConnection{

        @Override
        public void onServiceConnected(ComponentName name, IBinder service) {
            mi = (MusicInterface) service;
        }

        @Override
        public void onServiceDisconnected(ComponentName name) {

        }
    }
    public void play(View v){
        System.out.println("sssss");
        mi.play();
    }
    public void pause(View v){
        mi.pause();
    }
    public void continueplay(View v){
        mi.continueplay();
    }
}

PlayerService.java

package com.itheima.musicplayer;

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

import java.io.IOException;
import java.util.Timer;
import java.util.TimerTask;

public class PlayerService extends Service {
    MediaPlayer player;
    Timer timer;

    public PlayerService() {
    }

    @Override
    public IBinder onBind(Intent intent) {
        // TODO: Return the communication channel to the service.
       // throw new UnsupportedOperationException("Not yet implemented");
        return new MusicController();
    }

    @Override
    public void onCreate() {
        super.onCreate();
        player=new MediaPlayer();
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        player.stop();
        player.release();
        player = null;
        if (timer!=null){
            timer.cancel();
            timer=null;
        }
    }

    class MusicController extends Binder implements MusicInterface{
        public void play(){
            PlayerService.this.play();
        }
        public void pause(){
            PlayerService.this.pause();
        }

        @Override
        public void continueplay() {
            PlayerService.this.continueplay();
        }

        @Override
        public void seekto(int currentposition) {
            PlayerService.this.seekto(currentposition);
        }
    }


    public void seekto(int currentposition){
        player.seekTo(currentposition);
    }


    public void play() {
        System.out.println("播放音乐");

        player.reset();
        try {
//            player.setDataSource("sdcard/heibaizhao.mp3");
//            player.prepare();//准备
//            player.start();
            player.setDataSource("http://10.0.3.2:8080/heibaizhao.mp3");
            System.out.println("连接成功");
            player.prepareAsync();
            player.setOnPreparedListener(new MediaPlayer.OnPreparedListener() {
                @Override
                public void onPrepared(MediaPlayer mp) {
                    System.out.println("加载成功");
                    player.start();
                    addTimer();
                }
            });

        } catch (IOException e) {
            e.printStackTrace();
        }
    }
    public void continueplay(){
        player.start();
    }

    public void pause() {
        System.out.println("暂停");
        player.pause();
    }
    public void addTimer(){

        if(timer==null){

            timer = new Timer();
            timer.schedule(new TimerTask() {
              @Override
                public void run() {
                    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);


                }
            }, 5, 500);
        }
    }
}

musicInterface.java

package com.itheima.musicplayer;

/**
 * Created by Administrator on 2015/12/23.
 */
public interface MusicInterface {
    void play();
    void pause();
    void continueplay();
    void seekto(int currentposition);
}

Layout file activity_main.xml

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent"
    android:layout_height="match_parent" android:paddingLeft="@dimen/activity_horizontal_margin"
    android:paddingRight="@dimen/activity_horizontal_margin"
    android:paddingTop="@dimen/activity_vertical_margin"
    android:paddingBottom="@dimen/activity_vertical_margin"
    android:orientation="vertical"
    tools:context=".MainActivity">

    <Button
        android:id="@+id/play"
        android:onClick="play"
        android:text="开始播放"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content" />
    <Button
        android:id="@+id/pause"
        android:onClick="pause"
        android:text="暂停播放"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content" />
    <Button
        android:id="@+id/continueplay"
        android:onClick="continueplay"
        android:text="继续播放"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content" />
    <SeekBar
        android:id="@+id/sb"
        android:layout_width="match_parent"
        android:layout_height="wrap_content" />

</LinearLayout>

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=325855361&siteId=291194637