android四大组件之Service 简单音乐播放器

如果要从service里向activity里发消息,要把handle定义为static这样不管在那里都能获取到了。

private void addTime(){
        Timer timer = new Timer();
        //放在计时器里是为了不断的获取进度
        timer.schedule(new TimerTask() {
            
            @Override
            public void run() {
                //总长度
                int du = mediaPlayer.getDuration();
                //当前进度
                int oo = mediaPlayer.getCurrentPosition();
                Message msg = MainActivity.handler.obtainMessage();
                Bundle bundle = new Bundle();
                bundle.putInt("du",du);
                bundle.putInt("oo",oo);
                msg.setData(bundle);
                MainActivity.handler.sendMessage(msg);
                
            }
            //延迟,更新时间
        }, 5, 500);
        
    }

这里用到了这个计时器类,主要功能就是让这个每个多少秒刷新一次

package com.example.musicplay;

public interface PlayInterface {
    void play();
    void playContiue();
    void pause();
    //设置音乐播放的时间
    void seekTo(int pross);
}
package com.example.musicplay;


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

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

public class PlayService extends Service {
    private MediaPlayer mediaPlayer;
    @Override
    public IBinder onBind(Intent intent) {
        // TODO: Return the communication channel to the service.
        return new MusicBinder();
    }
    class MusicBinder extends Binder implements PlayInterface{

        @Override
        public void play() {
            // TODO Auto-generated method stub
            PlayService.this.play();
        }

        @Override
        public void playContiue() {
            // TODO Auto-generated method stub
            PlayService.this.playContiue();
        }

        @Override
        public void pause() {
            // TODO Auto-generated method stub
            PlayService.this.pause();
            
        }

        @Override
        public void seekTo(int pross) {
            // TODO Auto-generated method stub
            PlayService.this.seekTo(pross);
        }
        
    }
    @Override
    public void onCreate() {
        mediaPlayer = new MediaPlayer();
    }
    
    private void play(){
        //重置
        mediaPlayer.reset();
        try {
            mediaPlayer.setDataSource("sdcard/Charlotte Perrelli - Hero.mp3");
            //准备
            mediaPlayer.prepare();
        } catch (Exception e) {
            // TODO Auto-generated catcssh block
            e.printStackTrace();
        }
        mediaPlayer.setOnPreparedListener(new OnPreparedListener() {
            //准备完毕此方法调用
            @Override
            public void onPrepared(MediaPlayer arg0) {
                // TODO Auto-generated method stub
                mediaPlayer.start();
                addTime();
            }
        });
    }
    private void playContiue(){
        mediaPlayer.start();
    }
    private void pause(){
        mediaPlayer.pause();
    }
    //用seekbar设置音乐的时间
    private void seekTo(int pross){
        mediaPlayer.seekTo(pross);
    }
    private void addTime(){
        Timer timer = new Timer();
        //放在计时器里是为了不断的获取进度
        timer.schedule(new TimerTask() {
            
            @Override
            public void run() {
                //总长度
                int du = mediaPlayer.getDuration();
                //当前进度
                int oo = mediaPlayer.getCurrentPosition();
                Message msg = MainActivity.handler.obtainMessage();
                Bundle bundle = new Bundle();
                bundle.putInt("du",du);
                bundle.putInt("oo",oo);
                msg.setData(bundle);
                MainActivity.handler.sendMessage(msg);
                
            }
            //延迟,更新时间
        }, 5, 500);
        
    }
}
package com.example.musicplay;

import android.os.Bundle;
import android.os.Handler;
import android.os.IBinder;
import android.app.Activity;
import android.content.ComponentName;
import android.content.Intent;
import android.content.ServiceConnection;
import android.view.Menu;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.SeekBar;
import android.widget.TextView;
import android.widget.SeekBar.OnSeekBarChangeListener;

public class MainActivity extends Activity {
    private PlayInterface p;
    static Handler handler = new Handler() {
        public void handleMessage(android.os.Message msg) {
            Bundle bundle = msg.getData();
            int du = bundle.getInt("du");
            int oo = bundle.getInt("oo");
            sb.setMax(du);
            sb.setProgress(oo);
            int mmm = sb.getProgress() / 1000;
            int min = mmm / 60;
            int mm = mmm % 60;
            if (min == 0) {

                show.setText("" + mm);
            } else {
                show.setText(min + ":" + mm);
            }
        };
    };
    private static SeekBar sb;
    private static TextView show;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        sb = (SeekBar) findViewById(R.id.sb);
        show = (TextView) findViewById(R.id.show);
        Intent intent = new Intent(this, PlayService.class);
        startService(intent);
        bindService(intent, new Conn(), BIND_AUTO_CREATE);
        sb.setOnSeekBarChangeListener(new OnSeekBarChangeListener() {

            @Override
            public void onStopTrackingTouch(SeekBar seekbar) {
                // TODO Auto-generated method stub
                p.seekTo(seekbar.getProgress());
            }

            @Override
            public void onStartTrackingTouch(SeekBar arg0) {
                // TODO Auto-generated method stub

            }

            @Override
            public void onProgressChanged(SeekBar arg0, int arg1, boolean arg2) {
                // TODO Auto-generated method stub

            }
        });

        findViewById(R.id.paly).setOnClickListener(new OnClickListener() {

            @Override
            public void onClick(View arg0) {
                p.play();

            }
        });
        findViewById(R.id.contiue).setOnClickListener(new OnClickListener() {

            @Override
            public void onClick(View arg0) {
                p.playContiue();

            }
        });
        findViewById(R.id.pause).setOnClickListener(new OnClickListener() {

            @Override
            public void onClick(View arg0) {
                // TODO Auto-generated method stub
                p.pause();
            }
        });
    }

    class Conn implements ServiceConnection {

        @Override
        public void onServiceConnected(ComponentName arg0, IBinder arg1) {
            // TODO Auto-generated method stub
            p = (PlayInterface) arg1;
        }

        @Override
        public void onServiceDisconnected(ComponentName arg0) {
            // TODO Auto-generated method stub

        }

    }

}
<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:orientation="vertical"
    android:paddingBottom="@dimen/activity_vertical_margin"
    android:paddingLeft="@dimen/activity_horizontal_margin"
    android:paddingRight="@dimen/activity_horizontal_margin"
    android:paddingTop="@dimen/activity_vertical_margin"
    tools:context=".MainActivity" >

    <Button
        android:id="@+id/paly"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="开始播放" />

    <Button
        android:id="@+id/contiue"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="继续播放" />

    <Button
        android:id="@+id/pause"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="暂停播放" />

    <SeekBar
        android:id="@+id/sb"
        android:layout_width="match_parent"
        android:layout_height="wrap_content" />

    <TextView
        android:id="@+id/show"
        android:layout_width="match_parent"
        android:layout_height="wrap_content" />

</LinearLayout>
原文地址:https://www.cnblogs.com/84126858jmz/p/4979068.html