浏览代码

<广播文件提前下载到分机本地,解决广播播放不同步问题>

weizhengliang 4 年之前
父节点
当前提交
125c8d4743

+ 5 - 0
app/src/main/java/com/wdkl/callingbed2/common/Constants.java

@@ -1,5 +1,7 @@
 package com.wdkl.callingbed2.common;
 
+import android.os.Environment;
+
 import com.wdkl.callingbed2.ui.InitActivity;
 
 /**
@@ -153,7 +155,10 @@ public class Constants {
     public static final String CALLINGBED_NOTICE = "/WDFJ-I/callingBed_notice.aspx";
     //广播音量大小
     public static final String CALLINGMAINNURSE_BROADCAST_VOL = "/WDHS-I/callingMainNurse_BroadcastVol.aspx";
+    //广播数据
+    public static final String CALLINGMAINNURSE_BROADCAST = "/WDHS-I/callingMainNurse_BroadcastInfo.aspx";
 
+    public static final String BROADCAST_AUDIO_PATH = Environment.getExternalStorageDirectory() + "/BroadcastAudio";
 
     //EventBus 所需判断类型
     public static final int EVENT_UDP = 0x01;

+ 101 - 0
app/src/main/java/com/wdkl/callingbed2/entity/AllBroadcastEntity.java

@@ -0,0 +1,101 @@
+package com.wdkl.callingbed2.entity;
+
+/**
+ * Created by fengxiangqian on 2017/9/28.
+ */
+
+public class AllBroadcastEntity {
+
+    /**
+     * PartitionNo : 0
+     * FileName : 2C4A3C2E0F603123.wma|早上好,
+     * Status : 1
+     * Remarks : 湘乡欢迎您
+     * Weeks : 一,
+     * StartTime : 7:00
+     * IsChecked : false
+     * EndTime : 7:30
+     */
+
+    private String PartitionNo;
+    private String FileName;
+    private String Status;
+    private String Remarks;
+    private String Weeks;
+    private String StartTime;
+    private boolean IsChecked;
+    private String EndTime;
+    private String ID;//播放条目id
+
+    public String getID() {
+        return ID == null ? "0" : ID;
+    }
+
+    public void setID(String ID) {
+        this.ID = ID;
+    }
+
+    public String getPartitionNo() {
+        return PartitionNo == null ? "暂无" : PartitionNo;
+    }
+
+    public void setPartitionNo(String PartitionNo) {
+        this.PartitionNo = PartitionNo;
+    }
+
+    public String getFileName() {
+        return FileName == null ? "" : FileName;
+    }
+
+    public void setFileName(String FileName) {
+        this.FileName = FileName;
+    }
+
+    public String getStatus() {
+        return Status == null ? "1" : Status;
+    }//1:关闭;0:开启
+
+    public void setStatus(String Status) {
+        this.Status = Status;
+    }
+
+    public String getRemarks() {
+        return Remarks == null ? "暂无" : Remarks;
+    }
+
+    public void setRemarks(String Remarks) {
+        this.Remarks = Remarks;
+    }
+
+    public String getWeeks() {
+        return Weeks == null ? "暂无" : Weeks;
+    }
+
+    public void setWeeks(String Weeks) {
+        this.Weeks = Weeks;
+    }
+
+    public String getStartTime() {
+        return StartTime == null ? "暂无" : StartTime;
+    }
+
+    public void setStartTime(String StartTime) {
+        this.StartTime = StartTime;
+    }
+
+    public boolean isIsChecked() {
+        return IsChecked;
+    }
+
+    public void setIsChecked(boolean IsChecked) {
+        this.IsChecked = IsChecked;
+    }
+
+    public String getEndTime() {
+        return EndTime == null ? "暂无" : EndTime;
+    }
+
+    public void setEndTime(String EndTime) {
+        this.EndTime = EndTime;
+    }
+}

+ 149 - 3
app/src/main/java/com/wdkl/callingbed2/ui/CallingBedActivity.java

