23 广播服务结合音乐Demo5

时间:2024-04-10 10:36:04

23 广播服务结合音乐Demo5

MainActivity.java

package com.dmy.demo5;

import android.app.Activity;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.SeekBar;
import android.widget.SeekBar.OnSeekBarChangeListener;
import android.widget.TextView; public class MainActivity extends Activity { private TextView time;
private SeekBar seekBar;
private Button play;
private Button stop;
private BroadcastReceiver receiver;
boolean onTouch =false;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
//初始化控件
init();
} private void init() {
time = (TextView) findViewById(R.id.time);
seekBar = (SeekBar) findViewById(R.id.seek_bar);
play = (Button) findViewById(R.id.play);
stop = (Button) findViewById(R.id.stop);
//为进度条设置监听
seekBar.setOnSeekBarChangeListener(new OnSeekBarChangeListener() { //用户停止进度条操作
@Override
public void onStopTrackingTouch(SeekBar seekBar) {
// TODO Auto-generated method stub
Intent intent = new Intent();
intent.setAction(com.dmy.demo5.Menu.SERVER_INTENT);
//flase意义表示播放音乐 true为暂停
intent.putExtra(com.dmy.demo5.Menu.IS_PAUSE, false);
intent.putExtra(Menu.POS, seekBar.getProgress());
sendBroadcast(intent);
onTouch=false;
}
//用户手指点击点击
@Override
public void onStartTrackingTouch(SeekBar seekBar) {
//给服务发送一个暂停状态过去
Intent intent = new Intent();
intent.setAction(com.dmy.demo5.Menu.SERVER_INTENT);
intent.putExtra(com.dmy.demo5.Menu.IS_PAUSE, true);
//-1表示不改变当前进度
intent.putExtra(com.dmy.demo5.Menu.POS, -1);
onTouch = true;
sendBroadcast(intent);
} @Override
public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) { }
}); receiver = new BroadcastReceiver() { @Override
public void onReceive(Context context, Intent intent) { // 音乐的总长度
int total = intent.getIntExtra(com.dmy.demo5.Menu.TOTAL, 0);
// 音乐当前位置
int pos = intent.getIntExtra(com.dmy.demo5.Menu.POS, 0);
// 音乐总分钟
int totalM = total / 1000 / 60;
// 音乐总分钟剩余秒
int totalS = total / 1000 % 60; // 音乐当前分钟
int posM = pos / 1000 / 60;
// 音乐总分钟剩余秒
int posS = pos / 1000 % 60; StringBuilder sb = new StringBuilder();
sb.append(posM / 10)
.append(posM % 10)
.append(":")
.append(posS / 10)
.append(posS % 10)
.append("/")
.append(totalM / 10).append(totalM % 10).append(":").append(totalS / 10).append(totalS % 10);
time.setText(sb);
seekBar.setMax(total);
if (!onTouch) {
seekBar.setProgress(pos); }
} }; Intent intent = new Intent("com.dmy.demo5.MyServer");
// 6.0需要写上包
intent.setPackage(getPackageName());
// 开启服务
startService(intent); //注册广播
IntentFilter filter = new IntentFilter();
filter.addAction(com.dmy.demo5.Menu.UI_INTENT);
registerReceiver(receiver, filter);
} public void play(View v) {
boolean flag = false;
// 如果当前按钮的内容是暂停则返回true
flag = "暂停".equals(play.getText());
// 给按钮设置新的文字
String newFlag = flag ? "播放" : "暂停";
play.setText(newFlag);
Intent intent = new Intent();
intent.setAction(com.dmy.demo5.Menu.SERVER_INTENT);
intent.putExtra(com.dmy.demo5.Menu.IS_PAUSE, flag);
//-1表示不改变当前进度
intent.putExtra(com.dmy.demo5.Menu.POS, -1);
sendBroadcast(intent);
}
public void stop(View v) { } }

Menu.java

package com.dmy.demo5;

public class Menu {
// 在itent中传入值 boolean如果为true是暂停状态的按钮
public static final String IS_PAUSE = "isPause";
// 判断是否按下停止状态
public static final String IS_STOP = "is_stop";
// 音乐当前位置
public static final String POS = "pos";
// 发送服务广播的意图
public static final String SERVER_INTENT = "updata.music.server";
// 发送UI界面广播的意图
public static final String UI_INTENT = "updata.music.ui";
// 音乐总时长
public static final String TOTAL = "total";
}

MyServer.java

package com.dmy.demo5;

import java.io.IOException;

import android.app.Service;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.media.MediaPlayer;
import android.os.Binder;
import android.os.IBinder;
import android.util.Log; public class MyServer extends Service { private MediaPlayer mp;
int pos = 0;
// 用于接收音乐播放时用户点击按钮和拉动滚动条
private BroadcastReceiver stateReceiver;
boolean flagStop = false; @Override
public void onCreate() {
super.onCreate();
mp = MediaPlayer.create(getApplicationContext(), R.raw.wlxq);
// 初始化广播接受者
initBroadCast();
// 初始化线程不断发送消息 改变UI
initThread();
} // 初始化线程不断发送消息 改变UI
public void initThread() {
new Thread() {
public void run() {
while (true) {
Intent intent = new Intent(Menu.UI_INTENT);
if (mp != null) {
intent.putExtra(Menu.TOTAL, mp.getDuration());
intent.putExtra(Menu.POS, mp.getCurrentPosition());
} if (!flagStop) { sendBroadcast(intent);
} try {
sleep(100);
} catch (InterruptedException e) { e.printStackTrace();
}
}
}; }.start();
} private void initBroadCast() {
stateReceiver = new BroadcastReceiver() { @Override
public void onReceive(Context context, Intent intent) { // 如果为true 现在的状态是用户点击了了暂停按钮
Boolean is_pause = intent.getBooleanExtra(Menu.IS_PAUSE, false);
if (is_pause && mp != null) {
mp.pause();
} else if (mp != null) {
pos = intent.getIntExtra(Menu.POS, -1);
mp.seekTo(pos);
// 否则用户点了播放按钮
mp.start();
}
} };
} @Override
public int onStartCommand(Intent intent, int flags, int startId) {
// 注册广播接受者
IntentFilter intentFilter = new IntentFilter();
intentFilter.addAction("updata.music.server");
registerReceiver(stateReceiver, intentFilter);
Log.e("fmy", "onStartCommand");
return START_NOT_STICKY; } @Override
public IBinder onBind(Intent intent) { return new MyBinder(); } class MyBinder extends Binder {
public MyServer getServer() {
return MyServer.this;
}
} }

清单文件

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.dmy.demo5"
android:versionCode="1"
android:versionName="1.0" > <uses-sdk
android:minSdkVersion="16"
android:targetSdkVersion="21" /> <application
android:allowBackup="true"
android:icon="@drawable/ic_launcher"
android:label="@string/app_name"
android:theme="@style/AppTheme" >
<activity
android:name=".MainActivity"
android:label="@string/app_name" >
<intent-filter>
<action android:name="android.intent.action.MAIN" /> <category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<service android:name="com.dmy.demo5.MyServer">
<intent-filter>
<action android:name="com.dmy.demo5.MyServer"></action>
</intent-filter>
</service>
</application> </manifest>