首先在AndroidManifest.xml 声明server 和网络权限
<service android:name=".Myservice" />
<uses-permission android:name="android.permission.INTERNET" />
直接上代码
activity_main.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
tools:context=".MainActivity">
<Button
android:id="@+id/button"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center"
android:gravity="center"
android:text="播放" />
<Button
android:id="@+id/button2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center"
android:text="暂停" />
<Button
android:id="@+id/button3"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center"
android:text="从暂停开启" />
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:padding="10dp"
android:orientation="horizontal">
<TextView
android:id="@+id/textView"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:gravity="center"
android:textSize="24dp"
android:layout_weight="1"
android:text="00:00" />
<SeekBar
android:id="@+id/seekBar"
android:layout_weight="20"
android:layout_gravity="center"
android:layout_width="wrap_content"
android:layout_height="wrap_content" />
<TextView
android:id="@+id/textView2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textSize="24dp"
android:layout_weight="1"
android:text="00:00" />
</LinearLayout>
</LinearLayout>
MainActivity.java
import androidx.appcompat.app.AppCompatActivity;
import android.annotation.SuppressLint;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.SeekBar;
import android.widget.TextView;
import java.text.DecimalFormat;
public class MainActivity extends AppCompatActivity implements SeekBar.OnSeekBarChangeListener {
private Button button,button2,button3; //分别是新开启音乐,暂停音乐,从暂停状态开启音乐
private MusicBroadsscastRoum musicReceiver; //广播接收(发送歌曲的总时间和当前时间)
private SeekBar seekBar; //进度条
private TextView textView; //显示当前时间
private TextView textView2; //显示总时间
private int tundong=0; //进度的时间
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
initView();
}
private void initView(){
//初始化
button = (Button) findViewById(R.id.button);
button2 = (Button) findViewById(R.id.button2);
button3 = (Button) findViewById(R.id.button3);
seekBar = (SeekBar) findViewById(R.id.seekBar);
textView = (TextView) findViewById(R.id.textView);
textView2 = (TextView)findViewById(R.id.textView2);
//注册广播
musicReceiver = new MusicBroadsscastRoum();
IntentFilter intentFilter = new IntentFilter(Myservice.JINDU);
registerReceiver(musicReceiver, intentFilter);
//新开始音乐
button.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
System.out.println("点击了Button");
Intent intent = new Intent(MainActivity.this, Myservice.class);
startService(intent);
}
});
//暂停音乐
button2.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Log.d("点击了button2","音乐暂停了");
Intent intent = new Intent(MainActivity.this, Myservice.class);
intent.putExtra("TUNDONG_NAME", Myservice.STOP);
startService(intent);
}
});
//从暂停状态开启音乐
button3.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Log.d("点击了Button3","音乐开启了");
Intent intent = new Intent(MainActivity.this, Myservice.class);
intent.putExtra("TUNDONG_NAME", Myservice.PAUSE_START);
intent.putExtra(Myservice.PAUSE_START_VALUES, tundong);
startService(intent);
}
});
//进度条的监听
seekBar.setOnSeekBarChangeListener(this);
}
//seekbar数值改变
@Override
public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) {
tundong = progress;
}
//seekbar开始拖动
@Override
public void onStartTrackingTouch(SeekBar seekBar) {
;Log.d("seekBar","拖动开始!");
}
//seebar结束拖动
//结束拖动后发送进度条当前所在的时间给server
@Override
public void onStopTrackingTouch(SeekBar seekBar) {
Log.d("seekBar","拖动结束!");
Intent intent = new Intent(MainActivity.this, Myservice.class);
intent.putExtra("TUNDONG_NAME", Myservice.TUNDONG_NAME);
intent.putExtra(Myservice.TUNDONG, tundong);
startService(intent);
}
//广播接收
class MusicBroadsscastRoum extends BroadcastReceiver{
@Override
public void onReceive(Context context, Intent intent) {
int duration = intent.getIntExtra(Myservice.DURATION,0); //歌曲总时间
int curr = intent.getIntExtra(Myservice.CURRENPOSITION,0); //歌曲当前时间
seekBar.setMax(duration); //最大值
seekBar.setProgress(curr); //当前值
textView.setText( format(curr));
textView2.setText(format(duration));
}
}
//时间格式化
private static String format(long time){
time = time/1000;
if(time<60){
return "00:" +formatlog("00", time);
}
else {
return formatlog("00", time/60) + ":"+ formatlog("00",time%60);
}
}
//DecimalFormat实现时间格式化
private static String formatlog(String s, long l){
return new DecimalFormat(s).format(l);
}
}
后台服务
Myservice.java
import android.annotation.SuppressLint;
import android.app.Service;
import android.content.Context;
import android.content.Intent;
import android.media.MediaPlayer;
import android.net.Uri;
import android.os.Handler;
import android.os.IBinder;
import android.os.Message;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import java.io.IOException;
public class Myservice extends Service {
private Context context;
//开启音乐
public static final int START = 0x4134;
//开启音乐传值
public static final String START_Value = "START_Value";
//从暂停中启动
public static final int PAUSE_START = 0X333;
//从暂停中传值
public static final String PAUSE_START_VALUES = "PAUSE_START_VALUES";
//进度条接受名
public static final String JINDU = "musicreceiver";
//当前时间接受名
public static final String CURRENPOSITION = "CurrentPosition";
//总时间
public static final String DURATION = "Duration";
//拖动seekbar的值
public static final String TUNDONG = "tundong";
//用于判断是否为seekbar拖动
public static final int TUNDONG_NAME = 1234;
//暂停音乐
public static final int STOP = 123455;
//拖动进度条或者从暂停状态开启歌曲后的当前时间
int dangqianjindu = 0;
//媒体播放器
MediaPlayer mediaPlayer;
@SuppressLint("HandlerLeak")
Handler handler = new Handler(new Handler.Callback() {
@Override
public boolean handleMessage(@NonNull Message msg) {
//传递进度信息
Intent intent = new Intent(JINDU);
//播放的当前位置时间
intent.putExtra(CURRENPOSITION, mediaPlayer.getCurrentPosition());
//音乐的总时间
intent.putExtra(DURATION, mediaPlayer.getDuration());
//发送广播
context.sendBroadcast(intent);
handler.sendEmptyMessageDelayed(1,500);
return false;
}
});
//初始化
public Myservice(){
context = this;
mediaPlayer = new MediaPlayer();
}
@Override
public void onCreate(){
super.onCreate();
}
@Nullable
@Override
public IBinder onBind(Intent intent) {
return null;
}
@Override
public int onStartCommand(Intent intent, int flags, int startId) {
//用于判断是哪个Intent发送的信息
int tundong = intent.getIntExtra("TUNDONG_NAME",0);
//拖动进度条
if(tundong == TUNDONG_NAME){
//接收当前时间
dangqianjindu = intent.getIntExtra(TUNDONG,0);
mediaPlayer.seekTo(dangqianjindu);
handler.sendEmptyMessage(1);
}
//暂停音乐
else if(tundong == STOP){
mediaPlayer.pause();
//结束handler
handler.removeCallbacksAndMessages(null);
}
//从暂停状态开启音乐
else if(tundong == PAUSE_START){
//接收当前时间
dangqianjindu = intent.getIntExtra(PAUSE_START_VALUES,0);
//指定位置播放
mediaPlayer.seekTo(dangqianjindu);
//开启播放
mediaPlayer.start();
//发送一个空消息
handler.sendEmptyMessage(1);
}
//重新开启音乐
else {
try {
//重置播放器
mediaPlayer.reset();
//获取网络资源
mediaPlayer.setDataSource(this, Uri.parse("歌曲地址"));
//资源预备
mediaPlayer.prepare();
//判断是否为拖动
if(tundong == TUNDONG_NAME){
dangqianjindu = intent.getIntExtra(TUNDONG,0);
mediaPlayer.seekTo(dangqianjindu);
handler.sendEmptyMessage(1);
}
//开始播放
mediaPlayer.start();
//发送一个空消息
handler.sendEmptyMessage(1);
} catch (IOException e) {
e.printStackTrace();
}
}
//播放完后监听
mediaPlayer.setOnCompletionListener(new MediaPlayer.OnCompletionListener() {
@Override
public void onCompletion(MediaPlayer mp) {
//重新播放
mediaPlayer.seekTo(0);
mediaPlayer.start();
//结束handler
// handler.removeCallbacksAndMessages(null);
}
});
return super.onStartCommand(intent, flags, startId);
}
}