@@ -52,6 +52,7 @@ import com.wdkl.callingbed2.adapter.DoctorAdapter;
 import com.wdkl.callingbed2.adapter.VersionInfoAdapter;
 import com.wdkl.callingbed2.base.BaseActivity;
 import com.wdkl.callingbed2.common.Constants;
+import com.wdkl.callingbed2.entity.AllBroadcastEntity;
 import com.wdkl.callingbed2.entity.BroadCastEntity;
 import com.wdkl.callingbed2.entity.CostDataEntity;
 import com.wdkl.callingbed2.entity.CostDataEntity.CostArray;
@@ -71,6 +72,7 @@ import com.wdkl.callingbed2.util.BitmapUtils;
 import com.wdkl.callingbed2.util.DateUtil;
 import com.wdkl.callingbed2.util.DensityUtils;
 import com.wdkl.callingbed2.util.DownloadUtil;
+import com.wdkl.callingbed2.util.DownloadUtil2;
 import com.wdkl.callingbed2.util.FullyLinearLayoutManager;
 import com.wdkl.callingbed2.util.LogUtil;
 import com.wdkl.callingbed2.util.MarqueeText;
@@ -97,8 +99,11 @@ import net.frakbot.jumpingbeans.JumpingBeans;
 
 import org.greenrobot.eventbus.Subscribe;
 import org.greenrobot.eventbus.ThreadMode;
+import org.json.JSONArray;
+import org.json.JSONException;
 import org.json.JSONObject;
 
+import java.io.File;
 import java.lang.ref.WeakReference;
 import java.util.ArrayList;
 import java.util.Arrays;
@@ -446,6 +451,7 @@ public class CallingBedActivity extends BaseActivity implements ISerialPortBedOn
     private final int SYSTEM_DATA_ERROR = 2002;
     private final int MAIN_DATA_RESPONSE = 2003;
     private final int MAIN_DATA_ERROR = 2004;
+    private final int UPDATE_BROADCAST = 2005;
     private MyHandler handler = new MyHandler(this);
 
     class MyHandler extends Handler {
@@ -504,6 +510,9 @@ public class CallingBedActivity extends BaseActivity implements ISerialPortBedOn
                         LogUtil.d("NURSELIGHT", "MAIN_DATA_ERROR");
                         getMainData(1);
                         break;
+                    case UPDATE_BROADCAST:
+                        checkAndDownloadMP3(0);
+                        break;
                 }
             } else {
                 // 没有实例不进行操作
@@ -866,6 +875,7 @@ public class CallingBedActivity extends BaseActivity implements ISerialPortBedOn
         getSystemSettingData();
         getNoticeData();
         setTrustIcon();
+        getBroadcastAudioFiles();
         /**
          * 由于机器性能方面的差异有些机子的串口反应速度比较慢;急速初始化将失效!
          * */
@@ -1631,6 +1641,8 @@ public class CallingBedActivity extends BaseActivity implements ISerialPortBedOn
 
     UdpEntity callNoticeEntity;
 
+    private long updateAudioTime = 0;
+
     @Subscribe(threadMode = ThreadMode.MAIN)
     public void onMoonEvent(MessageEvent messageEvent) {
         switch (messageEvent.getType()) {
@@ -1734,6 +1746,13 @@ public class CallingBedActivity extends BaseActivity implements ISerialPortBedOn
             case Constants.EVENT_BROADCAST:
                 BroadCastEntity broadCastEntity = (BroadCastEntity) messageEvent.getMessage();
                 switch (broadCastEntity.getIndexes()) {
+                    case "broadcast_update":
+                        long curTime = System.currentTimeMillis();
+                        if (curTime - updateAudioTime > 10000) {
+                            updateAudioTime = curTime;
+                            getBroadcastAudioFiles();
+                        }
+                        break;
                     case "broadcast_1":
                         boolean isPlay = false;
                         switch (Integer.parseInt(broadCastEntity.getZoneId())) {
@@ -1773,9 +1792,18 @@ public class CallingBedActivity extends BaseActivity implements ISerialPortBedOn
                                 //=====================停止廣播===================//
                                 MediaPlayerManger.getInstance().stopMediaPlayer();
                                 //=====================播放廣播===================//
-                                MediaPlayerManger.getInstance()
-                                        .playMusic(Constants.URL + Constants.URL_END + "/"
-                                                + broadCastEntity.getPath(), this, MediaPlayerManger.PLAY);
+                                String localAudioFile = isLocalAudioExist(broadCastEntity.getPath());
+                                if (localAudioFile != null) {
+                                    LogUtil.d("broadcast", "play local media, url: " + localAudioFile);
+                                    MediaPlayerManger.getInstance()
+                                            .playMusic(localAudioFile, this, MediaPlayerManger.PLAY);
+                                } else {
+                                    LogUtil.d("broadcast", "play stream media, url: " + Constants.URL + Constants.URL_END + "/" + broadCastEntity.getPath());
+                                    MediaPlayerManger.getInstance()
+                                            .playMusic(Constants.URL + Constants.URL_END + "/"
+                                                    + broadCastEntity.getPath(), this, MediaPlayerManger.PLAY);
+                                }
+
                                 if (!SharedPreferencesUtil.getStringSp(this, "SetUpBroadcastVoice", "voice").equals("")) {
                                     float voice = Float.parseFloat(SharedPreferencesUtil.getStringSp(this, "SetUpBroadcastVoice", "voice"));
                                     if (mVolume == 1.0f) {
@@ -2685,5 +2713,123 @@ public class CallingBedActivity extends BaseActivity implements ISerialPortBedOn
 
     /////////////////////////////////////////////////////////////////////////////////////////
 
+    //广播的实体
+    private ArrayList<AllBroadcastEntity> allBroadcastList = new ArrayList<>();
+
+    //下载广播音频文件
+    private void getBroadcastAudioFiles() {
+        if (!StringUtils.notEmpty(Constants.PartID)) return;
+        try {
+            OkHttpUtils.post().url(Constants.URL + Constants.URL_END + Constants.CALLINGMAINNURSE_BROADCAST)
+                    .addParams("PartID", Constants.PartID)
+                    .addParams("PartitionNo", "0")
+                    .build()
+                    .execute(new StringCallback() {
+                        @Override
+                        public void onError(Call call, Exception e, int id) {
+                            LogUtil.d("broadcast", "get broadcast exception: " + e.getMessage());
+                            e.printStackTrace();
+                        }
+
+                        @Override
+                        public void onResponse(String response, int id) {
+                            //去掉 ,OK!
+                            String data = response.substring(0, response.length() - 4);
+                            LogUtil.e("broadcast", response);
+                            try {
+                                JSONObject jsonObj = new JSONObject(data);
+                                if (jsonObj.getString("Code").equals("ERROR!")) {
+                                    LogUtil.w("broadcast", "网络错误");
+                                } else {
+                                    if (jsonObj.getString("Code").equals("OK!")) {
+                                        dealAllBroadcastDatas(jsonObj);
+                                        handler.sendEmptyMessage(UPDATE_BROADCAST);
+                                    } else {
+                                        LogUtil.w("broadcast", "网络错误");
+                                    }
 
+                                }
+                            } catch (JSONException e) {
+                                e.printStackTrace();
+                            }
+                        }
+                    });
+        } catch (Exception e) {
+            e.printStackTrace();
+        }
+    }
+
+    private void dealAllBroadcastDatas(JSONObject jsonObject) {
+        JSONArray jsonArray = null;
+        try {
+            jsonArray = jsonObject.getJSONArray("FileList");
+        } catch (JSONException e) {
+            e.printStackTrace();
+            return;
+        }
+        if (!allBroadcastList.isEmpty()) {
+            allBroadcastList.clear();
+        }
+        for (int i = 0; i < jsonArray.length(); i++) {
+            Gson gson = new Gson();
+            try {
+                JSONObject object = jsonArray.getJSONObject(i);
+                AllBroadcastEntity broadcastEntity = gson.fromJson(object.toString(), AllBroadcastEntity.class);
+                allBroadcastList = getAllBroadcastFileName(broadcastEntity);
+            } catch (JSONException e) {
+                e.printStackTrace();
+            }
+        }
+    }
+
+    private ArrayList<AllBroadcastEntity> getAllBroadcastFileName(AllBroadcastEntity broadcastEntity) {
+        String[] data = broadcastEntity.getFileName().split(",");
+
+        ArrayList<AllBroadcastEntity> list = new ArrayList<>();
+        for (int i = 0; i < data.length; i++) {
+            AllBroadcastEntity entity = new AllBroadcastEntity();
+            String[] mark = data[i].split("\\$");
+            entity.setFileName(mark[0]);
+            if (mark.length > 1) entity.setRemarks(mark[1]);
+            list.add(entity);
+        }
+        return list;
+    }
+
+    private void checkAndDownloadMP3(final int index) {
+        LogUtil.d("broadcast", "checkAndDownloadMP3 start..." + index);
+        if (allBroadcastList != null && allBroadcastList.size() > 0 && index < allBroadcastList.size()) {
+            AllBroadcastEntity entity = allBroadcastList.get(index);
+            String filePath = entity.getFileName();
+            DownloadUtil2.getInstance().download(Constants.URL + Constants.URL_END + "/" + filePath,
+                    Constants.BROADCAST_AUDIO_PATH, filePath.substring(filePath.lastIndexOf("/") + 1), new DownloadUtil2.OnDownloadListener() {
+                        @Override
+                        public void onDownloadSuccess() {
+                            LogUtil.d("broadcast", "download mp3 finish...");
+                            checkAndDownloadMP3(index+1);
+                        }
+
+                        @Override
+                        public void onDownloading(int progress) {
+                            //LogUtil.d("broadcast", "download mp3 progress: " + progress);
+                        }
+
+                        @Override
+                        public void onDownloadFailed() {
+                            LogUtil.d("broadcast", "download mp3 fail...");
+                            checkAndDownloadMP3(index+1);
+                        }
+                    });
+        }
+    }
+
+    private String isLocalAudioExist(String path) {
+        String fileName = path.substring(path.lastIndexOf("/")+1);
+        File file = new File(Constants.BROADCAST_AUDIO_PATH + "/" + fileName);
+        if (file.exists()) {
+            return file.getPath();
+        } else {
+            return null;
+        }
+    }
 }

+ 6 - 0
app/src/main/java/com/wdkl/callingbed2/util/AnalysisUdpUtil.java

@@ -39,6 +39,12 @@ public class AnalysisUdpUtil {
                 }}
 
                 switch (data[0]) {
+                    //更新广播文件
+                    case "broadcast_update":
+                        BroadCastEntity broadCastEntity0 = new BroadCastEntity();
+                        broadCastEntity0.setIndexes(data[0]);
+                        EventBus.getDefault().post(new MessageEvent(broadCastEntity0, Constants.EVENT_BROADCAST));  //将udp发送出去
+                        break;
                     //播放广播
                     case "broadcast_1":
                         if (!Constants.INTIME_BROADCAST.equals(data[1])) {

+ 140 - 0
app/src/main/java/com/wdkl/callingbed2/util/DownloadUtil2.java

@@ -0,0 +1,140 @@
+package com.wdkl.callingbed2.util;
+
+import android.support.annotation.NonNull;
+
+import java.io.File;
+import java.io.FileOutputStream;
+import java.io.IOException;
+import java.io.InputStream;
+
+import okhttp3.Call;
+import okhttp3.Callback;
+import okhttp3.OkHttpClient;
+import okhttp3.Request;
+import okhttp3.Response;
+
+public class DownloadUtil2 {
+    private static final String TAG = "DownloadUtil2";
+    private static DownloadUtil2 downloadUtil2;
+    private final OkHttpClient okHttpClient;
+
+    private DownloadUtil2() {
+        okHttpClient = new OkHttpClient();
+    }
+
+    public static DownloadUtil2 getInstance() {
+        if (downloadUtil2 == null) {
+            synchronized (DownloadUtil.class) {
+                if (downloadUtil2 == null) {
+                    downloadUtil2 = new DownloadUtil2();
+                }
+            }
+        }
+        return downloadUtil2;
+    }
+
+    /**
+     * @param url      下载连接
+     * @param listener 下载监听
+     */
+    public void download(final String url,final String dir, final String name, final OnDownloadListener listener) {
+        final String fileDir = isHaveExistDir(new File(dir), new File(dir + "/" + name));
+        LogUtil.d(TAG, "url==" + url + ", fileDir==" + fileDir);
+        if (fileDir == null) {
+            ToastUtil.showToast("下载文件路径创建失败");
+            return;
+        }
+        Request request = new Request.Builder().url(url).build();
+        okHttpClient.newCall(request).enqueue(new Callback() {
+            @Override
+            public void onFailure(Call call, IOException e) {
+                LogUtil.d(TAG, "onFailure==" + e.toString());
+                listener.onDownloadFailed(); // 下载失败
+            }
+
+            @Override
+            public void onResponse(Call call, Response response) {
+                LogUtil.d(TAG, "response==" + response.body().contentLength());
+                InputStream is = null;
+                byte[] buf = new byte[2048];
+                int len;
+                FileOutputStream fos = null;
+                try {
+                    is = response.body().byteStream();
+                    long total = response.body().contentLength();
+                    File file = new File(fileDir, name);
+                    fos = new FileOutputStream(file);
+                    long sum = 0;
+                    while ((len = is.read(buf)) != -1) {
+                        fos.write(buf, 0, len);
+                        sum = sum + (long) len;
+                        //int progress = (int) (sum * 1.0f / total * 100);
+                        float sp = (float) sum / (float) total;
+                        int progress = (int) (sp * 100);
+                        //LogUtil.d(TAG, "progress==" + progress);
+                        listener.onDownloading(progress);// 下载中
+                    }
+                    fos.flush();
+                    listener.onDownloadSuccess(); // 下载完成
+                } catch (Exception e) {
+                    LogUtil.d(TAG, "Exception==");
+                    listener.onDownloadFailed();
+                } finally {
+                    try {
+                        if (is != null)
+                            is.close();
+                        if (fos != null)
+                            fos.close();
+                    } catch (IOException e) {
+                        LogUtil.d(TAG, "IOException==");
+                    }
+                }
+            }
+        });
+    }
+
+
+    private String isHaveExistDir(File dir, File file) {
+        try {
+            if (!dir.mkdirs()) {
+                dir.createNewFile();
+            }
+            deleteFile(file);//只要文件名相同就可以自动替换(按道理此处不需要了,但为了保险起见还是先执行删除操作)。
+            return dir.getAbsolutePath();
+        } catch (Exception e) {
+            e.printStackTrace();
+        }
+        return null;
+    }
+
+    public boolean deleteFile(File downloadFile) {
+        //if (!downloadFile.isDirectory()) throw new NotHaveThisFileException();
+        return downloadFile.delete();
+    }
+
+    /**
+     * @param url
+     * @return 从下载连接中解析出文件名
+     */
+    @NonNull
+    private String getNameFromUrl(String url) {
+        return url.substring(url.lastIndexOf("/") + 1);
+    }
+
+    public interface OnDownloadListener {
+        /**
+         * 下载成功
+         */
+        void onDownloadSuccess();
+
+        /**
+         * @param progress 下载进度
+         */
+        void onDownloading(int progress);
+
+        /**
+         * 下载失败
+         */
+        void onDownloadFailed();
+    }
+}